From 0220422dde0633f8c7b66a59c68232db9e83f289 Mon Sep 17 00:00:00 2001 From: Owl Bot Date: Tue, 10 Sep 2024 20:57:21 +0000 Subject: [PATCH] =?UTF-8?q?=F0=9F=A6=89=20Updates=20from=20OwlBot=20post-p?= =?UTF-8?q?rocessor?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit See https://github.com/googleapis/repo-automation-bots/blob/main/packages/owl-bot/README.md --- google/pubsub_v1/types/pubsub.py | 2 +- owl-bot-staging/v1/.coveragerc | 13 - owl-bot-staging/v1/.flake8 | 33 - owl-bot-staging/v1/MANIFEST.in | 2 - owl-bot-staging/v1/README.rst | 49 - owl-bot-staging/v1/docs/_static/custom.css | 3 - owl-bot-staging/v1/docs/conf.py | 376 - owl-bot-staging/v1/docs/index.rst | 7 - .../v1/docs/pubsub_v1/publisher.rst | 10 - .../v1/docs/pubsub_v1/schema_service.rst | 10 - .../v1/docs/pubsub_v1/services_.rst | 8 - .../v1/docs/pubsub_v1/subscriber.rst | 10 - owl-bot-staging/v1/docs/pubsub_v1/types_.rst | 6 - owl-bot-staging/v1/google/pubsub/__init__.py | 163 - .../v1/google/pubsub/gapic_version.py | 16 - owl-bot-staging/v1/google/pubsub/py.typed | 2 - .../v1/google/pubsub_v1/__init__.py | 164 - .../v1/google/pubsub_v1/gapic_metadata.json | 591 - .../v1/google/pubsub_v1/gapic_version.py | 16 - owl-bot-staging/v1/google/pubsub_v1/py.typed | 2 - .../v1/google/pubsub_v1/services/__init__.py | 15 - .../pubsub_v1/services/publisher/__init__.py | 22 - .../services/publisher/async_client.py | 1515 -- .../pubsub_v1/services/publisher/client.py | 1883 --- .../pubsub_v1/services/publisher/pagers.py | 432 - .../services/publisher/transports/__init__.py | 38 - .../services/publisher/transports/base.py | 395 - .../services/publisher/transports/grpc.py | 581 - .../publisher/transports/grpc_asyncio.py | 727 - .../services/publisher/transports/rest.py | 1472 -- .../services/schema_service/__init__.py | 22 - .../services/schema_service/async_client.py | 1629 --- .../services/schema_service/client.py | 1978 --- .../services/schema_service/pagers.py | 297 - .../schema_service/transports/__init__.py | 38 - .../schema_service/transports/base.py | 405 - .../schema_service/transports/grpc.py | 588 - .../schema_service/transports/grpc_asyncio.py | 734 - .../schema_service/transports/rest.py | 1598 -- .../pubsub_v1/services/subscriber/__init__.py | 22 - .../services/subscriber/async_client.py | 2426 --- .../pubsub_v1/services/subscriber/client.py | 2788 ---- .../pubsub_v1/services/subscriber/pagers.py | 297 - .../subscriber/transports/__init__.py | 38 - .../services/subscriber/transports/base.py | 561 - .../services/subscriber/transports/grpc.py | 839 -- .../subscriber/transports/grpc_asyncio.py | 1088 -- .../services/subscriber/transports/rest.py | 2139 --- .../v1/google/pubsub_v1/types/__init__.py | 150 - .../v1/google/pubsub_v1/types/pubsub.py | 2387 --- .../v1/google/pubsub_v1/types/schema.py | 512 - owl-bot-staging/v1/mypy.ini | 3 - owl-bot-staging/v1/noxfile.py | 278 - ..._generated_publisher_create_topic_async.py | 52 - ...1_generated_publisher_create_topic_sync.py | 52 - ..._generated_publisher_delete_topic_async.py | 50 - ...1_generated_publisher_delete_topic_sync.py | 50 - ...ted_publisher_detach_subscription_async.py | 52 - ...ated_publisher_detach_subscription_sync.py | 52 - ..._v1_generated_publisher_get_topic_async.py | 52 - ...b_v1_generated_publisher_get_topic_sync.py | 52 - ...ed_publisher_list_topic_snapshots_async.py | 53 - ...ted_publisher_list_topic_snapshots_sync.py | 53 - ...ublisher_list_topic_subscriptions_async.py | 53 - ...publisher_list_topic_subscriptions_sync.py | 53 - ...1_generated_publisher_list_topics_async.py | 53 - ...v1_generated_publisher_list_topics_sync.py | 53 - ...ub_v1_generated_publisher_publish_async.py | 52 - ...sub_v1_generated_publisher_publish_sync.py | 52 - ..._generated_publisher_update_topic_async.py | 55 - ...1_generated_publisher_update_topic_sync.py | 55 - ...ated_schema_service_commit_schema_async.py | 56 - ...rated_schema_service_commit_schema_sync.py | 56 - ...ated_schema_service_create_schema_async.py | 56 - ...rated_schema_service_create_schema_sync.py | 56 - ...ated_schema_service_delete_schema_async.py | 50 - ...ma_service_delete_schema_revision_async.py | 52 - ...ema_service_delete_schema_revision_sync.py | 52 - ...rated_schema_service_delete_schema_sync.py | 50 - ...nerated_schema_service_get_schema_async.py | 52 - ...enerated_schema_service_get_schema_sync.py | 52 - ...ema_service_list_schema_revisions_async.py | 53 - ...hema_service_list_schema_revisions_sync.py | 53 - ...rated_schema_service_list_schemas_async.py | 53 - ...erated_schema_service_list_schemas_sync.py | 53 - ...ed_schema_service_rollback_schema_async.py | 53 - ...ted_schema_service_rollback_schema_sync.py | 53 - ...d_schema_service_validate_message_async.py | 53 - ...ed_schema_service_validate_message_sync.py | 53 - ...ed_schema_service_validate_schema_async.py | 56 - ...ted_schema_service_validate_schema_sync.py | 56 - ..._generated_subscriber_acknowledge_async.py | 51 - ...1_generated_subscriber_acknowledge_sync.py | 51 - ...erated_subscriber_create_snapshot_async.py | 53 - ...nerated_subscriber_create_snapshot_sync.py | 53 - ...ed_subscriber_create_subscription_async.py | 53 - ...ted_subscriber_create_subscription_sync.py | 53 - ...erated_subscriber_delete_snapshot_async.py | 50 - ...nerated_subscriber_delete_snapshot_sync.py | 50 - ...ed_subscriber_delete_subscription_async.py | 50 - ...ted_subscriber_delete_subscription_sync.py | 50 - ...generated_subscriber_get_snapshot_async.py | 52 - ..._generated_subscriber_get_snapshot_sync.py | 52 - ...rated_subscriber_get_subscription_async.py | 52 - ...erated_subscriber_get_subscription_sync.py | 52 - ...nerated_subscriber_list_snapshots_async.py | 53 - ...enerated_subscriber_list_snapshots_sync.py | 53 - ...ted_subscriber_list_subscriptions_async.py | 53 - ...ated_subscriber_list_subscriptions_sync.py | 53 - ...ed_subscriber_modify_ack_deadline_async.py | 52 - ...ted_subscriber_modify_ack_deadline_sync.py | 52 - ...ted_subscriber_modify_push_config_async.py | 50 - ...ated_subscriber_modify_push_config_sync.py | 50 - ...bsub_v1_generated_subscriber_pull_async.py | 53 - ...ubsub_v1_generated_subscriber_pull_sync.py | 53 - ...bsub_v1_generated_subscriber_seek_async.py | 52 - ...ubsub_v1_generated_subscriber_seek_sync.py | 52 - ...nerated_subscriber_streaming_pull_async.py | 64 - ...enerated_subscriber_streaming_pull_sync.py | 64 - ...erated_subscriber_update_snapshot_async.py | 51 - ...nerated_subscriber_update_snapshot_sync.py | 51 - ...ed_subscriber_update_subscription_async.py | 56 - ...ted_subscriber_update_subscription_sync.py | 56 - .../snippet_metadata_google.pubsub.v1.json | 5736 -------- .../v1/scripts/fixup_pubsub_v1_keywords.py | 213 - owl-bot-staging/v1/setup.py | 94 - .../v1/testing/constraints-3.10.txt | 7 - .../v1/testing/constraints-3.11.txt | 7 - .../v1/testing/constraints-3.12.txt | 7 - .../v1/testing/constraints-3.7.txt | 11 - .../v1/testing/constraints-3.8.txt | 7 - .../v1/testing/constraints-3.9.txt | 7 - owl-bot-staging/v1/tests/__init__.py | 16 - owl-bot-staging/v1/tests/unit/__init__.py | 16 - .../v1/tests/unit/gapic/__init__.py | 16 - .../v1/tests/unit/gapic/pubsub_v1/__init__.py | 16 - .../unit/gapic/pubsub_v1/test_publisher.py | 8402 ----------- .../gapic/pubsub_v1/test_schema_service.py | 8888 ----------- .../unit/gapic/pubsub_v1/test_subscriber.py | 12212 ---------------- .../snippet_metadata_google.pubsub.v1.json | 2 +- 140 files changed, 2 insertions(+), 68737 deletions(-) delete mode 100644 owl-bot-staging/v1/.coveragerc delete mode 100644 owl-bot-staging/v1/.flake8 delete mode 100644 owl-bot-staging/v1/MANIFEST.in delete mode 100644 owl-bot-staging/v1/README.rst delete mode 100644 owl-bot-staging/v1/docs/_static/custom.css delete mode 100644 owl-bot-staging/v1/docs/conf.py delete mode 100644 owl-bot-staging/v1/docs/index.rst delete mode 100644 owl-bot-staging/v1/docs/pubsub_v1/publisher.rst delete mode 100644 owl-bot-staging/v1/docs/pubsub_v1/schema_service.rst delete mode 100644 owl-bot-staging/v1/docs/pubsub_v1/services_.rst delete mode 100644 owl-bot-staging/v1/docs/pubsub_v1/subscriber.rst delete mode 100644 owl-bot-staging/v1/docs/pubsub_v1/types_.rst delete mode 100644 owl-bot-staging/v1/google/pubsub/__init__.py delete mode 100644 owl-bot-staging/v1/google/pubsub/gapic_version.py delete mode 100644 owl-bot-staging/v1/google/pubsub/py.typed delete mode 100644 owl-bot-staging/v1/google/pubsub_v1/__init__.py delete mode 100644 owl-bot-staging/v1/google/pubsub_v1/gapic_metadata.json delete mode 100644 owl-bot-staging/v1/google/pubsub_v1/gapic_version.py delete mode 100644 owl-bot-staging/v1/google/pubsub_v1/py.typed delete mode 100644 owl-bot-staging/v1/google/pubsub_v1/services/__init__.py delete mode 100644 owl-bot-staging/v1/google/pubsub_v1/services/publisher/__init__.py delete mode 100644 owl-bot-staging/v1/google/pubsub_v1/services/publisher/async_client.py delete mode 100644 owl-bot-staging/v1/google/pubsub_v1/services/publisher/client.py delete mode 100644 owl-bot-staging/v1/google/pubsub_v1/services/publisher/pagers.py delete mode 100644 owl-bot-staging/v1/google/pubsub_v1/services/publisher/transports/__init__.py delete mode 100644 owl-bot-staging/v1/google/pubsub_v1/services/publisher/transports/base.py delete mode 100644 owl-bot-staging/v1/google/pubsub_v1/services/publisher/transports/grpc.py delete mode 100644 owl-bot-staging/v1/google/pubsub_v1/services/publisher/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/v1/google/pubsub_v1/services/publisher/transports/rest.py delete mode 100644 owl-bot-staging/v1/google/pubsub_v1/services/schema_service/__init__.py delete mode 100644 owl-bot-staging/v1/google/pubsub_v1/services/schema_service/async_client.py delete mode 100644 owl-bot-staging/v1/google/pubsub_v1/services/schema_service/client.py delete mode 100644 owl-bot-staging/v1/google/pubsub_v1/services/schema_service/pagers.py delete mode 100644 owl-bot-staging/v1/google/pubsub_v1/services/schema_service/transports/__init__.py delete mode 100644 owl-bot-staging/v1/google/pubsub_v1/services/schema_service/transports/base.py delete mode 100644 owl-bot-staging/v1/google/pubsub_v1/services/schema_service/transports/grpc.py delete mode 100644 owl-bot-staging/v1/google/pubsub_v1/services/schema_service/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/v1/google/pubsub_v1/services/schema_service/transports/rest.py delete mode 100644 owl-bot-staging/v1/google/pubsub_v1/services/subscriber/__init__.py delete mode 100644 owl-bot-staging/v1/google/pubsub_v1/services/subscriber/async_client.py delete mode 100644 owl-bot-staging/v1/google/pubsub_v1/services/subscriber/client.py delete mode 100644 owl-bot-staging/v1/google/pubsub_v1/services/subscriber/pagers.py delete mode 100644 owl-bot-staging/v1/google/pubsub_v1/services/subscriber/transports/__init__.py delete mode 100644 owl-bot-staging/v1/google/pubsub_v1/services/subscriber/transports/base.py delete mode 100644 owl-bot-staging/v1/google/pubsub_v1/services/subscriber/transports/grpc.py delete mode 100644 owl-bot-staging/v1/google/pubsub_v1/services/subscriber/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/v1/google/pubsub_v1/services/subscriber/transports/rest.py delete mode 100644 owl-bot-staging/v1/google/pubsub_v1/types/__init__.py delete mode 100644 owl-bot-staging/v1/google/pubsub_v1/types/pubsub.py delete mode 100644 owl-bot-staging/v1/google/pubsub_v1/types/schema.py delete mode 100644 owl-bot-staging/v1/mypy.ini delete mode 100644 owl-bot-staging/v1/noxfile.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/pubsub_v1_generated_publisher_create_topic_async.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/pubsub_v1_generated_publisher_create_topic_sync.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/pubsub_v1_generated_publisher_delete_topic_async.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/pubsub_v1_generated_publisher_delete_topic_sync.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/pubsub_v1_generated_publisher_detach_subscription_async.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/pubsub_v1_generated_publisher_detach_subscription_sync.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/pubsub_v1_generated_publisher_get_topic_async.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/pubsub_v1_generated_publisher_get_topic_sync.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/pubsub_v1_generated_publisher_list_topic_snapshots_async.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/pubsub_v1_generated_publisher_list_topic_snapshots_sync.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/pubsub_v1_generated_publisher_list_topic_subscriptions_async.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/pubsub_v1_generated_publisher_list_topic_subscriptions_sync.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/pubsub_v1_generated_publisher_list_topics_async.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/pubsub_v1_generated_publisher_list_topics_sync.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/pubsub_v1_generated_publisher_publish_async.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/pubsub_v1_generated_publisher_publish_sync.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/pubsub_v1_generated_publisher_update_topic_async.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/pubsub_v1_generated_publisher_update_topic_sync.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/pubsub_v1_generated_schema_service_commit_schema_async.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/pubsub_v1_generated_schema_service_commit_schema_sync.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/pubsub_v1_generated_schema_service_create_schema_async.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/pubsub_v1_generated_schema_service_create_schema_sync.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/pubsub_v1_generated_schema_service_delete_schema_async.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/pubsub_v1_generated_schema_service_delete_schema_revision_async.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/pubsub_v1_generated_schema_service_delete_schema_revision_sync.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/pubsub_v1_generated_schema_service_delete_schema_sync.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/pubsub_v1_generated_schema_service_get_schema_async.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/pubsub_v1_generated_schema_service_get_schema_sync.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/pubsub_v1_generated_schema_service_list_schema_revisions_async.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/pubsub_v1_generated_schema_service_list_schema_revisions_sync.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/pubsub_v1_generated_schema_service_list_schemas_async.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/pubsub_v1_generated_schema_service_list_schemas_sync.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/pubsub_v1_generated_schema_service_rollback_schema_async.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/pubsub_v1_generated_schema_service_rollback_schema_sync.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/pubsub_v1_generated_schema_service_validate_message_async.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/pubsub_v1_generated_schema_service_validate_message_sync.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/pubsub_v1_generated_schema_service_validate_schema_async.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/pubsub_v1_generated_schema_service_validate_schema_sync.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/pubsub_v1_generated_subscriber_acknowledge_async.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/pubsub_v1_generated_subscriber_acknowledge_sync.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/pubsub_v1_generated_subscriber_create_snapshot_async.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/pubsub_v1_generated_subscriber_create_snapshot_sync.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/pubsub_v1_generated_subscriber_create_subscription_async.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/pubsub_v1_generated_subscriber_create_subscription_sync.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/pubsub_v1_generated_subscriber_delete_snapshot_async.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/pubsub_v1_generated_subscriber_delete_snapshot_sync.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/pubsub_v1_generated_subscriber_delete_subscription_async.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/pubsub_v1_generated_subscriber_delete_subscription_sync.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/pubsub_v1_generated_subscriber_get_snapshot_async.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/pubsub_v1_generated_subscriber_get_snapshot_sync.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/pubsub_v1_generated_subscriber_get_subscription_async.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/pubsub_v1_generated_subscriber_get_subscription_sync.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/pubsub_v1_generated_subscriber_list_snapshots_async.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/pubsub_v1_generated_subscriber_list_snapshots_sync.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/pubsub_v1_generated_subscriber_list_subscriptions_async.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/pubsub_v1_generated_subscriber_list_subscriptions_sync.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/pubsub_v1_generated_subscriber_modify_ack_deadline_async.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/pubsub_v1_generated_subscriber_modify_ack_deadline_sync.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/pubsub_v1_generated_subscriber_modify_push_config_async.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/pubsub_v1_generated_subscriber_modify_push_config_sync.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/pubsub_v1_generated_subscriber_pull_async.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/pubsub_v1_generated_subscriber_pull_sync.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/pubsub_v1_generated_subscriber_seek_async.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/pubsub_v1_generated_subscriber_seek_sync.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/pubsub_v1_generated_subscriber_streaming_pull_async.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/pubsub_v1_generated_subscriber_streaming_pull_sync.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/pubsub_v1_generated_subscriber_update_snapshot_async.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/pubsub_v1_generated_subscriber_update_snapshot_sync.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/pubsub_v1_generated_subscriber_update_subscription_async.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/pubsub_v1_generated_subscriber_update_subscription_sync.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/snippet_metadata_google.pubsub.v1.json delete mode 100644 owl-bot-staging/v1/scripts/fixup_pubsub_v1_keywords.py delete mode 100644 owl-bot-staging/v1/setup.py delete mode 100644 owl-bot-staging/v1/testing/constraints-3.10.txt delete mode 100644 owl-bot-staging/v1/testing/constraints-3.11.txt delete mode 100644 owl-bot-staging/v1/testing/constraints-3.12.txt delete mode 100644 owl-bot-staging/v1/testing/constraints-3.7.txt delete mode 100644 owl-bot-staging/v1/testing/constraints-3.8.txt delete mode 100644 owl-bot-staging/v1/testing/constraints-3.9.txt delete mode 100644 owl-bot-staging/v1/tests/__init__.py delete mode 100644 owl-bot-staging/v1/tests/unit/__init__.py delete mode 100644 owl-bot-staging/v1/tests/unit/gapic/__init__.py delete mode 100644 owl-bot-staging/v1/tests/unit/gapic/pubsub_v1/__init__.py delete mode 100644 owl-bot-staging/v1/tests/unit/gapic/pubsub_v1/test_publisher.py delete mode 100644 owl-bot-staging/v1/tests/unit/gapic/pubsub_v1/test_schema_service.py delete mode 100644 owl-bot-staging/v1/tests/unit/gapic/pubsub_v1/test_subscriber.py diff --git a/google/pubsub_v1/types/pubsub.py b/google/pubsub_v1/types/pubsub.py index 5f8266014..1e898c3d3 100644 --- a/google/pubsub_v1/types/pubsub.py +++ b/google/pubsub_v1/types/pubsub.py @@ -821,7 +821,7 @@ class Subscription(proto.Message): published. If ``retain_acked_messages`` is true, then this also configures the retention of acknowledged messages, and thus configures how far back in time a ``Seek`` can be done. - Defaults to 7 days. Cannot be more than 7 days or less than + Defaults to 7 days. Cannot be more than 31 days or less than 10 minutes. labels (MutableMapping[str, str]): Optional. See `Creating and managing diff --git a/owl-bot-staging/v1/.coveragerc b/owl-bot-staging/v1/.coveragerc deleted file mode 100644 index 2416e5fa4..000000000 --- a/owl-bot-staging/v1/.coveragerc +++ /dev/null @@ -1,13 +0,0 @@ -[run] -branch = True - -[report] -show_missing = True -omit = - google/pubsub/__init__.py - google/pubsub/gapic_version.py -exclude_lines = - # Re-enable the standard pragma - pragma: NO COVER - # Ignore debug-only repr - def __repr__ diff --git a/owl-bot-staging/v1/.flake8 b/owl-bot-staging/v1/.flake8 deleted file mode 100644 index 29227d4cf..000000000 --- a/owl-bot-staging/v1/.flake8 +++ /dev/null @@ -1,33 +0,0 @@ -# -*- coding: utf-8 -*- -# -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -# Generated by synthtool. DO NOT EDIT! -[flake8] -ignore = E203, E266, E501, W503 -exclude = - # Exclude generated code. - **/proto/** - **/gapic/** - **/services/** - **/types/** - *_pb2.py - - # Standard linting exemptions. - **/.nox/** - __pycache__, - .git, - *.pyc, - conf.py diff --git a/owl-bot-staging/v1/MANIFEST.in b/owl-bot-staging/v1/MANIFEST.in deleted file mode 100644 index 4daeccbde..000000000 --- a/owl-bot-staging/v1/MANIFEST.in +++ /dev/null @@ -1,2 +0,0 @@ -recursive-include google/pubsub *.py -recursive-include google/pubsub_v1 *.py diff --git a/owl-bot-staging/v1/README.rst b/owl-bot-staging/v1/README.rst deleted file mode 100644 index 4c7897d8f..000000000 --- a/owl-bot-staging/v1/README.rst +++ /dev/null @@ -1,49 +0,0 @@ -Python Client for Google Pubsub 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 Pubsub API. -4. `Setup Authentication.`_ - -.. _Select or create a Cloud Platform project.: https://console.cloud.google.com/project -.. _Enable billing for your project.: https://cloud.google.com/billing/docs/how-to/modify-project#enable_billing_for_a_project -.. _Setup Authentication.: https://googleapis.dev/python/google-api-core/latest/auth.html - -Installation -~~~~~~~~~~~~ - -Install this library in a `virtualenv`_ using pip. `virtualenv`_ is a tool to -create isolated Python environments. The basic problem it addresses is one of -dependencies and versions, and indirectly permissions. - -With `virtualenv`_, it's possible to install this library without needing system -install permissions, and without clashing with the installed system -dependencies. - -.. _`virtualenv`: https://virtualenv.pypa.io/en/latest/ - - -Mac/Linux -^^^^^^^^^ - -.. code-block:: console - - python3 -m venv - source /bin/activate - /bin/pip install /path/to/library - - -Windows -^^^^^^^ - -.. code-block:: console - - python3 -m venv - \Scripts\activate - \Scripts\pip.exe install \path\to\library diff --git a/owl-bot-staging/v1/docs/_static/custom.css b/owl-bot-staging/v1/docs/_static/custom.css deleted file mode 100644 index 06423be0b..000000000 --- a/owl-bot-staging/v1/docs/_static/custom.css +++ /dev/null @@ -1,3 +0,0 @@ -dl.field-list > dt { - min-width: 100px -} diff --git a/owl-bot-staging/v1/docs/conf.py b/owl-bot-staging/v1/docs/conf.py deleted file mode 100644 index a122c8001..000000000 --- a/owl-bot-staging/v1/docs/conf.py +++ /dev/null @@ -1,376 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# -# google-cloud-pubsub documentation build configuration file -# -# This file is execfile()d with the current directory set to its -# containing dir. -# -# Note that not all possible configuration values are present in this -# autogenerated file. -# -# All configuration values have a default; values that are commented out -# serve to show the default. - -import sys -import os -import shlex - -# If extensions (or modules to document with autodoc) are in another directory, -# add these directories to sys.path here. If the directory is relative to the -# documentation root, use os.path.abspath to make it absolute, like shown here. -sys.path.insert(0, os.path.abspath("..")) - -__version__ = "0.1.0" - -# -- General configuration ------------------------------------------------ - -# If your documentation needs a minimal Sphinx version, state it here. -needs_sphinx = "4.0.1" - -# Add any Sphinx extension module names here, as strings. They can be -# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom -# ones. -extensions = [ - "sphinx.ext.autodoc", - "sphinx.ext.autosummary", - "sphinx.ext.intersphinx", - "sphinx.ext.coverage", - "sphinx.ext.napoleon", - "sphinx.ext.todo", - "sphinx.ext.viewcode", -] - -# autodoc/autosummary flags -autoclass_content = "both" -autodoc_default_flags = ["members"] -autosummary_generate = True - - -# Add any paths that contain templates here, relative to this directory. -templates_path = ["_templates"] - -# Allow markdown includes (so releases.md can include CHANGLEOG.md) -# http://www.sphinx-doc.org/en/master/markdown.html -source_parsers = {".md": "recommonmark.parser.CommonMarkParser"} - -# The suffix(es) of source filenames. -# You can specify multiple suffix as a list of string: -source_suffix = [".rst", ".md"] - -# The encoding of source files. -# source_encoding = 'utf-8-sig' - -# The root toctree document. -root_doc = "index" - -# General information about the project. -project = u"google-cloud-pubsub" -copyright = u"2023, Google, LLC" -author = u"Google APIs" # TODO: autogenerate this bit - -# The version info for the project you're documenting, acts as replacement for -# |version| and |release|, also used in various other places throughout the -# built documents. -# -# The full version, including alpha/beta/rc tags. -release = __version__ -# The short X.Y version. -version = ".".join(release.split(".")[0:2]) - -# The language for content autogenerated by Sphinx. Refer to documentation -# for a list of supported languages. -# -# This is also used if you do content translation via gettext catalogs. -# Usually you set "language" from the command line for these cases. -language = 'en' - -# There are two options for replacing |today|: either, you set today to some -# non-false value, then it is used: -# today = '' -# Else, today_fmt is used as the format for a strftime call. -# today_fmt = '%B %d, %Y' - -# List of patterns, relative to source directory, that match files and -# directories to ignore when looking for source files. -exclude_patterns = ["_build"] - -# The reST default role (used for this markup: `text`) to use for all -# documents. -# default_role = None - -# If true, '()' will be appended to :func: etc. cross-reference text. -# add_function_parentheses = True - -# If true, the current module name will be prepended to all description -# unit titles (such as .. function::). -# add_module_names = True - -# If true, sectionauthor and moduleauthor directives will be shown in the -# output. They are ignored by default. -# show_authors = False - -# The name of the Pygments (syntax highlighting) style to use. -pygments_style = "sphinx" - -# A list of ignored prefixes for module index sorting. -# modindex_common_prefix = [] - -# If true, keep warnings as "system message" paragraphs in the built documents. -# keep_warnings = False - -# If true, `todo` and `todoList` produce output, else they produce nothing. -todo_include_todos = True - - -# -- Options for HTML output ---------------------------------------------- - -# The theme to use for HTML and HTML Help pages. See the documentation for -# a list of builtin themes. -html_theme = "alabaster" - -# Theme options are theme-specific and customize the look and feel of a theme -# further. For a list of options available for each theme, see the -# documentation. -html_theme_options = { - "description": "Google Client Libraries for Python", - "github_user": "googleapis", - "github_repo": "google-cloud-python", - "github_banner": True, - "font_family": "'Roboto', Georgia, sans", - "head_font_family": "'Roboto', Georgia, serif", - "code_font_family": "'Roboto Mono', 'Consolas', monospace", -} - -# Add any paths that contain custom themes here, relative to this directory. -# html_theme_path = [] - -# The name for this set of Sphinx documents. If None, it defaults to -# " v documentation". -# html_title = None - -# A shorter title for the navigation bar. Default is the same as html_title. -# html_short_title = None - -# The name of an image file (relative to this directory) to place at the top -# of the sidebar. -# html_logo = None - -# The name of an image file (within the static path) to use as favicon of the -# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 -# pixels large. -# html_favicon = None - -# Add any paths that contain custom static files (such as style sheets) here, -# relative to this directory. They are copied after the builtin static files, -# so a file named "default.css" will overwrite the builtin "default.css". -html_static_path = ["_static"] - -# Add any extra paths that contain custom files (such as robots.txt or -# .htaccess) here, relative to this directory. These files are copied -# directly to the root of the documentation. -# html_extra_path = [] - -# If not '', a 'Last updated on:' timestamp is inserted at every page bottom, -# using the given strftime format. -# html_last_updated_fmt = '%b %d, %Y' - -# If true, SmartyPants will be used to convert quotes and dashes to -# typographically correct entities. -# html_use_smartypants = True - -# Custom sidebar templates, maps document names to template names. -# html_sidebars = {} - -# Additional templates that should be rendered to pages, maps page names to -# template names. -# html_additional_pages = {} - -# If false, no module index is generated. -# html_domain_indices = True - -# If false, no index is generated. -# html_use_index = True - -# If true, the index is split into individual pages for each letter. -# html_split_index = False - -# If true, links to the reST sources are added to the pages. -# html_show_sourcelink = True - -# If true, "Created using Sphinx" is shown in the HTML footer. Default is True. -# html_show_sphinx = True - -# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. -# html_show_copyright = True - -# If true, an OpenSearch description file will be output, and all pages will -# contain a tag referring to it. The value of this option must be the -# base URL from which the finished HTML is served. -# html_use_opensearch = '' - -# This is the file name suffix for HTML files (e.g. ".xhtml"). -# html_file_suffix = None - -# Language to be used for generating the HTML full-text search index. -# Sphinx supports the following languages: -# 'da', 'de', 'en', 'es', 'fi', 'fr', 'hu', 'it', 'ja' -# 'nl', 'no', 'pt', 'ro', 'ru', 'sv', 'tr' -# html_search_language = 'en' - -# A dictionary with options for the search language support, empty by default. -# Now only 'ja' uses this config value -# html_search_options = {'type': 'default'} - -# The name of a javascript file (relative to the configuration directory) that -# implements a search results scorer. If empty, the default will be used. -# html_search_scorer = 'scorer.js' - -# Output file base name for HTML help builder. -htmlhelp_basename = "google-cloud-pubsub-doc" - -# -- Options for warnings ------------------------------------------------------ - - -suppress_warnings = [ - # Temporarily suppress this to avoid "more than one target found for - # cross-reference" warning, which are intractable for us to avoid while in - # a mono-repo. - # See https://github.com/sphinx-doc/sphinx/blob - # /2a65ffeef5c107c19084fabdd706cdff3f52d93c/sphinx/domains/python.py#L843 - "ref.python" -] - -# -- Options for LaTeX output --------------------------------------------- - -latex_elements = { - # The paper size ('letterpaper' or 'a4paper'). - # 'papersize': 'letterpaper', - # The font size ('10pt', '11pt' or '12pt'). - # 'pointsize': '10pt', - # Additional stuff for the LaTeX preamble. - # 'preamble': '', - # Latex figure (float) alignment - # 'figure_align': 'htbp', -} - -# Grouping the document tree into LaTeX files. List of tuples -# (source start file, target name, title, -# author, documentclass [howto, manual, or own class]). -latex_documents = [ - ( - root_doc, - "google-cloud-pubsub.tex", - u"google-cloud-pubsub Documentation", - author, - "manual", - ) -] - -# The name of an image file (relative to this directory) to place at the top of -# the title page. -# latex_logo = None - -# For "manual" documents, if this is true, then toplevel headings are parts, -# not chapters. -# latex_use_parts = False - -# If true, show page references after internal links. -# latex_show_pagerefs = False - -# If true, show URL addresses after external links. -# latex_show_urls = False - -# Documents to append as an appendix to all manuals. -# latex_appendices = [] - -# If false, no module index is generated. -# latex_domain_indices = True - - -# -- Options for manual page output --------------------------------------- - -# One entry per manual page. List of tuples -# (source start file, name, description, authors, manual section). -man_pages = [ - ( - root_doc, - "google-cloud-pubsub", - u"Google Pubsub Documentation", - [author], - 1, - ) -] - -# If true, show URL addresses after external links. -# man_show_urls = False - - -# -- Options for Texinfo output ------------------------------------------- - -# Grouping the document tree into Texinfo files. List of tuples -# (source start file, target name, title, author, -# dir menu entry, description, category) -texinfo_documents = [ - ( - root_doc, - "google-cloud-pubsub", - u"google-cloud-pubsub Documentation", - author, - "google-cloud-pubsub", - "GAPIC library for Google Pubsub API", - "APIs", - ) -] - -# Documents to append as an appendix to all manuals. -# texinfo_appendices = [] - -# If false, no module index is generated. -# texinfo_domain_indices = True - -# How to display URL addresses: 'footnote', 'no', or 'inline'. -# texinfo_show_urls = 'footnote' - -# If true, do not generate a @detailmenu in the "Top" node's menu. -# texinfo_no_detailmenu = False - - -# Example configuration for intersphinx: refer to the Python standard library. -intersphinx_mapping = { - "python": ("http://python.readthedocs.org/en/latest/", None), - "gax": ("https://gax-python.readthedocs.org/en/latest/", None), - "google-auth": ("https://google-auth.readthedocs.io/en/stable", None), - "google-gax": ("https://gax-python.readthedocs.io/en/latest/", None), - "google.api_core": ("https://googleapis.dev/python/google-api-core/latest/", None), - "grpc": ("https://grpc.io/grpc/python/", None), - "requests": ("http://requests.kennethreitz.org/en/stable/", None), - "proto": ("https://proto-plus-python.readthedocs.io/en/stable", None), - "protobuf": ("https://googleapis.dev/python/protobuf/latest/", None), -} - - -# Napoleon settings -napoleon_google_docstring = True -napoleon_numpy_docstring = True -napoleon_include_private_with_doc = False -napoleon_include_special_with_doc = True -napoleon_use_admonition_for_examples = False -napoleon_use_admonition_for_notes = False -napoleon_use_admonition_for_references = False -napoleon_use_ivar = False -napoleon_use_param = True -napoleon_use_rtype = True diff --git a/owl-bot-staging/v1/docs/index.rst b/owl-bot-staging/v1/docs/index.rst deleted file mode 100644 index 5cb0459d0..000000000 --- a/owl-bot-staging/v1/docs/index.rst +++ /dev/null @@ -1,7 +0,0 @@ -API Reference -------------- -.. toctree:: - :maxdepth: 2 - - pubsub_v1/services - pubsub_v1/types diff --git a/owl-bot-staging/v1/docs/pubsub_v1/publisher.rst b/owl-bot-staging/v1/docs/pubsub_v1/publisher.rst deleted file mode 100644 index 0a132656d..000000000 --- a/owl-bot-staging/v1/docs/pubsub_v1/publisher.rst +++ /dev/null @@ -1,10 +0,0 @@ -Publisher ---------------------------- - -.. automodule:: google.pubsub_v1.services.publisher - :members: - :inherited-members: - -.. automodule:: google.pubsub_v1.services.publisher.pagers - :members: - :inherited-members: diff --git a/owl-bot-staging/v1/docs/pubsub_v1/schema_service.rst b/owl-bot-staging/v1/docs/pubsub_v1/schema_service.rst deleted file mode 100644 index 4cb7a0496..000000000 --- a/owl-bot-staging/v1/docs/pubsub_v1/schema_service.rst +++ /dev/null @@ -1,10 +0,0 @@ -SchemaService -------------------------------- - -.. automodule:: google.pubsub_v1.services.schema_service - :members: - :inherited-members: - -.. automodule:: google.pubsub_v1.services.schema_service.pagers - :members: - :inherited-members: diff --git a/owl-bot-staging/v1/docs/pubsub_v1/services_.rst b/owl-bot-staging/v1/docs/pubsub_v1/services_.rst deleted file mode 100644 index 6ab7d9e52..000000000 --- a/owl-bot-staging/v1/docs/pubsub_v1/services_.rst +++ /dev/null @@ -1,8 +0,0 @@ -Services for Google Pubsub v1 API -================================= -.. toctree:: - :maxdepth: 2 - - publisher - schema_service - subscriber diff --git a/owl-bot-staging/v1/docs/pubsub_v1/subscriber.rst b/owl-bot-staging/v1/docs/pubsub_v1/subscriber.rst deleted file mode 100644 index 7f2c74a41..000000000 --- a/owl-bot-staging/v1/docs/pubsub_v1/subscriber.rst +++ /dev/null @@ -1,10 +0,0 @@ -Subscriber ----------------------------- - -.. automodule:: google.pubsub_v1.services.subscriber - :members: - :inherited-members: - -.. automodule:: google.pubsub_v1.services.subscriber.pagers - :members: - :inherited-members: diff --git a/owl-bot-staging/v1/docs/pubsub_v1/types_.rst b/owl-bot-staging/v1/docs/pubsub_v1/types_.rst deleted file mode 100644 index 42d4483a2..000000000 --- a/owl-bot-staging/v1/docs/pubsub_v1/types_.rst +++ /dev/null @@ -1,6 +0,0 @@ -Types for Google Pubsub v1 API -============================== - -.. automodule:: google.pubsub_v1.types - :members: - :show-inheritance: diff --git a/owl-bot-staging/v1/google/pubsub/__init__.py b/owl-bot-staging/v1/google/pubsub/__init__.py deleted file mode 100644 index 0abf9d5bc..000000000 --- a/owl-bot-staging/v1/google/pubsub/__init__.py +++ /dev/null @@ -1,163 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from google.pubsub import gapic_version as package_version - -__version__ = package_version.__version__ - - -from google.pubsub_v1.services.publisher.client import PublisherClient -from google.pubsub_v1.services.publisher.async_client import PublisherAsyncClient -from google.pubsub_v1.services.schema_service.client import SchemaServiceClient -from google.pubsub_v1.services.schema_service.async_client import SchemaServiceAsyncClient -from google.pubsub_v1.services.subscriber.client import SubscriberClient -from google.pubsub_v1.services.subscriber.async_client import SubscriberAsyncClient - -from google.pubsub_v1.types.pubsub import AcknowledgeRequest -from google.pubsub_v1.types.pubsub import BigQueryConfig -from google.pubsub_v1.types.pubsub import CloudStorageConfig -from google.pubsub_v1.types.pubsub import CreateSnapshotRequest -from google.pubsub_v1.types.pubsub import DeadLetterPolicy -from google.pubsub_v1.types.pubsub import DeleteSnapshotRequest -from google.pubsub_v1.types.pubsub import DeleteSubscriptionRequest -from google.pubsub_v1.types.pubsub import DeleteTopicRequest -from google.pubsub_v1.types.pubsub import DetachSubscriptionRequest -from google.pubsub_v1.types.pubsub import DetachSubscriptionResponse -from google.pubsub_v1.types.pubsub import ExpirationPolicy -from google.pubsub_v1.types.pubsub import GetSnapshotRequest -from google.pubsub_v1.types.pubsub import GetSubscriptionRequest -from google.pubsub_v1.types.pubsub import GetTopicRequest -from google.pubsub_v1.types.pubsub import IngestionDataSourceSettings -from google.pubsub_v1.types.pubsub import ListSnapshotsRequest -from google.pubsub_v1.types.pubsub import ListSnapshotsResponse -from google.pubsub_v1.types.pubsub import ListSubscriptionsRequest -from google.pubsub_v1.types.pubsub import ListSubscriptionsResponse -from google.pubsub_v1.types.pubsub import ListTopicSnapshotsRequest -from google.pubsub_v1.types.pubsub import ListTopicSnapshotsResponse -from google.pubsub_v1.types.pubsub import ListTopicsRequest -from google.pubsub_v1.types.pubsub import ListTopicsResponse -from google.pubsub_v1.types.pubsub import ListTopicSubscriptionsRequest -from google.pubsub_v1.types.pubsub import ListTopicSubscriptionsResponse -from google.pubsub_v1.types.pubsub import MessageStoragePolicy -from google.pubsub_v1.types.pubsub import ModifyAckDeadlineRequest -from google.pubsub_v1.types.pubsub import ModifyPushConfigRequest -from google.pubsub_v1.types.pubsub import PublishRequest -from google.pubsub_v1.types.pubsub import PublishResponse -from google.pubsub_v1.types.pubsub import PubsubMessage -from google.pubsub_v1.types.pubsub import PullRequest -from google.pubsub_v1.types.pubsub import PullResponse -from google.pubsub_v1.types.pubsub import PushConfig -from google.pubsub_v1.types.pubsub import ReceivedMessage -from google.pubsub_v1.types.pubsub import RetryPolicy -from google.pubsub_v1.types.pubsub import SchemaSettings -from google.pubsub_v1.types.pubsub import SeekRequest -from google.pubsub_v1.types.pubsub import SeekResponse -from google.pubsub_v1.types.pubsub import Snapshot -from google.pubsub_v1.types.pubsub import StreamingPullRequest -from google.pubsub_v1.types.pubsub import StreamingPullResponse -from google.pubsub_v1.types.pubsub import Subscription -from google.pubsub_v1.types.pubsub import Topic -from google.pubsub_v1.types.pubsub import UpdateSnapshotRequest -from google.pubsub_v1.types.pubsub import UpdateSubscriptionRequest -from google.pubsub_v1.types.pubsub import UpdateTopicRequest -from google.pubsub_v1.types.schema import CommitSchemaRequest -from google.pubsub_v1.types.schema import CreateSchemaRequest -from google.pubsub_v1.types.schema import DeleteSchemaRequest -from google.pubsub_v1.types.schema import DeleteSchemaRevisionRequest -from google.pubsub_v1.types.schema import GetSchemaRequest -from google.pubsub_v1.types.schema import ListSchemaRevisionsRequest -from google.pubsub_v1.types.schema import ListSchemaRevisionsResponse -from google.pubsub_v1.types.schema import ListSchemasRequest -from google.pubsub_v1.types.schema import ListSchemasResponse -from google.pubsub_v1.types.schema import RollbackSchemaRequest -from google.pubsub_v1.types.schema import Schema -from google.pubsub_v1.types.schema import ValidateMessageRequest -from google.pubsub_v1.types.schema import ValidateMessageResponse -from google.pubsub_v1.types.schema import ValidateSchemaRequest -from google.pubsub_v1.types.schema import ValidateSchemaResponse -from google.pubsub_v1.types.schema import Encoding -from google.pubsub_v1.types.schema import SchemaView - -__all__ = ('PublisherClient', - 'PublisherAsyncClient', - 'SchemaServiceClient', - 'SchemaServiceAsyncClient', - 'SubscriberClient', - 'SubscriberAsyncClient', - 'AcknowledgeRequest', - 'BigQueryConfig', - 'CloudStorageConfig', - 'CreateSnapshotRequest', - 'DeadLetterPolicy', - 'DeleteSnapshotRequest', - 'DeleteSubscriptionRequest', - 'DeleteTopicRequest', - 'DetachSubscriptionRequest', - 'DetachSubscriptionResponse', - 'ExpirationPolicy', - 'GetSnapshotRequest', - 'GetSubscriptionRequest', - 'GetTopicRequest', - 'IngestionDataSourceSettings', - 'ListSnapshotsRequest', - 'ListSnapshotsResponse', - 'ListSubscriptionsRequest', - 'ListSubscriptionsResponse', - 'ListTopicSnapshotsRequest', - 'ListTopicSnapshotsResponse', - 'ListTopicsRequest', - 'ListTopicsResponse', - 'ListTopicSubscriptionsRequest', - 'ListTopicSubscriptionsResponse', - 'MessageStoragePolicy', - 'ModifyAckDeadlineRequest', - 'ModifyPushConfigRequest', - 'PublishRequest', - 'PublishResponse', - 'PubsubMessage', - 'PullRequest', - 'PullResponse', - 'PushConfig', - 'ReceivedMessage', - 'RetryPolicy', - 'SchemaSettings', - 'SeekRequest', - 'SeekResponse', - 'Snapshot', - 'StreamingPullRequest', - 'StreamingPullResponse', - 'Subscription', - 'Topic', - 'UpdateSnapshotRequest', - 'UpdateSubscriptionRequest', - 'UpdateTopicRequest', - 'CommitSchemaRequest', - 'CreateSchemaRequest', - 'DeleteSchemaRequest', - 'DeleteSchemaRevisionRequest', - 'GetSchemaRequest', - 'ListSchemaRevisionsRequest', - 'ListSchemaRevisionsResponse', - 'ListSchemasRequest', - 'ListSchemasResponse', - 'RollbackSchemaRequest', - 'Schema', - 'ValidateMessageRequest', - 'ValidateMessageResponse', - 'ValidateSchemaRequest', - 'ValidateSchemaResponse', - 'Encoding', - 'SchemaView', -) diff --git a/owl-bot-staging/v1/google/pubsub/gapic_version.py b/owl-bot-staging/v1/google/pubsub/gapic_version.py deleted file mode 100644 index 558c8aab6..000000000 --- a/owl-bot-staging/v1/google/pubsub/gapic_version.py +++ /dev/null @@ -1,16 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -__version__ = "0.0.0" # {x-release-please-version} diff --git a/owl-bot-staging/v1/google/pubsub/py.typed b/owl-bot-staging/v1/google/pubsub/py.typed deleted file mode 100644 index 1cec9a5ba..000000000 --- a/owl-bot-staging/v1/google/pubsub/py.typed +++ /dev/null @@ -1,2 +0,0 @@ -# Marker file for PEP 561. -# The google-cloud-pubsub package uses inline types. diff --git a/owl-bot-staging/v1/google/pubsub_v1/__init__.py b/owl-bot-staging/v1/google/pubsub_v1/__init__.py deleted file mode 100644 index 40a6021b5..000000000 --- a/owl-bot-staging/v1/google/pubsub_v1/__init__.py +++ /dev/null @@ -1,164 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from google.pubsub_v1 import gapic_version as package_version - -__version__ = package_version.__version__ - - -from .services.publisher import PublisherClient -from .services.publisher import PublisherAsyncClient -from .services.schema_service import SchemaServiceClient -from .services.schema_service import SchemaServiceAsyncClient -from .services.subscriber import SubscriberClient -from .services.subscriber import SubscriberAsyncClient - -from .types.pubsub import AcknowledgeRequest -from .types.pubsub import BigQueryConfig -from .types.pubsub import CloudStorageConfig -from .types.pubsub import CreateSnapshotRequest -from .types.pubsub import DeadLetterPolicy -from .types.pubsub import DeleteSnapshotRequest -from .types.pubsub import DeleteSubscriptionRequest -from .types.pubsub import DeleteTopicRequest -from .types.pubsub import DetachSubscriptionRequest -from .types.pubsub import DetachSubscriptionResponse -from .types.pubsub import ExpirationPolicy -from .types.pubsub import GetSnapshotRequest -from .types.pubsub import GetSubscriptionRequest -from .types.pubsub import GetTopicRequest -from .types.pubsub import IngestionDataSourceSettings -from .types.pubsub import ListSnapshotsRequest -from .types.pubsub import ListSnapshotsResponse -from .types.pubsub import ListSubscriptionsRequest -from .types.pubsub import ListSubscriptionsResponse -from .types.pubsub import ListTopicSnapshotsRequest -from .types.pubsub import ListTopicSnapshotsResponse -from .types.pubsub import ListTopicsRequest -from .types.pubsub import ListTopicsResponse -from .types.pubsub import ListTopicSubscriptionsRequest -from .types.pubsub import ListTopicSubscriptionsResponse -from .types.pubsub import MessageStoragePolicy -from .types.pubsub import ModifyAckDeadlineRequest -from .types.pubsub import ModifyPushConfigRequest -from .types.pubsub import PublishRequest -from .types.pubsub import PublishResponse -from .types.pubsub import PubsubMessage -from .types.pubsub import PullRequest -from .types.pubsub import PullResponse -from .types.pubsub import PushConfig -from .types.pubsub import ReceivedMessage -from .types.pubsub import RetryPolicy -from .types.pubsub import SchemaSettings -from .types.pubsub import SeekRequest -from .types.pubsub import SeekResponse -from .types.pubsub import Snapshot -from .types.pubsub import StreamingPullRequest -from .types.pubsub import StreamingPullResponse -from .types.pubsub import Subscription -from .types.pubsub import Topic -from .types.pubsub import UpdateSnapshotRequest -from .types.pubsub import UpdateSubscriptionRequest -from .types.pubsub import UpdateTopicRequest -from .types.schema import CommitSchemaRequest -from .types.schema import CreateSchemaRequest -from .types.schema import DeleteSchemaRequest -from .types.schema import DeleteSchemaRevisionRequest -from .types.schema import GetSchemaRequest -from .types.schema import ListSchemaRevisionsRequest -from .types.schema import ListSchemaRevisionsResponse -from .types.schema import ListSchemasRequest -from .types.schema import ListSchemasResponse -from .types.schema import RollbackSchemaRequest -from .types.schema import Schema -from .types.schema import ValidateMessageRequest -from .types.schema import ValidateMessageResponse -from .types.schema import ValidateSchemaRequest -from .types.schema import ValidateSchemaResponse -from .types.schema import Encoding -from .types.schema import SchemaView - -__all__ = ( - 'PublisherAsyncClient', - 'SchemaServiceAsyncClient', - 'SubscriberAsyncClient', -'AcknowledgeRequest', -'BigQueryConfig', -'CloudStorageConfig', -'CommitSchemaRequest', -'CreateSchemaRequest', -'CreateSnapshotRequest', -'DeadLetterPolicy', -'DeleteSchemaRequest', -'DeleteSchemaRevisionRequest', -'DeleteSnapshotRequest', -'DeleteSubscriptionRequest', -'DeleteTopicRequest', -'DetachSubscriptionRequest', -'DetachSubscriptionResponse', -'Encoding', -'ExpirationPolicy', -'GetSchemaRequest', -'GetSnapshotRequest', -'GetSubscriptionRequest', -'GetTopicRequest', -'IngestionDataSourceSettings', -'ListSchemaRevisionsRequest', -'ListSchemaRevisionsResponse', -'ListSchemasRequest', -'ListSchemasResponse', -'ListSnapshotsRequest', -'ListSnapshotsResponse', -'ListSubscriptionsRequest', -'ListSubscriptionsResponse', -'ListTopicSnapshotsRequest', -'ListTopicSnapshotsResponse', -'ListTopicSubscriptionsRequest', -'ListTopicSubscriptionsResponse', -'ListTopicsRequest', -'ListTopicsResponse', -'MessageStoragePolicy', -'ModifyAckDeadlineRequest', -'ModifyPushConfigRequest', -'PublishRequest', -'PublishResponse', -'PublisherClient', -'PubsubMessage', -'PullRequest', -'PullResponse', -'PushConfig', -'ReceivedMessage', -'RetryPolicy', -'RollbackSchemaRequest', -'Schema', -'SchemaServiceClient', -'SchemaSettings', -'SchemaView', -'SeekRequest', -'SeekResponse', -'Snapshot', -'StreamingPullRequest', -'StreamingPullResponse', -'SubscriberClient', -'Subscription', -'Topic', -'UpdateSnapshotRequest', -'UpdateSubscriptionRequest', -'UpdateTopicRequest', -'ValidateMessageRequest', -'ValidateMessageResponse', -'ValidateSchemaRequest', -'ValidateSchemaResponse', -) diff --git a/owl-bot-staging/v1/google/pubsub_v1/gapic_metadata.json b/owl-bot-staging/v1/google/pubsub_v1/gapic_metadata.json deleted file mode 100644 index 4a8f51a51..000000000 --- a/owl-bot-staging/v1/google/pubsub_v1/gapic_metadata.json +++ /dev/null @@ -1,591 +0,0 @@ - { - "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", - "language": "python", - "libraryPackage": "google.pubsub_v1", - "protoPackage": "google.pubsub.v1", - "schema": "1.0", - "services": { - "Publisher": { - "clients": { - "grpc": { - "libraryClient": "PublisherClient", - "rpcs": { - "CreateTopic": { - "methods": [ - "create_topic" - ] - }, - "DeleteTopic": { - "methods": [ - "delete_topic" - ] - }, - "DetachSubscription": { - "methods": [ - "detach_subscription" - ] - }, - "GetTopic": { - "methods": [ - "get_topic" - ] - }, - "ListTopicSnapshots": { - "methods": [ - "list_topic_snapshots" - ] - }, - "ListTopicSubscriptions": { - "methods": [ - "list_topic_subscriptions" - ] - }, - "ListTopics": { - "methods": [ - "list_topics" - ] - }, - "Publish": { - "methods": [ - "publish" - ] - }, - "UpdateTopic": { - "methods": [ - "update_topic" - ] - } - } - }, - "grpc-async": { - "libraryClient": "PublisherAsyncClient", - "rpcs": { - "CreateTopic": { - "methods": [ - "create_topic" - ] - }, - "DeleteTopic": { - "methods": [ - "delete_topic" - ] - }, - "DetachSubscription": { - "methods": [ - "detach_subscription" - ] - }, - "GetTopic": { - "methods": [ - "get_topic" - ] - }, - "ListTopicSnapshots": { - "methods": [ - "list_topic_snapshots" - ] - }, - "ListTopicSubscriptions": { - "methods": [ - "list_topic_subscriptions" - ] - }, - "ListTopics": { - "methods": [ - "list_topics" - ] - }, - "Publish": { - "methods": [ - "publish" - ] - }, - "UpdateTopic": { - "methods": [ - "update_topic" - ] - } - } - }, - "rest": { - "libraryClient": "PublisherClient", - "rpcs": { - "CreateTopic": { - "methods": [ - "create_topic" - ] - }, - "DeleteTopic": { - "methods": [ - "delete_topic" - ] - }, - "DetachSubscription": { - "methods": [ - "detach_subscription" - ] - }, - "GetTopic": { - "methods": [ - "get_topic" - ] - }, - "ListTopicSnapshots": { - "methods": [ - "list_topic_snapshots" - ] - }, - "ListTopicSubscriptions": { - "methods": [ - "list_topic_subscriptions" - ] - }, - "ListTopics": { - "methods": [ - "list_topics" - ] - }, - "Publish": { - "methods": [ - "publish" - ] - }, - "UpdateTopic": { - "methods": [ - "update_topic" - ] - } - } - } - } - }, - "SchemaService": { - "clients": { - "grpc": { - "libraryClient": "SchemaServiceClient", - "rpcs": { - "CommitSchema": { - "methods": [ - "commit_schema" - ] - }, - "CreateSchema": { - "methods": [ - "create_schema" - ] - }, - "DeleteSchema": { - "methods": [ - "delete_schema" - ] - }, - "DeleteSchemaRevision": { - "methods": [ - "delete_schema_revision" - ] - }, - "GetSchema": { - "methods": [ - "get_schema" - ] - }, - "ListSchemaRevisions": { - "methods": [ - "list_schema_revisions" - ] - }, - "ListSchemas": { - "methods": [ - "list_schemas" - ] - }, - "RollbackSchema": { - "methods": [ - "rollback_schema" - ] - }, - "ValidateMessage": { - "methods": [ - "validate_message" - ] - }, - "ValidateSchema": { - "methods": [ - "validate_schema" - ] - } - } - }, - "grpc-async": { - "libraryClient": "SchemaServiceAsyncClient", - "rpcs": { - "CommitSchema": { - "methods": [ - "commit_schema" - ] - }, - "CreateSchema": { - "methods": [ - "create_schema" - ] - }, - "DeleteSchema": { - "methods": [ - "delete_schema" - ] - }, - "DeleteSchemaRevision": { - "methods": [ - "delete_schema_revision" - ] - }, - "GetSchema": { - "methods": [ - "get_schema" - ] - }, - "ListSchemaRevisions": { - "methods": [ - "list_schema_revisions" - ] - }, - "ListSchemas": { - "methods": [ - "list_schemas" - ] - }, - "RollbackSchema": { - "methods": [ - "rollback_schema" - ] - }, - "ValidateMessage": { - "methods": [ - "validate_message" - ] - }, - "ValidateSchema": { - "methods": [ - "validate_schema" - ] - } - } - }, - "rest": { - "libraryClient": "SchemaServiceClient", - "rpcs": { - "CommitSchema": { - "methods": [ - "commit_schema" - ] - }, - "CreateSchema": { - "methods": [ - "create_schema" - ] - }, - "DeleteSchema": { - "methods": [ - "delete_schema" - ] - }, - "DeleteSchemaRevision": { - "methods": [ - "delete_schema_revision" - ] - }, - "GetSchema": { - "methods": [ - "get_schema" - ] - }, - "ListSchemaRevisions": { - "methods": [ - "list_schema_revisions" - ] - }, - "ListSchemas": { - "methods": [ - "list_schemas" - ] - }, - "RollbackSchema": { - "methods": [ - "rollback_schema" - ] - }, - "ValidateMessage": { - "methods": [ - "validate_message" - ] - }, - "ValidateSchema": { - "methods": [ - "validate_schema" - ] - } - } - } - } - }, - "Subscriber": { - "clients": { - "grpc": { - "libraryClient": "SubscriberClient", - "rpcs": { - "Acknowledge": { - "methods": [ - "acknowledge" - ] - }, - "CreateSnapshot": { - "methods": [ - "create_snapshot" - ] - }, - "CreateSubscription": { - "methods": [ - "create_subscription" - ] - }, - "DeleteSnapshot": { - "methods": [ - "delete_snapshot" - ] - }, - "DeleteSubscription": { - "methods": [ - "delete_subscription" - ] - }, - "GetSnapshot": { - "methods": [ - "get_snapshot" - ] - }, - "GetSubscription": { - "methods": [ - "get_subscription" - ] - }, - "ListSnapshots": { - "methods": [ - "list_snapshots" - ] - }, - "ListSubscriptions": { - "methods": [ - "list_subscriptions" - ] - }, - "ModifyAckDeadline": { - "methods": [ - "modify_ack_deadline" - ] - }, - "ModifyPushConfig": { - "methods": [ - "modify_push_config" - ] - }, - "Pull": { - "methods": [ - "pull" - ] - }, - "Seek": { - "methods": [ - "seek" - ] - }, - "StreamingPull": { - "methods": [ - "streaming_pull" - ] - }, - "UpdateSnapshot": { - "methods": [ - "update_snapshot" - ] - }, - "UpdateSubscription": { - "methods": [ - "update_subscription" - ] - } - } - }, - "grpc-async": { - "libraryClient": "SubscriberAsyncClient", - "rpcs": { - "Acknowledge": { - "methods": [ - "acknowledge" - ] - }, - "CreateSnapshot": { - "methods": [ - "create_snapshot" - ] - }, - "CreateSubscription": { - "methods": [ - "create_subscription" - ] - }, - "DeleteSnapshot": { - "methods": [ - "delete_snapshot" - ] - }, - "DeleteSubscription": { - "methods": [ - "delete_subscription" - ] - }, - "GetSnapshot": { - "methods": [ - "get_snapshot" - ] - }, - "GetSubscription": { - "methods": [ - "get_subscription" - ] - }, - "ListSnapshots": { - "methods": [ - "list_snapshots" - ] - }, - "ListSubscriptions": { - "methods": [ - "list_subscriptions" - ] - }, - "ModifyAckDeadline": { - "methods": [ - "modify_ack_deadline" - ] - }, - "ModifyPushConfig": { - "methods": [ - "modify_push_config" - ] - }, - "Pull": { - "methods": [ - "pull" - ] - }, - "Seek": { - "methods": [ - "seek" - ] - }, - "StreamingPull": { - "methods": [ - "streaming_pull" - ] - }, - "UpdateSnapshot": { - "methods": [ - "update_snapshot" - ] - }, - "UpdateSubscription": { - "methods": [ - "update_subscription" - ] - } - } - }, - "rest": { - "libraryClient": "SubscriberClient", - "rpcs": { - "Acknowledge": { - "methods": [ - "acknowledge" - ] - }, - "CreateSnapshot": { - "methods": [ - "create_snapshot" - ] - }, - "CreateSubscription": { - "methods": [ - "create_subscription" - ] - }, - "DeleteSnapshot": { - "methods": [ - "delete_snapshot" - ] - }, - "DeleteSubscription": { - "methods": [ - "delete_subscription" - ] - }, - "GetSnapshot": { - "methods": [ - "get_snapshot" - ] - }, - "GetSubscription": { - "methods": [ - "get_subscription" - ] - }, - "ListSnapshots": { - "methods": [ - "list_snapshots" - ] - }, - "ListSubscriptions": { - "methods": [ - "list_subscriptions" - ] - }, - "ModifyAckDeadline": { - "methods": [ - "modify_ack_deadline" - ] - }, - "ModifyPushConfig": { - "methods": [ - "modify_push_config" - ] - }, - "Pull": { - "methods": [ - "pull" - ] - }, - "Seek": { - "methods": [ - "seek" - ] - }, - "StreamingPull": { - "methods": [ - "streaming_pull" - ] - }, - "UpdateSnapshot": { - "methods": [ - "update_snapshot" - ] - }, - "UpdateSubscription": { - "methods": [ - "update_subscription" - ] - } - } - } - } - } - } -} diff --git a/owl-bot-staging/v1/google/pubsub_v1/gapic_version.py b/owl-bot-staging/v1/google/pubsub_v1/gapic_version.py deleted file mode 100644 index 558c8aab6..000000000 --- a/owl-bot-staging/v1/google/pubsub_v1/gapic_version.py +++ /dev/null @@ -1,16 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -__version__ = "0.0.0" # {x-release-please-version} diff --git a/owl-bot-staging/v1/google/pubsub_v1/py.typed b/owl-bot-staging/v1/google/pubsub_v1/py.typed deleted file mode 100644 index 1cec9a5ba..000000000 --- a/owl-bot-staging/v1/google/pubsub_v1/py.typed +++ /dev/null @@ -1,2 +0,0 @@ -# Marker file for PEP 561. -# The google-cloud-pubsub package uses inline types. diff --git a/owl-bot-staging/v1/google/pubsub_v1/services/__init__.py b/owl-bot-staging/v1/google/pubsub_v1/services/__init__.py deleted file mode 100644 index 8f6cf0682..000000000 --- a/owl-bot-staging/v1/google/pubsub_v1/services/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# diff --git a/owl-bot-staging/v1/google/pubsub_v1/services/publisher/__init__.py b/owl-bot-staging/v1/google/pubsub_v1/services/publisher/__init__.py deleted file mode 100644 index 4f8d14c26..000000000 --- a/owl-bot-staging/v1/google/pubsub_v1/services/publisher/__init__.py +++ /dev/null @@ -1,22 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from .client import PublisherClient -from .async_client import PublisherAsyncClient - -__all__ = ( - 'PublisherClient', - 'PublisherAsyncClient', -) diff --git a/owl-bot-staging/v1/google/pubsub_v1/services/publisher/async_client.py b/owl-bot-staging/v1/google/pubsub_v1/services/publisher/async_client.py deleted file mode 100644 index 8c50468e1..000000000 --- a/owl-bot-staging/v1/google/pubsub_v1/services/publisher/async_client.py +++ /dev/null @@ -1,1515 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import re -from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union - -from google.pubsub_v1 import gapic_version as package_version - -from google.api_core.client_options import ClientOptions -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry_async as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - - -try: - OptionalRetry = Union[retries.AsyncRetry, gapic_v1.method._MethodDefault, None] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore - -from google.iam.v1 import iam_policy_pb2 # type: ignore -from google.iam.v1 import policy_pb2 # type: ignore -from google.protobuf import duration_pb2 # type: ignore -from google.protobuf import field_mask_pb2 # type: ignore -from google.pubsub_v1.services.publisher import pagers -from google.pubsub_v1.types import pubsub -from .transports.base import PublisherTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import PublisherGrpcAsyncIOTransport -from .client import PublisherClient - - -class PublisherAsyncClient: - """The service that an application uses to manipulate topics, - and to send messages to a topic. - """ - - _client: PublisherClient - - # Copy defaults from the synchronous client for use here. - # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. - DEFAULT_ENDPOINT = PublisherClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = PublisherClient.DEFAULT_MTLS_ENDPOINT - _DEFAULT_ENDPOINT_TEMPLATE = PublisherClient._DEFAULT_ENDPOINT_TEMPLATE - _DEFAULT_UNIVERSE = PublisherClient._DEFAULT_UNIVERSE - - schema_path = staticmethod(PublisherClient.schema_path) - parse_schema_path = staticmethod(PublisherClient.parse_schema_path) - subscription_path = staticmethod(PublisherClient.subscription_path) - parse_subscription_path = staticmethod(PublisherClient.parse_subscription_path) - topic_path = staticmethod(PublisherClient.topic_path) - parse_topic_path = staticmethod(PublisherClient.parse_topic_path) - common_billing_account_path = staticmethod(PublisherClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(PublisherClient.parse_common_billing_account_path) - common_folder_path = staticmethod(PublisherClient.common_folder_path) - parse_common_folder_path = staticmethod(PublisherClient.parse_common_folder_path) - common_organization_path = staticmethod(PublisherClient.common_organization_path) - parse_common_organization_path = staticmethod(PublisherClient.parse_common_organization_path) - common_project_path = staticmethod(PublisherClient.common_project_path) - parse_common_project_path = staticmethod(PublisherClient.parse_common_project_path) - common_location_path = staticmethod(PublisherClient.common_location_path) - parse_common_location_path = staticmethod(PublisherClient.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: - PublisherAsyncClient: The constructed client. - """ - return PublisherClient.from_service_account_info.__func__(PublisherAsyncClient, info, *args, **kwargs) # type: ignore - - @classmethod - def from_service_account_file(cls, filename: str, *args, **kwargs): - """Creates an instance of this client using the provided credentials - file. - - Args: - filename (str): The path to the service account private key json - file. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - PublisherAsyncClient: The constructed client. - """ - return PublisherClient.from_service_account_file.__func__(PublisherAsyncClient, filename, *args, **kwargs) # type: ignore - - from_service_account_json = from_service_account_file - - @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[ClientOptions] = None): - """Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variable is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - return PublisherClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore - - @property - def transport(self) -> PublisherTransport: - """Returns the transport used by the client instance. - - Returns: - PublisherTransport: The transport used by the client instance. - """ - return self._client.transport - - @property - def api_endpoint(self): - """Return the API endpoint used by the client instance. - - Returns: - str: The API endpoint used by the client instance. - """ - return self._client._api_endpoint - - @property - def universe_domain(self) -> str: - """Return the universe domain used by the client instance. - - Returns: - str: The universe domain used - by the client instance. - """ - return self._client._universe_domain - - get_transport_class = PublisherClient.get_transport_class - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, PublisherTransport, Callable[..., PublisherTransport]]] = "grpc_asyncio", - client_options: Optional[ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the publisher 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,PublisherTransport,Callable[..., PublisherTransport]]]): - 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 PublisherTransport constructor. - If set to None, a transport is chosen automatically. - client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): - Custom options for the client. - - 1. The ``api_endpoint`` property can be used to override the - default endpoint provided by the client when ``transport`` is - not explicitly provided. Only if this property is not set and - ``transport`` was not explicitly provided, the endpoint is - determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment - variable, which have one of the following values: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto-switch to the - default mTLS endpoint if client certificate is present; this is - the default value). - - 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide a client certificate for mTLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - - 3. The ``universe_domain`` property can be used to override the - default "googleapis.com" universe. Note that ``api_endpoint`` - property still takes precedence; and ``universe_domain`` is - currently not supported for mTLS. - - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - """ - self._client = PublisherClient( - credentials=credentials, - transport=transport, - client_options=client_options, - client_info=client_info, - - ) - - async def create_topic(self, - request: Optional[Union[pubsub.Topic, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pubsub.Topic: - r"""Creates the given topic with the given name. See the [resource - name rules] - (https://cloud.google.com/pubsub/docs/pubsub-basics#resource_names). - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require 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 pubsub_v1 - - async def sample_create_topic(): - # Create a client - client = pubsub_v1.PublisherAsyncClient() - - # Initialize request argument(s) - request = pubsub_v1.Topic( - name="name_value", - ) - - # Make the request - response = await client.create_topic(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.pubsub_v1.types.Topic, dict]]): - The request object. A topic resource. - name (:class:`str`): - Required. The name of the topic. It must have the format - ``"projects/{project}/topics/{topic}"``. ``{topic}`` - must start with a letter, and contain only letters - (``[A-Za-z]``), numbers (``[0-9]``), dashes (``-``), - underscores (``_``), periods (``.``), tildes (``~``), - plus (``+``) or percent signs (``%``). It must be - between 3 and 255 characters in length, and it must not - start with ``"goog"``. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.pubsub_v1.types.Topic: - A topic resource. - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, pubsub.Topic): - request = pubsub.Topic(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - 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.create_topic] - - # Certain 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_topic(self, - request: Optional[Union[pubsub.UpdateTopicRequest, dict]] = None, - *, - topic: Optional[pubsub.Topic] = None, - update_mask: Optional[field_mask_pb2.FieldMask] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pubsub.Topic: - r"""Updates an existing topic by updating the fields - specified in the update mask. Note that certain - properties of a topic are not modifiable. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require 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 pubsub_v1 - - async def sample_update_topic(): - # Create a client - client = pubsub_v1.PublisherAsyncClient() - - # Initialize request argument(s) - topic = pubsub_v1.Topic() - topic.name = "name_value" - - request = pubsub_v1.UpdateTopicRequest( - topic=topic, - ) - - # Make the request - response = await client.update_topic(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.pubsub_v1.types.UpdateTopicRequest, dict]]): - The request object. Request for the UpdateTopic method. - topic (:class:`google.pubsub_v1.types.Topic`): - Required. The updated topic object. - This corresponds to the ``topic`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): - Required. Indicates which fields in the provided topic - to update. Must be specified and non-empty. Note that if - ``update_mask`` contains "message_storage_policy" but - the ``message_storage_policy`` is not set in the - ``topic`` provided above, then the updated value is - determined by the policy configured at the project or - organization level. - - This corresponds to the ``update_mask`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.pubsub_v1.types.Topic: - A topic resource. - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([topic, update_mask]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, pubsub.UpdateTopicRequest): - request = pubsub.UpdateTopicRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if topic is not None: - request.topic = topic - if update_mask is not None: - request.update_mask = update_mask - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.update_topic] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("topic.name", request.topic.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 publish(self, - request: Optional[Union[pubsub.PublishRequest, dict]] = None, - *, - topic: Optional[str] = None, - messages: Optional[MutableSequence[pubsub.PubsubMessage]] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pubsub.PublishResponse: - r"""Adds one or more messages to the topic. Returns ``NOT_FOUND`` if - the topic does not exist. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require 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 pubsub_v1 - - async def sample_publish(): - # Create a client - client = pubsub_v1.PublisherAsyncClient() - - # Initialize request argument(s) - request = pubsub_v1.PublishRequest( - topic="topic_value", - ) - - # Make the request - response = await client.publish(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.pubsub_v1.types.PublishRequest, dict]]): - The request object. Request for the Publish method. - topic (:class:`str`): - Required. The messages in the request will be published - on this topic. Format is - ``projects/{project}/topics/{topic}``. - - This corresponds to the ``topic`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - messages (:class:`MutableSequence[google.pubsub_v1.types.PubsubMessage]`): - Required. The messages to publish. - This corresponds to the ``messages`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.pubsub_v1.types.PublishResponse: - Response for the Publish 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. - has_flattened_params = any([topic, messages]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, pubsub.PublishRequest): - request = pubsub.PublishRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if topic is not None: - request.topic = topic - if messages: - request.messages.extend(messages) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.publish] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("topic", request.topic), - )), - ) - - # 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_topic(self, - request: Optional[Union[pubsub.GetTopicRequest, dict]] = None, - *, - topic: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pubsub.Topic: - r"""Gets the configuration of a topic. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require 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 pubsub_v1 - - async def sample_get_topic(): - # Create a client - client = pubsub_v1.PublisherAsyncClient() - - # Initialize request argument(s) - request = pubsub_v1.GetTopicRequest( - topic="topic_value", - ) - - # Make the request - response = await client.get_topic(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.pubsub_v1.types.GetTopicRequest, dict]]): - The request object. Request for the GetTopic method. - topic (:class:`str`): - Required. The name of the topic to get. Format is - ``projects/{project}/topics/{topic}``. - - This corresponds to the ``topic`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.pubsub_v1.types.Topic: - A topic resource. - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([topic]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, pubsub.GetTopicRequest): - request = pubsub.GetTopicRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if topic is not None: - request.topic = topic - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.get_topic] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("topic", request.topic), - )), - ) - - # 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_topics(self, - request: Optional[Union[pubsub.ListTopicsRequest, dict]] = None, - *, - project: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListTopicsAsyncPager: - r"""Lists matching topics. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require 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 pubsub_v1 - - async def sample_list_topics(): - # Create a client - client = pubsub_v1.PublisherAsyncClient() - - # Initialize request argument(s) - request = pubsub_v1.ListTopicsRequest( - project="project_value", - ) - - # Make the request - page_result = client.list_topics(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.pubsub_v1.types.ListTopicsRequest, dict]]): - The request object. Request for the ``ListTopics`` method. - project (:class:`str`): - Required. The name of the project in which to list - topics. Format is ``projects/{project-id}``. - - This corresponds to the ``project`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.pubsub_v1.services.publisher.pagers.ListTopicsAsyncPager: - Response for the ListTopics method. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([project]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, pubsub.ListTopicsRequest): - request = pubsub.ListTopicsRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if project is not None: - request.project = project - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.list_topics] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("project", request.project), - )), - ) - - # 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.ListTopicsAsyncPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def list_topic_subscriptions(self, - request: Optional[Union[pubsub.ListTopicSubscriptionsRequest, dict]] = None, - *, - topic: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListTopicSubscriptionsAsyncPager: - r"""Lists the names of the attached subscriptions on this - topic. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require 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 pubsub_v1 - - async def sample_list_topic_subscriptions(): - # Create a client - client = pubsub_v1.PublisherAsyncClient() - - # Initialize request argument(s) - request = pubsub_v1.ListTopicSubscriptionsRequest( - topic="topic_value", - ) - - # Make the request - page_result = client.list_topic_subscriptions(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.pubsub_v1.types.ListTopicSubscriptionsRequest, dict]]): - The request object. Request for the ``ListTopicSubscriptions`` method. - topic (:class:`str`): - Required. The name of the topic that subscriptions are - attached to. Format is - ``projects/{project}/topics/{topic}``. - - This corresponds to the ``topic`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.pubsub_v1.services.publisher.pagers.ListTopicSubscriptionsAsyncPager: - Response for the ListTopicSubscriptions method. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([topic]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, pubsub.ListTopicSubscriptionsRequest): - request = pubsub.ListTopicSubscriptionsRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if topic is not None: - request.topic = topic - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.list_topic_subscriptions] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("topic", request.topic), - )), - ) - - # 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.ListTopicSubscriptionsAsyncPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def list_topic_snapshots(self, - request: Optional[Union[pubsub.ListTopicSnapshotsRequest, dict]] = None, - *, - topic: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListTopicSnapshotsAsyncPager: - r"""Lists the names of the snapshots on this topic. Snapshots are - used in - `Seek `__ - operations, which allow you to manage message acknowledgments in - bulk. That is, you can set the acknowledgment state of messages - in an existing subscription to the state captured by a snapshot. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require 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 pubsub_v1 - - async def sample_list_topic_snapshots(): - # Create a client - client = pubsub_v1.PublisherAsyncClient() - - # Initialize request argument(s) - request = pubsub_v1.ListTopicSnapshotsRequest( - topic="topic_value", - ) - - # Make the request - page_result = client.list_topic_snapshots(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.pubsub_v1.types.ListTopicSnapshotsRequest, dict]]): - The request object. Request for the ``ListTopicSnapshots`` method. - topic (:class:`str`): - Required. The name of the topic that snapshots are - attached to. Format is - ``projects/{project}/topics/{topic}``. - - This corresponds to the ``topic`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.pubsub_v1.services.publisher.pagers.ListTopicSnapshotsAsyncPager: - Response for the ListTopicSnapshots method. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([topic]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, pubsub.ListTopicSnapshotsRequest): - request = pubsub.ListTopicSnapshotsRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if topic is not None: - request.topic = topic - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.list_topic_snapshots] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("topic", request.topic), - )), - ) - - # 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.ListTopicSnapshotsAsyncPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def delete_topic(self, - request: Optional[Union[pubsub.DeleteTopicRequest, dict]] = None, - *, - topic: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes the topic with the given name. Returns ``NOT_FOUND`` if - the topic does not exist. After a topic is deleted, a new topic - may be created with the same name; this is an entirely new topic - with none of the old configuration or subscriptions. Existing - subscriptions to this topic are not deleted, but their ``topic`` - field is set to ``_deleted-topic_``. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require 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 pubsub_v1 - - async def sample_delete_topic(): - # Create a client - client = pubsub_v1.PublisherAsyncClient() - - # Initialize request argument(s) - request = pubsub_v1.DeleteTopicRequest( - topic="topic_value", - ) - - # Make the request - await client.delete_topic(request=request) - - Args: - request (Optional[Union[google.pubsub_v1.types.DeleteTopicRequest, dict]]): - The request object. Request for the ``DeleteTopic`` method. - topic (:class:`str`): - Required. Name of the topic to delete. Format is - ``projects/{project}/topics/{topic}``. - - This corresponds to the ``topic`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([topic]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, pubsub.DeleteTopicRequest): - request = pubsub.DeleteTopicRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if topic is not None: - request.topic = topic - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.delete_topic] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("topic", request.topic), - )), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - async def detach_subscription(self, - request: Optional[Union[pubsub.DetachSubscriptionRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pubsub.DetachSubscriptionResponse: - r"""Detaches a subscription from this topic. All messages retained - in the subscription are dropped. Subsequent ``Pull`` and - ``StreamingPull`` requests will return FAILED_PRECONDITION. If - the subscription is a push subscription, pushes to the endpoint - will stop. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require 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 pubsub_v1 - - async def sample_detach_subscription(): - # Create a client - client = pubsub_v1.PublisherAsyncClient() - - # Initialize request argument(s) - request = pubsub_v1.DetachSubscriptionRequest( - subscription="subscription_value", - ) - - # Make the request - response = await client.detach_subscription(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.pubsub_v1.types.DetachSubscriptionRequest, dict]]): - The request object. Request for the DetachSubscription - method. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.pubsub_v1.types.DetachSubscriptionResponse: - Response for the DetachSubscription - method. Reserved for future use. - - """ - # 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, pubsub.DetachSubscriptionRequest): - request = pubsub.DetachSubscriptionRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.detach_subscription] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("subscription", request.subscription), - )), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def set_iam_policy( - self, - request: Optional[iam_policy_pb2.SetIamPolicyRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> policy_pb2.Policy: - r"""Sets the IAM access control policy on the specified function. - - Replaces any existing policy. - - Args: - request (:class:`~.policy_pb2.SetIamPolicyRequest`): - The request object. Request message for `SetIamPolicy` - method. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.policy_pb2.Policy: - Defines an Identity and Access Management (IAM) policy. - It is used to specify access control policies for Cloud - Platform resources. - A ``Policy`` is a collection of ``bindings``. A - ``binding`` binds one or more ``members`` to a single - ``role``. Members can be user accounts, service - accounts, Google groups, and domains (such as G Suite). - A ``role`` is a named list of permissions (defined by - IAM or configured by users). A ``binding`` can - optionally specify a ``condition``, which is a logic - expression that further constrains the role binding - based on attributes about the request and/or target - resource. - - **JSON Example** - - :: - { - "bindings": [ - { - "role": "roles/resourcemanager.organizationAdmin", - "members": [ - "user:mike@example.com", - "group:admins@example.com", - "domain:google.com", - "serviceAccount:my-project-id@appspot.gserviceaccount.com" - ] - }, - { - "role": "roles/resourcemanager.organizationViewer", - "members": ["user:eve@example.com"], - "condition": { - "title": "expirable access", - "description": "Does not grant access after Sep 2020", - "expression": "request.time < - timestamp('2020-10-01T00:00:00.000Z')", - } - } - ] - } - - **YAML Example** - - :: - - bindings: - - members: - - user:mike@example.com - - group:admins@example.com - - domain:google.com - - serviceAccount:my-project-id@appspot.gserviceaccount.com - role: roles/resourcemanager.organizationAdmin - - members: - - user:eve@example.com - role: roles/resourcemanager.organizationViewer - condition: - title: expirable access - description: Does not grant access after Sep 2020 - expression: request.time < timestamp('2020-10-01T00:00:00.000Z') - - For a description of IAM and its features, see the `IAM - developer's - guide `__. - """ - # Create or coerce a protobuf request object. - - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = iam_policy_pb2.SetIamPolicyRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.set_iam_policy, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("resource", request.resource),)), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - async def get_iam_policy( - self, - request: Optional[iam_policy_pb2.GetIamPolicyRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> policy_pb2.Policy: - r"""Gets the IAM access control policy for a function. - - Returns an empty policy if the function exists and does - not have a policy set. - - Args: - request (:class:`~.iam_policy_pb2.GetIamPolicyRequest`): - The request object. Request message for `GetIamPolicy` - method. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.policy_pb2.Policy: - Defines an Identity and Access Management (IAM) policy. - It is used to specify access control policies for Cloud - Platform resources. - A ``Policy`` is a collection of ``bindings``. A - ``binding`` binds one or more ``members`` to a single - ``role``. Members can be user accounts, service - accounts, Google groups, and domains (such as G Suite). - A ``role`` is a named list of permissions (defined by - IAM or configured by users). A ``binding`` can - optionally specify a ``condition``, which is a logic - expression that further constrains the role binding - based on attributes about the request and/or target - resource. - - **JSON Example** - - :: - - { - "bindings": [ - { - "role": "roles/resourcemanager.organizationAdmin", - "members": [ - "user:mike@example.com", - "group:admins@example.com", - "domain:google.com", - "serviceAccount:my-project-id@appspot.gserviceaccount.com" - ] - }, - { - "role": "roles/resourcemanager.organizationViewer", - "members": ["user:eve@example.com"], - "condition": { - "title": "expirable access", - "description": "Does not grant access after Sep 2020", - "expression": "request.time < - timestamp('2020-10-01T00:00:00.000Z')", - } - } - ] - } - - **YAML Example** - - :: - - bindings: - - members: - - user:mike@example.com - - group:admins@example.com - - domain:google.com - - serviceAccount:my-project-id@appspot.gserviceaccount.com - role: roles/resourcemanager.organizationAdmin - - members: - - user:eve@example.com - role: roles/resourcemanager.organizationViewer - condition: - title: expirable access - description: Does not grant access after Sep 2020 - expression: request.time < timestamp('2020-10-01T00:00:00.000Z') - - For a description of IAM and its features, see the `IAM - developer's - guide `__. - """ - # Create or coerce a protobuf request object. - - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = iam_policy_pb2.GetIamPolicyRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.get_iam_policy, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("resource", request.resource),)), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - async def test_iam_permissions( - self, - request: Optional[iam_policy_pb2.TestIamPermissionsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> iam_policy_pb2.TestIamPermissionsResponse: - r"""Tests the specified permissions against the IAM access control - policy for a function. - - If the function does not exist, this will - return an empty set of permissions, not a NOT_FOUND error. - - Args: - request (:class:`~.iam_policy_pb2.TestIamPermissionsRequest`): - The request object. Request message for - `TestIamPermissions` method. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~iam_policy_pb2.PolicyTestIamPermissionsResponse: - Response message for ``TestIamPermissions`` method. - """ - # Create or coerce a protobuf request object. - - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = iam_policy_pb2.TestIamPermissionsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.test_iam_permissions, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("resource", request.resource),)), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - async def __aenter__(self) -> "PublisherAsyncClient": - return self - - async def __aexit__(self, exc_type, exc, tb): - await self.transport.close() - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -__all__ = ( - "PublisherAsyncClient", -) diff --git a/owl-bot-staging/v1/google/pubsub_v1/services/publisher/client.py b/owl-bot-staging/v1/google/pubsub_v1/services/publisher/client.py deleted file mode 100644 index 1847023c4..000000000 --- a/owl-bot-staging/v1/google/pubsub_v1/services/publisher/client.py +++ /dev/null @@ -1,1883 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import os -import re -from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast -import warnings - -from google.pubsub_v1 import gapic_version as package_version - -from google.api_core import client_options as client_options_lib -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport import mtls # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth.exceptions import MutualTLSChannelError # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object, None] # type: ignore - -from google.iam.v1 import iam_policy_pb2 # type: ignore -from google.iam.v1 import policy_pb2 # type: ignore -from google.protobuf import duration_pb2 # type: ignore -from google.protobuf import field_mask_pb2 # type: ignore -from google.pubsub_v1.services.publisher import pagers -from google.pubsub_v1.types import pubsub -from .transports.base import PublisherTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import PublisherGrpcTransport -from .transports.grpc_asyncio import PublisherGrpcAsyncIOTransport -from .transports.rest import PublisherRestTransport - - -class PublisherClientMeta(type): - """Metaclass for the Publisher 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[PublisherTransport]] - _transport_registry["grpc"] = PublisherGrpcTransport - _transport_registry["grpc_asyncio"] = PublisherGrpcAsyncIOTransport - _transport_registry["rest"] = PublisherRestTransport - - def get_transport_class(cls, - label: Optional[str] = None, - ) -> Type[PublisherTransport]: - """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 PublisherClient(metaclass=PublisherClientMeta): - """The service that an application uses to manipulate topics, - and to send messages to a topic. - """ - - @staticmethod - def _get_default_mtls_endpoint(api_endpoint): - """Converts api endpoint to mTLS endpoint. - - Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to - "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. - Args: - api_endpoint (Optional[str]): the api endpoint to convert. - Returns: - str: converted mTLS api endpoint. - """ - if not api_endpoint: - return api_endpoint - - mtls_endpoint_re = re.compile( - r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" - ) - - m = mtls_endpoint_re.match(api_endpoint) - name, mtls, sandbox, googledomain = m.groups() - if mtls or not googledomain: - return api_endpoint - - if sandbox: - return api_endpoint.replace( - "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" - ) - - return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") - - # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. - DEFAULT_ENDPOINT = "pubsub.googleapis.com" - DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore - DEFAULT_ENDPOINT - ) - - _DEFAULT_ENDPOINT_TEMPLATE = "pubsub.{UNIVERSE_DOMAIN}" - _DEFAULT_UNIVERSE = "googleapis.com" - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - Args: - info (dict): The service account private key info. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - PublisherClient: 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: - PublisherClient: 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) -> PublisherTransport: - """Returns the transport used by the client instance. - - Returns: - PublisherTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def schema_path(project: str,schema: str,) -> str: - """Returns a fully-qualified schema string.""" - return "projects/{project}/schemas/{schema}".format(project=project, schema=schema, ) - - @staticmethod - def parse_schema_path(path: str) -> Dict[str,str]: - """Parses a schema path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/schemas/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def subscription_path(project: str,subscription: str,) -> str: - """Returns a fully-qualified subscription string.""" - return "projects/{project}/subscriptions/{subscription}".format(project=project, subscription=subscription, ) - - @staticmethod - def parse_subscription_path(path: str) -> Dict[str,str]: - """Parses a subscription path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/subscriptions/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def topic_path(project: str,topic: str,) -> str: - """Returns a fully-qualified topic string.""" - return "projects/{project}/topics/{topic}".format(project=project, topic=topic, ) - - @staticmethod - def parse_topic_path(path: str) -> Dict[str,str]: - """Parses a topic path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/topics/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_billing_account_path(billing_account: str, ) -> str: - """Returns a fully-qualified billing_account string.""" - return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - - @staticmethod - def parse_common_billing_account_path(path: str) -> Dict[str,str]: - """Parse a billing_account path into its component segments.""" - m = re.match(r"^billingAccounts/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_folder_path(folder: str, ) -> str: - """Returns a fully-qualified folder string.""" - return "folders/{folder}".format(folder=folder, ) - - @staticmethod - def parse_common_folder_path(path: str) -> Dict[str,str]: - """Parse a folder path into its component segments.""" - m = re.match(r"^folders/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_organization_path(organization: str, ) -> str: - """Returns a fully-qualified organization string.""" - return "organizations/{organization}".format(organization=organization, ) - - @staticmethod - def parse_common_organization_path(path: str) -> Dict[str,str]: - """Parse a organization path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_project_path(project: str, ) -> str: - """Returns a fully-qualified project string.""" - return "projects/{project}".format(project=project, ) - - @staticmethod - def parse_common_project_path(path: str) -> Dict[str,str]: - """Parse a project path into its component segments.""" - m = re.match(r"^projects/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_location_path(project: str, location: str, ) -> str: - """Returns a fully-qualified location string.""" - return "projects/{project}/locations/{location}".format(project=project, location=location, ) - - @staticmethod - def parse_common_location_path(path: str) -> Dict[str,str]: - """Parse a location path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): - """Deprecated. Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variable is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - - warnings.warn("get_mtls_endpoint_and_cert_source is deprecated. Use the api_endpoint property instead.", - DeprecationWarning) - if client_options is None: - client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") - use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") - if use_mtls_endpoint not in ("auto", "never", "always"): - raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") - - # Figure out the client cert source to use. - client_cert_source = None - if use_client_cert == "true": - if client_options.client_cert_source: - client_cert_source = client_options.client_cert_source - elif mtls.has_default_client_cert_source(): - client_cert_source = mtls.default_client_cert_source() - - # Figure out which api endpoint to use. - if client_options.api_endpoint is not None: - api_endpoint = client_options.api_endpoint - elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): - api_endpoint = cls.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = cls.DEFAULT_ENDPOINT - - return api_endpoint, client_cert_source - - @staticmethod - def _read_environment_variables(): - """Returns the environment variables used by the client. - - Returns: - Tuple[bool, str, str]: returns the GOOGLE_API_USE_CLIENT_CERTIFICATE, - GOOGLE_API_USE_MTLS_ENDPOINT, and GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variables. - - Raises: - ValueError: If GOOGLE_API_USE_CLIENT_CERTIFICATE is not - any of ["true", "false"]. - google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT - is not any of ["auto", "never", "always"]. - """ - use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false").lower() - use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto").lower() - universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") - if use_mtls_endpoint not in ("auto", "never", "always"): - raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env - - @staticmethod - def _get_client_cert_source(provided_cert_source, use_cert_flag): - """Return the client cert source to be used by the client. - - Args: - provided_cert_source (bytes): The client certificate source provided. - use_cert_flag (bool): A flag indicating whether to use the client certificate. - - Returns: - bytes or None: The client cert source to be used by the client. - """ - client_cert_source = None - if use_cert_flag: - if provided_cert_source: - client_cert_source = provided_cert_source - elif mtls.has_default_client_cert_source(): - client_cert_source = mtls.default_client_cert_source() - return client_cert_source - - @staticmethod - def _get_api_endpoint(api_override, client_cert_source, universe_domain, use_mtls_endpoint): - """Return the API endpoint used by the client. - - Args: - api_override (str): The API endpoint override. If specified, this is always - the return value of this function and the other arguments are not used. - client_cert_source (bytes): The client certificate source used by the client. - universe_domain (str): The universe domain used by the client. - use_mtls_endpoint (str): How to use the mTLS endpoint, which depends also on the other parameters. - Possible values are "always", "auto", or "never". - - Returns: - str: The API endpoint to be used by the client. - """ - if api_override is not None: - api_endpoint = api_override - elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): - _default_universe = PublisherClient._DEFAULT_UNIVERSE - if universe_domain != _default_universe: - raise MutualTLSChannelError(f"mTLS is not supported in any universe other than {_default_universe}.") - api_endpoint = PublisherClient.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = PublisherClient._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 = PublisherClient._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 - - @staticmethod - def _compare_universes(client_universe: str, - credentials: ga_credentials.Credentials) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = PublisherClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError("The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default.") - return True - - 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. - """ - self._is_universe_domain_valid = (self._is_universe_domain_valid or - PublisherClient._compare_universes(self.universe_domain, self.transport._credentials)) - return self._is_universe_domain_valid - - @property - def api_endpoint(self): - """Return the API endpoint used by the client instance. - - Returns: - str: The API endpoint used by the client instance. - """ - return self._api_endpoint - - @property - def universe_domain(self) -> str: - """Return the universe domain used by the client instance. - - Returns: - str: The universe domain used by the client instance. - """ - return self._universe_domain - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, PublisherTransport, Callable[..., PublisherTransport]]] = None, - client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the publisher 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,PublisherTransport,Callable[..., PublisherTransport]]]): - 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 PublisherTransport constructor. - If set to None, a transport is chosen automatically. - client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): - Custom options for the client. - - 1. The ``api_endpoint`` property can be used to override the - default endpoint provided by the client when ``transport`` is - not explicitly provided. Only if this property is not set and - ``transport`` was not explicitly provided, the endpoint is - determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment - variable, which have one of the following values: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto-switch to the - default mTLS endpoint if client certificate is present; this is - the default value). - - 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide a client certificate for mTLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - - 3. The ``universe_domain`` property can be used to override the - default "googleapis.com" universe. Note that the ``api_endpoint`` - property still takes precedence; and ``universe_domain`` is - currently not supported for mTLS. - - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - """ - self._client_options = client_options - if isinstance(self._client_options, dict): - self._client_options = client_options_lib.from_dict(self._client_options) - if self._client_options is None: - self._client_options = client_options_lib.ClientOptions() - self._client_options = cast(client_options_lib.ClientOptions, self._client_options) - - universe_domain_opt = getattr(self._client_options, 'universe_domain', None) - - self._use_client_cert, self._use_mtls_endpoint, self._universe_domain_env = PublisherClient._read_environment_variables() - self._client_cert_source = PublisherClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) - self._universe_domain = PublisherClient._get_universe_domain(universe_domain_opt, self._universe_domain_env) - self._api_endpoint = None # updated below, depending on `transport` - - # Initialize the universe domain validation. - self._is_universe_domain_valid = False - - api_key_value = getattr(self._client_options, "api_key", None) - if api_key_value and credentials: - raise ValueError("client_options.api_key and credentials are mutually exclusive") - - # Save or instantiate the transport. - # Ordinarily, we provide the transport, but allowing a custom transport - # instance provides an extensibility point for unusual situations. - transport_provided = isinstance(transport, PublisherTransport) - if transport_provided: - # transport is a PublisherTransport 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(PublisherTransport, transport) - self._api_endpoint = self._transport.host - - self._api_endpoint = (self._api_endpoint or - PublisherClient._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[PublisherTransport], Callable[..., PublisherTransport]] = ( - PublisherClient.get_transport_class(transport) - if isinstance(transport, str) or transport is None - else cast(Callable[..., PublisherTransport], transport) - ) - # initialize with the provided callable or the passed in class - self._transport = transport_init( - credentials=credentials, - credentials_file=self._client_options.credentials_file, - host=self._api_endpoint, - scopes=self._client_options.scopes, - client_cert_source_for_mtls=self._client_cert_source, - quota_project_id=self._client_options.quota_project_id, - client_info=client_info, - always_use_jwt_access=True, - api_audience=self._client_options.api_audience, - ) - - def create_topic(self, - request: Optional[Union[pubsub.Topic, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pubsub.Topic: - r"""Creates the given topic with the given name. See the [resource - name rules] - (https://cloud.google.com/pubsub/docs/pubsub-basics#resource_names). - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require 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 pubsub_v1 - - def sample_create_topic(): - # Create a client - client = pubsub_v1.PublisherClient() - - # Initialize request argument(s) - request = pubsub_v1.Topic( - name="name_value", - ) - - # Make the request - response = client.create_topic(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.pubsub_v1.types.Topic, dict]): - The request object. A topic resource. - name (str): - Required. The name of the topic. It must have the format - ``"projects/{project}/topics/{topic}"``. ``{topic}`` - must start with a letter, and contain only letters - (``[A-Za-z]``), numbers (``[0-9]``), dashes (``-``), - underscores (``_``), periods (``.``), tildes (``~``), - plus (``+``) or percent signs (``%``). It must be - between 3 and 255 characters in length, and it must not - start with ``"goog"``. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.pubsub_v1.types.Topic: - A topic resource. - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, pubsub.Topic): - request = pubsub.Topic(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - 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.create_topic] - - # Certain 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_topic(self, - request: Optional[Union[pubsub.UpdateTopicRequest, dict]] = None, - *, - topic: Optional[pubsub.Topic] = None, - update_mask: Optional[field_mask_pb2.FieldMask] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pubsub.Topic: - r"""Updates an existing topic by updating the fields - specified in the update mask. Note that certain - properties of a topic are not modifiable. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require 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 pubsub_v1 - - def sample_update_topic(): - # Create a client - client = pubsub_v1.PublisherClient() - - # Initialize request argument(s) - topic = pubsub_v1.Topic() - topic.name = "name_value" - - request = pubsub_v1.UpdateTopicRequest( - topic=topic, - ) - - # Make the request - response = client.update_topic(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.pubsub_v1.types.UpdateTopicRequest, dict]): - The request object. Request for the UpdateTopic method. - topic (google.pubsub_v1.types.Topic): - Required. The updated topic object. - This corresponds to the ``topic`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Required. Indicates which fields in the provided topic - to update. Must be specified and non-empty. Note that if - ``update_mask`` contains "message_storage_policy" but - the ``message_storage_policy`` is not set in the - ``topic`` provided above, then the updated value is - determined by the policy configured at the project or - organization level. - - This corresponds to the ``update_mask`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.pubsub_v1.types.Topic: - A topic resource. - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([topic, update_mask]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, pubsub.UpdateTopicRequest): - request = pubsub.UpdateTopicRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if topic is not None: - request.topic = topic - if update_mask is not None: - request.update_mask = update_mask - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.update_topic] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("topic.name", request.topic.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 publish(self, - request: Optional[Union[pubsub.PublishRequest, dict]] = None, - *, - topic: Optional[str] = None, - messages: Optional[MutableSequence[pubsub.PubsubMessage]] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pubsub.PublishResponse: - r"""Adds one or more messages to the topic. Returns ``NOT_FOUND`` if - the topic does not exist. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require 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 pubsub_v1 - - def sample_publish(): - # Create a client - client = pubsub_v1.PublisherClient() - - # Initialize request argument(s) - request = pubsub_v1.PublishRequest( - topic="topic_value", - ) - - # Make the request - response = client.publish(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.pubsub_v1.types.PublishRequest, dict]): - The request object. Request for the Publish method. - topic (str): - Required. The messages in the request will be published - on this topic. Format is - ``projects/{project}/topics/{topic}``. - - This corresponds to the ``topic`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - messages (MutableSequence[google.pubsub_v1.types.PubsubMessage]): - Required. The messages to publish. - This corresponds to the ``messages`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.pubsub_v1.types.PublishResponse: - Response for the Publish 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. - has_flattened_params = any([topic, messages]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, pubsub.PublishRequest): - request = pubsub.PublishRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if topic is not None: - request.topic = topic - if messages is not None: - request.messages = messages - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.publish] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("topic", request.topic), - )), - ) - - # 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_topic(self, - request: Optional[Union[pubsub.GetTopicRequest, dict]] = None, - *, - topic: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pubsub.Topic: - r"""Gets the configuration of a topic. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require 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 pubsub_v1 - - def sample_get_topic(): - # Create a client - client = pubsub_v1.PublisherClient() - - # Initialize request argument(s) - request = pubsub_v1.GetTopicRequest( - topic="topic_value", - ) - - # Make the request - response = client.get_topic(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.pubsub_v1.types.GetTopicRequest, dict]): - The request object. Request for the GetTopic method. - topic (str): - Required. The name of the topic to get. Format is - ``projects/{project}/topics/{topic}``. - - This corresponds to the ``topic`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.pubsub_v1.types.Topic: - A topic resource. - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([topic]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, pubsub.GetTopicRequest): - request = pubsub.GetTopicRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if topic is not None: - request.topic = topic - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.get_topic] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("topic", request.topic), - )), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def list_topics(self, - request: Optional[Union[pubsub.ListTopicsRequest, dict]] = None, - *, - project: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListTopicsPager: - r"""Lists matching topics. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require 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 pubsub_v1 - - def sample_list_topics(): - # Create a client - client = pubsub_v1.PublisherClient() - - # Initialize request argument(s) - request = pubsub_v1.ListTopicsRequest( - project="project_value", - ) - - # Make the request - page_result = client.list_topics(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.pubsub_v1.types.ListTopicsRequest, dict]): - The request object. Request for the ``ListTopics`` method. - project (str): - Required. The name of the project in which to list - topics. Format is ``projects/{project-id}``. - - This corresponds to the ``project`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.pubsub_v1.services.publisher.pagers.ListTopicsPager: - Response for the ListTopics method. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([project]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, pubsub.ListTopicsRequest): - request = pubsub.ListTopicsRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if project is not None: - request.project = project - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.list_topics] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("project", request.project), - )), - ) - - # 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.ListTopicsPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def list_topic_subscriptions(self, - request: Optional[Union[pubsub.ListTopicSubscriptionsRequest, dict]] = None, - *, - topic: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListTopicSubscriptionsPager: - r"""Lists the names of the attached subscriptions on this - topic. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require 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 pubsub_v1 - - def sample_list_topic_subscriptions(): - # Create a client - client = pubsub_v1.PublisherClient() - - # Initialize request argument(s) - request = pubsub_v1.ListTopicSubscriptionsRequest( - topic="topic_value", - ) - - # Make the request - page_result = client.list_topic_subscriptions(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.pubsub_v1.types.ListTopicSubscriptionsRequest, dict]): - The request object. Request for the ``ListTopicSubscriptions`` method. - topic (str): - Required. The name of the topic that subscriptions are - attached to. Format is - ``projects/{project}/topics/{topic}``. - - This corresponds to the ``topic`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.pubsub_v1.services.publisher.pagers.ListTopicSubscriptionsPager: - Response for the ListTopicSubscriptions method. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([topic]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, pubsub.ListTopicSubscriptionsRequest): - request = pubsub.ListTopicSubscriptionsRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if topic is not None: - request.topic = topic - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.list_topic_subscriptions] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("topic", request.topic), - )), - ) - - # 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.ListTopicSubscriptionsPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def list_topic_snapshots(self, - request: Optional[Union[pubsub.ListTopicSnapshotsRequest, dict]] = None, - *, - topic: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListTopicSnapshotsPager: - r"""Lists the names of the snapshots on this topic. Snapshots are - used in - `Seek `__ - operations, which allow you to manage message acknowledgments in - bulk. That is, you can set the acknowledgment state of messages - in an existing subscription to the state captured by a snapshot. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require 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 pubsub_v1 - - def sample_list_topic_snapshots(): - # Create a client - client = pubsub_v1.PublisherClient() - - # Initialize request argument(s) - request = pubsub_v1.ListTopicSnapshotsRequest( - topic="topic_value", - ) - - # Make the request - page_result = client.list_topic_snapshots(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.pubsub_v1.types.ListTopicSnapshotsRequest, dict]): - The request object. Request for the ``ListTopicSnapshots`` method. - topic (str): - Required. The name of the topic that snapshots are - attached to. Format is - ``projects/{project}/topics/{topic}``. - - This corresponds to the ``topic`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.pubsub_v1.services.publisher.pagers.ListTopicSnapshotsPager: - Response for the ListTopicSnapshots method. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([topic]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, pubsub.ListTopicSnapshotsRequest): - request = pubsub.ListTopicSnapshotsRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if topic is not None: - request.topic = topic - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.list_topic_snapshots] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("topic", request.topic), - )), - ) - - # 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.ListTopicSnapshotsPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def delete_topic(self, - request: Optional[Union[pubsub.DeleteTopicRequest, dict]] = None, - *, - topic: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes the topic with the given name. Returns ``NOT_FOUND`` if - the topic does not exist. After a topic is deleted, a new topic - may be created with the same name; this is an entirely new topic - with none of the old configuration or subscriptions. Existing - subscriptions to this topic are not deleted, but their ``topic`` - field is set to ``_deleted-topic_``. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require 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 pubsub_v1 - - def sample_delete_topic(): - # Create a client - client = pubsub_v1.PublisherClient() - - # Initialize request argument(s) - request = pubsub_v1.DeleteTopicRequest( - topic="topic_value", - ) - - # Make the request - client.delete_topic(request=request) - - Args: - request (Union[google.pubsub_v1.types.DeleteTopicRequest, dict]): - The request object. Request for the ``DeleteTopic`` method. - topic (str): - Required. Name of the topic to delete. Format is - ``projects/{project}/topics/{topic}``. - - This corresponds to the ``topic`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([topic]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, pubsub.DeleteTopicRequest): - request = pubsub.DeleteTopicRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if topic is not None: - request.topic = topic - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.delete_topic] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("topic", request.topic), - )), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - def detach_subscription(self, - request: Optional[Union[pubsub.DetachSubscriptionRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pubsub.DetachSubscriptionResponse: - r"""Detaches a subscription from this topic. All messages retained - in the subscription are dropped. Subsequent ``Pull`` and - ``StreamingPull`` requests will return FAILED_PRECONDITION. If - the subscription is a push subscription, pushes to the endpoint - will stop. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require 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 pubsub_v1 - - def sample_detach_subscription(): - # Create a client - client = pubsub_v1.PublisherClient() - - # Initialize request argument(s) - request = pubsub_v1.DetachSubscriptionRequest( - subscription="subscription_value", - ) - - # Make the request - response = client.detach_subscription(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.pubsub_v1.types.DetachSubscriptionRequest, dict]): - The request object. Request for the DetachSubscription - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.pubsub_v1.types.DetachSubscriptionResponse: - Response for the DetachSubscription - method. Reserved for future use. - - """ - # 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, pubsub.DetachSubscriptionRequest): - request = pubsub.DetachSubscriptionRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.detach_subscription] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("subscription", request.subscription), - )), - ) - - # 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) -> "PublisherClient": - 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 set_iam_policy( - self, - request: Optional[iam_policy_pb2.SetIamPolicyRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> policy_pb2.Policy: - r"""Sets the IAM access control policy on the specified function. - - Replaces any existing policy. - - Args: - request (:class:`~.iam_policy_pb2.SetIamPolicyRequest`): - The request object. Request message for `SetIamPolicy` - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.policy_pb2.Policy: - Defines an Identity and Access Management (IAM) policy. - It is used to specify access control policies for Cloud - Platform resources. - A ``Policy`` is a collection of ``bindings``. A - ``binding`` binds one or more ``members`` to a single - ``role``. Members can be user accounts, service - accounts, Google groups, and domains (such as G Suite). - A ``role`` is a named list of permissions (defined by - IAM or configured by users). A ``binding`` can - optionally specify a ``condition``, which is a logic - expression that further constrains the role binding - based on attributes about the request and/or target - resource. - - **JSON Example** - - :: - - { - "bindings": [ - { - "role": "roles/resourcemanager.organizationAdmin", - "members": [ - "user:mike@example.com", - "group:admins@example.com", - "domain:google.com", - "serviceAccount:my-project-id@appspot.gserviceaccount.com" - ] - }, - { - "role": "roles/resourcemanager.organizationViewer", - "members": ["user:eve@example.com"], - "condition": { - "title": "expirable access", - "description": "Does not grant access after Sep 2020", - "expression": "request.time < - timestamp('2020-10-01T00:00:00.000Z')", - } - } - ] - } - - **YAML Example** - - :: - - bindings: - - members: - - user:mike@example.com - - group:admins@example.com - - domain:google.com - - serviceAccount:my-project-id@appspot.gserviceaccount.com - role: roles/resourcemanager.organizationAdmin - - members: - - user:eve@example.com - role: roles/resourcemanager.organizationViewer - condition: - title: expirable access - description: Does not grant access after Sep 2020 - expression: request.time < timestamp('2020-10-01T00:00:00.000Z') - - For a description of IAM and its features, see the `IAM - developer's - guide `__. - """ - # Create or coerce a protobuf request object. - - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = iam_policy_pb2.SetIamPolicyRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.set_iam_policy, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("resource", request.resource),)), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - def get_iam_policy( - self, - request: Optional[iam_policy_pb2.GetIamPolicyRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> policy_pb2.Policy: - r"""Gets the IAM access control policy for a function. - - Returns an empty policy if the function exists and does not have a - policy set. - - Args: - request (:class:`~.iam_policy_pb2.GetIamPolicyRequest`): - The request object. Request message for `GetIamPolicy` - method. - retry (google.api_core.retry.Retry): Designation of what errors, if - any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.policy_pb2.Policy: - Defines an Identity and Access Management (IAM) policy. - It is used to specify access control policies for Cloud - Platform resources. - A ``Policy`` is a collection of ``bindings``. A - ``binding`` binds one or more ``members`` to a single - ``role``. Members can be user accounts, service - accounts, Google groups, and domains (such as G Suite). - A ``role`` is a named list of permissions (defined by - IAM or configured by users). A ``binding`` can - optionally specify a ``condition``, which is a logic - expression that further constrains the role binding - based on attributes about the request and/or target - resource. - - **JSON Example** - - :: - - { - "bindings": [ - { - "role": "roles/resourcemanager.organizationAdmin", - "members": [ - "user:mike@example.com", - "group:admins@example.com", - "domain:google.com", - "serviceAccount:my-project-id@appspot.gserviceaccount.com" - ] - }, - { - "role": "roles/resourcemanager.organizationViewer", - "members": ["user:eve@example.com"], - "condition": { - "title": "expirable access", - "description": "Does not grant access after Sep 2020", - "expression": "request.time < - timestamp('2020-10-01T00:00:00.000Z')", - } - } - ] - } - - **YAML Example** - - :: - - bindings: - - members: - - user:mike@example.com - - group:admins@example.com - - domain:google.com - - serviceAccount:my-project-id@appspot.gserviceaccount.com - role: roles/resourcemanager.organizationAdmin - - members: - - user:eve@example.com - role: roles/resourcemanager.organizationViewer - condition: - title: expirable access - description: Does not grant access after Sep 2020 - expression: request.time < timestamp('2020-10-01T00:00:00.000Z') - - For a description of IAM and its features, see the `IAM - developer's - guide `__. - """ - # Create or coerce a protobuf request object. - - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = iam_policy_pb2.GetIamPolicyRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.get_iam_policy, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("resource", request.resource),)), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - def test_iam_permissions( - self, - request: Optional[iam_policy_pb2.TestIamPermissionsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> iam_policy_pb2.TestIamPermissionsResponse: - r"""Tests the specified IAM permissions against the IAM access control - policy for a function. - - If the function does not exist, this will return an empty set - of permissions, not a NOT_FOUND error. - - Args: - request (:class:`~.iam_policy_pb2.TestIamPermissionsRequest`): - The request object. Request message for - `TestIamPermissions` method. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.iam_policy_pb2.TestIamPermissionsResponse: - Response message for ``TestIamPermissions`` method. - """ - # Create or coerce a protobuf request object. - - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = iam_policy_pb2.TestIamPermissionsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.test_iam_permissions, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("resource", request.resource),)), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -__all__ = ( - "PublisherClient", -) diff --git a/owl-bot-staging/v1/google/pubsub_v1/services/publisher/pagers.py b/owl-bot-staging/v1/google/pubsub_v1/services/publisher/pagers.py deleted file mode 100644 index 03a753fc1..000000000 --- a/owl-bot-staging/v1/google/pubsub_v1/services/publisher/pagers.py +++ /dev/null @@ -1,432 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.api_core import retry_async as retries_async -from typing import Any, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator, Union -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] - OptionalAsyncRetry = Union[retries_async.AsyncRetry, gapic_v1.method._MethodDefault, None] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object, None] # type: ignore - OptionalAsyncRetry = Union[retries_async.AsyncRetry, object, None] # type: ignore - -from google.pubsub_v1.types import pubsub - - -class ListTopicsPager: - """A pager for iterating through ``list_topics`` requests. - - This class thinly wraps an initial - :class:`google.pubsub_v1.types.ListTopicsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``topics`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListTopics`` requests and continue to iterate - through the ``topics`` field on the - corresponding responses. - - All the usual :class:`google.pubsub_v1.types.ListTopicsResponse` - attributes are available on the pager. If multiple requests are made, only - the most recent response is retained, and thus used for attribute lookup. - """ - def __init__(self, - method: Callable[..., pubsub.ListTopicsResponse], - request: pubsub.ListTopicsRequest, - response: pubsub.ListTopicsResponse, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiate the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.pubsub_v1.types.ListTopicsRequest): - The initial request object. - response (google.pubsub_v1.types.ListTopicsResponse): - The initial response object. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = pubsub.ListTopicsRequest(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[pubsub.ListTopicsResponse]: - 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[pubsub.Topic]: - for page in self.pages: - yield from page.topics - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListTopicsAsyncPager: - """A pager for iterating through ``list_topics`` requests. - - This class thinly wraps an initial - :class:`google.pubsub_v1.types.ListTopicsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``topics`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListTopics`` requests and continue to iterate - through the ``topics`` field on the - corresponding responses. - - All the usual :class:`google.pubsub_v1.types.ListTopicsResponse` - attributes are available on the 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[pubsub.ListTopicsResponse]], - request: pubsub.ListTopicsRequest, - response: pubsub.ListTopicsResponse, - *, - retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiates the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.pubsub_v1.types.ListTopicsRequest): - The initial request object. - response (google.pubsub_v1.types.ListTopicsResponse): - The initial response object. - retry (google.api_core.retry.AsyncRetry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = pubsub.ListTopicsRequest(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[pubsub.ListTopicsResponse]: - 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[pubsub.Topic]: - async def async_generator(): - async for page in self.pages: - for response in page.topics: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListTopicSubscriptionsPager: - """A pager for iterating through ``list_topic_subscriptions`` requests. - - This class thinly wraps an initial - :class:`google.pubsub_v1.types.ListTopicSubscriptionsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``subscriptions`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListTopicSubscriptions`` requests and continue to iterate - through the ``subscriptions`` field on the - corresponding responses. - - All the usual :class:`google.pubsub_v1.types.ListTopicSubscriptionsResponse` - attributes are available on the pager. If multiple requests are made, only - the most recent response is retained, and thus used for attribute lookup. - """ - def __init__(self, - method: Callable[..., pubsub.ListTopicSubscriptionsResponse], - request: pubsub.ListTopicSubscriptionsRequest, - response: pubsub.ListTopicSubscriptionsResponse, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiate the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.pubsub_v1.types.ListTopicSubscriptionsRequest): - The initial request object. - response (google.pubsub_v1.types.ListTopicSubscriptionsResponse): - The initial response object. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = pubsub.ListTopicSubscriptionsRequest(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[pubsub.ListTopicSubscriptionsResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = self._method(self._request, retry=self._retry, timeout=self._timeout, metadata=self._metadata) - yield self._response - - def __iter__(self) -> Iterator[str]: - for page in self.pages: - yield from page.subscriptions - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListTopicSubscriptionsAsyncPager: - """A pager for iterating through ``list_topic_subscriptions`` requests. - - This class thinly wraps an initial - :class:`google.pubsub_v1.types.ListTopicSubscriptionsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``subscriptions`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListTopicSubscriptions`` requests and continue to iterate - through the ``subscriptions`` field on the - corresponding responses. - - All the usual :class:`google.pubsub_v1.types.ListTopicSubscriptionsResponse` - attributes are available on the 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[pubsub.ListTopicSubscriptionsResponse]], - request: pubsub.ListTopicSubscriptionsRequest, - response: pubsub.ListTopicSubscriptionsResponse, - *, - retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiates the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.pubsub_v1.types.ListTopicSubscriptionsRequest): - The initial request object. - response (google.pubsub_v1.types.ListTopicSubscriptionsResponse): - The initial response object. - retry (google.api_core.retry.AsyncRetry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = pubsub.ListTopicSubscriptionsRequest(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[pubsub.ListTopicSubscriptionsResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = await self._method(self._request, retry=self._retry, timeout=self._timeout, metadata=self._metadata) - yield self._response - def __aiter__(self) -> AsyncIterator[str]: - async def async_generator(): - async for page in self.pages: - for response in page.subscriptions: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListTopicSnapshotsPager: - """A pager for iterating through ``list_topic_snapshots`` requests. - - This class thinly wraps an initial - :class:`google.pubsub_v1.types.ListTopicSnapshotsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``snapshots`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListTopicSnapshots`` requests and continue to iterate - through the ``snapshots`` field on the - corresponding responses. - - All the usual :class:`google.pubsub_v1.types.ListTopicSnapshotsResponse` - attributes are available on the pager. If multiple requests are made, only - the most recent response is retained, and thus used for attribute lookup. - """ - def __init__(self, - method: Callable[..., pubsub.ListTopicSnapshotsResponse], - request: pubsub.ListTopicSnapshotsRequest, - response: pubsub.ListTopicSnapshotsResponse, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiate the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.pubsub_v1.types.ListTopicSnapshotsRequest): - The initial request object. - response (google.pubsub_v1.types.ListTopicSnapshotsResponse): - The initial response object. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = pubsub.ListTopicSnapshotsRequest(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[pubsub.ListTopicSnapshotsResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = self._method(self._request, retry=self._retry, timeout=self._timeout, metadata=self._metadata) - yield self._response - - def __iter__(self) -> Iterator[str]: - for page in self.pages: - yield from page.snapshots - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListTopicSnapshotsAsyncPager: - """A pager for iterating through ``list_topic_snapshots`` requests. - - This class thinly wraps an initial - :class:`google.pubsub_v1.types.ListTopicSnapshotsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``snapshots`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListTopicSnapshots`` requests and continue to iterate - through the ``snapshots`` field on the - corresponding responses. - - All the usual :class:`google.pubsub_v1.types.ListTopicSnapshotsResponse` - attributes are available on the 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[pubsub.ListTopicSnapshotsResponse]], - request: pubsub.ListTopicSnapshotsRequest, - response: pubsub.ListTopicSnapshotsResponse, - *, - retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiates the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.pubsub_v1.types.ListTopicSnapshotsRequest): - The initial request object. - response (google.pubsub_v1.types.ListTopicSnapshotsResponse): - The initial response object. - retry (google.api_core.retry.AsyncRetry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = pubsub.ListTopicSnapshotsRequest(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[pubsub.ListTopicSnapshotsResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = await self._method(self._request, retry=self._retry, timeout=self._timeout, metadata=self._metadata) - yield self._response - def __aiter__(self) -> AsyncIterator[str]: - async def async_generator(): - async for page in self.pages: - for response in page.snapshots: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) diff --git a/owl-bot-staging/v1/google/pubsub_v1/services/publisher/transports/__init__.py b/owl-bot-staging/v1/google/pubsub_v1/services/publisher/transports/__init__.py deleted file mode 100644 index 5ab6ee561..000000000 --- a/owl-bot-staging/v1/google/pubsub_v1/services/publisher/transports/__init__.py +++ /dev/null @@ -1,38 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -from typing import Dict, Type - -from .base import PublisherTransport -from .grpc import PublisherGrpcTransport -from .grpc_asyncio import PublisherGrpcAsyncIOTransport -from .rest import PublisherRestTransport -from .rest import PublisherRestInterceptor - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[PublisherTransport]] -_transport_registry['grpc'] = PublisherGrpcTransport -_transport_registry['grpc_asyncio'] = PublisherGrpcAsyncIOTransport -_transport_registry['rest'] = PublisherRestTransport - -__all__ = ( - 'PublisherTransport', - 'PublisherGrpcTransport', - 'PublisherGrpcAsyncIOTransport', - 'PublisherRestTransport', - 'PublisherRestInterceptor', -) diff --git a/owl-bot-staging/v1/google/pubsub_v1/services/publisher/transports/base.py b/owl-bot-staging/v1/google/pubsub_v1/services/publisher/transports/base.py deleted file mode 100644 index 2a73f4f4a..000000000 --- a/owl-bot-staging/v1/google/pubsub_v1/services/publisher/transports/base.py +++ /dev/null @@ -1,395 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import abc -from typing import Awaitable, Callable, Dict, Optional, Sequence, Union - -from google.pubsub_v1 import gapic_version as package_version - -import google.auth # type: ignore -import google.api_core -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.iam.v1 import iam_policy_pb2 # type: ignore -from google.iam.v1 import policy_pb2 # type: ignore -from google.protobuf import empty_pb2 # type: ignore -from google.pubsub_v1.types import pubsub - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -class PublisherTransport(abc.ABC): - """Abstract transport class for Publisher.""" - - AUTH_SCOPES = ( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/pubsub', - ) - - DEFAULT_HOST: str = 'pubsub.googleapis.com' - def __init__( - self, *, - host: str = DEFAULT_HOST, - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - **kwargs, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to (default: 'pubsub.googleapis.com'). - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A list of scopes. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - """ - - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - - # Save the scopes. - self._scopes = scopes - if not hasattr(self, "_ignore_credentials"): - self._ignore_credentials: bool = False - - # If no credentials are provided, then determine the appropriate - # defaults. - if credentials and credentials_file: - raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") - - if credentials_file is not None: - credentials, _ = google.auth.load_credentials_from_file( - credentials_file, - **scopes_kwargs, - quota_project_id=quota_project_id - ) - elif credentials is None and not self._ignore_credentials: - credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) - # Don't apply audience if the credentials file passed from user. - if hasattr(credentials, "with_gdch_audience"): - credentials = credentials.with_gdch_audience(api_audience if api_audience else host) - - # If the credentials are service account credentials, then always try to use self signed JWT. - if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): - credentials = credentials.with_always_use_jwt_access(True) - - # Save the credentials. - self._credentials = credentials - - # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ':' not in host: - host += ':443' - self._host = host - - @property - def host(self): - return self._host - - def _prep_wrapped_messages(self, client_info): - # Precompute the wrapped methods. - self._wrapped_methods = { - self.create_topic: gapic_v1.method.wrap_method( - self.create_topic, - default_retry=retries.Retry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.update_topic: gapic_v1.method.wrap_method( - self.update_topic, - default_retry=retries.Retry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.publish: gapic_v1.method.wrap_method( - self.publish, - default_retry=retries.Retry( - initial=0.1, - maximum=60.0, - multiplier=4, - predicate=retries.if_exception_type( - core_exceptions.Aborted, - core_exceptions.Cancelled, - core_exceptions.DeadlineExceeded, - core_exceptions.InternalServerError, - core_exceptions.ResourceExhausted, - core_exceptions.ServiceUnavailable, - core_exceptions.Unknown, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.get_topic: gapic_v1.method.wrap_method( - self.get_topic, - default_retry=retries.Retry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.Aborted, - core_exceptions.ServiceUnavailable, - core_exceptions.Unknown, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.list_topics: gapic_v1.method.wrap_method( - self.list_topics, - default_retry=retries.Retry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.Aborted, - core_exceptions.ServiceUnavailable, - core_exceptions.Unknown, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.list_topic_subscriptions: gapic_v1.method.wrap_method( - self.list_topic_subscriptions, - default_retry=retries.Retry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.Aborted, - core_exceptions.ServiceUnavailable, - core_exceptions.Unknown, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.list_topic_snapshots: gapic_v1.method.wrap_method( - self.list_topic_snapshots, - default_retry=retries.Retry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.Aborted, - core_exceptions.ServiceUnavailable, - core_exceptions.Unknown, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.delete_topic: gapic_v1.method.wrap_method( - self.delete_topic, - default_retry=retries.Retry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.detach_subscription: gapic_v1.method.wrap_method( - self.detach_subscription, - default_retry=retries.Retry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - 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_topic(self) -> Callable[ - [pubsub.Topic], - Union[ - pubsub.Topic, - Awaitable[pubsub.Topic] - ]]: - raise NotImplementedError() - - @property - def update_topic(self) -> Callable[ - [pubsub.UpdateTopicRequest], - Union[ - pubsub.Topic, - Awaitable[pubsub.Topic] - ]]: - raise NotImplementedError() - - @property - def publish(self) -> Callable[ - [pubsub.PublishRequest], - Union[ - pubsub.PublishResponse, - Awaitable[pubsub.PublishResponse] - ]]: - raise NotImplementedError() - - @property - def get_topic(self) -> Callable[ - [pubsub.GetTopicRequest], - Union[ - pubsub.Topic, - Awaitable[pubsub.Topic] - ]]: - raise NotImplementedError() - - @property - def list_topics(self) -> Callable[ - [pubsub.ListTopicsRequest], - Union[ - pubsub.ListTopicsResponse, - Awaitable[pubsub.ListTopicsResponse] - ]]: - raise NotImplementedError() - - @property - def list_topic_subscriptions(self) -> Callable[ - [pubsub.ListTopicSubscriptionsRequest], - Union[ - pubsub.ListTopicSubscriptionsResponse, - Awaitable[pubsub.ListTopicSubscriptionsResponse] - ]]: - raise NotImplementedError() - - @property - def list_topic_snapshots(self) -> Callable[ - [pubsub.ListTopicSnapshotsRequest], - Union[ - pubsub.ListTopicSnapshotsResponse, - Awaitable[pubsub.ListTopicSnapshotsResponse] - ]]: - raise NotImplementedError() - - @property - def delete_topic(self) -> Callable[ - [pubsub.DeleteTopicRequest], - Union[ - empty_pb2.Empty, - Awaitable[empty_pb2.Empty] - ]]: - raise NotImplementedError() - - @property - def detach_subscription(self) -> Callable[ - [pubsub.DetachSubscriptionRequest], - Union[ - pubsub.DetachSubscriptionResponse, - Awaitable[pubsub.DetachSubscriptionResponse] - ]]: - 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 kind(self) -> str: - raise NotImplementedError() - - -__all__ = ( - 'PublisherTransport', -) diff --git a/owl-bot-staging/v1/google/pubsub_v1/services/publisher/transports/grpc.py b/owl-bot-staging/v1/google/pubsub_v1/services/publisher/transports/grpc.py deleted file mode 100644 index 081664185..000000000 --- a/owl-bot-staging/v1/google/pubsub_v1/services/publisher/transports/grpc.py +++ /dev/null @@ -1,581 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import grpc_helpers -from google.api_core import gapic_v1 -import google.auth # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore - -from google.iam.v1 import iam_policy_pb2 # type: ignore -from google.iam.v1 import policy_pb2 # type: ignore -from google.protobuf import empty_pb2 # type: ignore -from google.pubsub_v1.types import pubsub -from .base import PublisherTransport, DEFAULT_CLIENT_INFO - - -class PublisherGrpcTransport(PublisherTransport): - """gRPC backend transport for Publisher. - - The service that an application uses to manipulate topics, - and to send messages to a topic. - - This 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 = 'pubsub.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to (default: 'pubsub.googleapis.com'). - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if a ``channel`` instance is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if a ``channel`` instance is provided. - channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): - A ``Channel`` instance through which to make calls, or a Callable - that constructs and returns one. If set to None, ``self.create_channel`` - is used to create the channel. If a Callable is given, it will be called - with the same arguments as used in ``self.create_channel``. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if a ``channel`` instance is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if a ``channel`` instance or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if isinstance(channel, grpc.Channel): - # Ignore credentials if a channel was passed. - credentials = None - self._ignore_credentials = True - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - # initialize with the provided callable or the default channel - channel_init = channel or type(self).create_channel - self._grpc_channel = channel_init( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @classmethod - def create_channel(cls, - host: str = 'pubsub.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> grpc.Channel: - """Create and return a gRPC channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - grpc.Channel: A gRPC channel object. - - Raises: - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - - return grpc_helpers.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - @property - def grpc_channel(self) -> grpc.Channel: - """Return the channel designed to connect to this service. - """ - return self._grpc_channel - - @property - def create_topic(self) -> Callable[ - [pubsub.Topic], - pubsub.Topic]: - r"""Return a callable for the create topic method over gRPC. - - Creates the given topic with the given name. See the [resource - name rules] - (https://cloud.google.com/pubsub/docs/pubsub-basics#resource_names). - - Returns: - Callable[[~.Topic], - ~.Topic]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_topic' not in self._stubs: - self._stubs['create_topic'] = self.grpc_channel.unary_unary( - '/google.pubsub.v1.Publisher/CreateTopic', - request_serializer=pubsub.Topic.serialize, - response_deserializer=pubsub.Topic.deserialize, - ) - return self._stubs['create_topic'] - - @property - def update_topic(self) -> Callable[ - [pubsub.UpdateTopicRequest], - pubsub.Topic]: - r"""Return a callable for the update topic method over gRPC. - - Updates an existing topic by updating the fields - specified in the update mask. Note that certain - properties of a topic are not modifiable. - - Returns: - Callable[[~.UpdateTopicRequest], - ~.Topic]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_topic' not in self._stubs: - self._stubs['update_topic'] = self.grpc_channel.unary_unary( - '/google.pubsub.v1.Publisher/UpdateTopic', - request_serializer=pubsub.UpdateTopicRequest.serialize, - response_deserializer=pubsub.Topic.deserialize, - ) - return self._stubs['update_topic'] - - @property - def publish(self) -> Callable[ - [pubsub.PublishRequest], - pubsub.PublishResponse]: - r"""Return a callable for the publish method over gRPC. - - Adds one or more messages to the topic. Returns ``NOT_FOUND`` if - the topic does not exist. - - Returns: - Callable[[~.PublishRequest], - ~.PublishResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'publish' not in self._stubs: - self._stubs['publish'] = self.grpc_channel.unary_unary( - '/google.pubsub.v1.Publisher/Publish', - request_serializer=pubsub.PublishRequest.serialize, - response_deserializer=pubsub.PublishResponse.deserialize, - ) - return self._stubs['publish'] - - @property - def get_topic(self) -> Callable[ - [pubsub.GetTopicRequest], - pubsub.Topic]: - r"""Return a callable for the get topic method over gRPC. - - Gets the configuration of a topic. - - Returns: - Callable[[~.GetTopicRequest], - ~.Topic]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'get_topic' not in self._stubs: - self._stubs['get_topic'] = self.grpc_channel.unary_unary( - '/google.pubsub.v1.Publisher/GetTopic', - request_serializer=pubsub.GetTopicRequest.serialize, - response_deserializer=pubsub.Topic.deserialize, - ) - return self._stubs['get_topic'] - - @property - def list_topics(self) -> Callable[ - [pubsub.ListTopicsRequest], - pubsub.ListTopicsResponse]: - r"""Return a callable for the list topics method over gRPC. - - Lists matching topics. - - Returns: - Callable[[~.ListTopicsRequest], - ~.ListTopicsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'list_topics' not in self._stubs: - self._stubs['list_topics'] = self.grpc_channel.unary_unary( - '/google.pubsub.v1.Publisher/ListTopics', - request_serializer=pubsub.ListTopicsRequest.serialize, - response_deserializer=pubsub.ListTopicsResponse.deserialize, - ) - return self._stubs['list_topics'] - - @property - def list_topic_subscriptions(self) -> Callable[ - [pubsub.ListTopicSubscriptionsRequest], - pubsub.ListTopicSubscriptionsResponse]: - r"""Return a callable for the list topic subscriptions method over gRPC. - - Lists the names of the attached subscriptions on this - topic. - - Returns: - Callable[[~.ListTopicSubscriptionsRequest], - ~.ListTopicSubscriptionsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'list_topic_subscriptions' not in self._stubs: - self._stubs['list_topic_subscriptions'] = self.grpc_channel.unary_unary( - '/google.pubsub.v1.Publisher/ListTopicSubscriptions', - request_serializer=pubsub.ListTopicSubscriptionsRequest.serialize, - response_deserializer=pubsub.ListTopicSubscriptionsResponse.deserialize, - ) - return self._stubs['list_topic_subscriptions'] - - @property - def list_topic_snapshots(self) -> Callable[ - [pubsub.ListTopicSnapshotsRequest], - pubsub.ListTopicSnapshotsResponse]: - r"""Return a callable for the list topic snapshots method over gRPC. - - Lists the names of the snapshots on this topic. Snapshots are - used in - `Seek `__ - operations, which allow you to manage message acknowledgments in - bulk. That is, you can set the acknowledgment state of messages - in an existing subscription to the state captured by a snapshot. - - Returns: - Callable[[~.ListTopicSnapshotsRequest], - ~.ListTopicSnapshotsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'list_topic_snapshots' not in self._stubs: - self._stubs['list_topic_snapshots'] = self.grpc_channel.unary_unary( - '/google.pubsub.v1.Publisher/ListTopicSnapshots', - request_serializer=pubsub.ListTopicSnapshotsRequest.serialize, - response_deserializer=pubsub.ListTopicSnapshotsResponse.deserialize, - ) - return self._stubs['list_topic_snapshots'] - - @property - def delete_topic(self) -> Callable[ - [pubsub.DeleteTopicRequest], - empty_pb2.Empty]: - r"""Return a callable for the delete topic method over gRPC. - - Deletes the topic with the given name. Returns ``NOT_FOUND`` if - the topic does not exist. After a topic is deleted, a new topic - may be created with the same name; this is an entirely new topic - with none of the old configuration or subscriptions. Existing - subscriptions to this topic are not deleted, but their ``topic`` - field is set to ``_deleted-topic_``. - - Returns: - Callable[[~.DeleteTopicRequest], - ~.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_topic' not in self._stubs: - self._stubs['delete_topic'] = self.grpc_channel.unary_unary( - '/google.pubsub.v1.Publisher/DeleteTopic', - request_serializer=pubsub.DeleteTopicRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_topic'] - - @property - def detach_subscription(self) -> Callable[ - [pubsub.DetachSubscriptionRequest], - pubsub.DetachSubscriptionResponse]: - r"""Return a callable for the detach subscription method over gRPC. - - Detaches a subscription from this topic. All messages retained - in the subscription are dropped. Subsequent ``Pull`` and - ``StreamingPull`` requests will return FAILED_PRECONDITION. If - the subscription is a push subscription, pushes to the endpoint - will stop. - - Returns: - Callable[[~.DetachSubscriptionRequest], - ~.DetachSubscriptionResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'detach_subscription' not in self._stubs: - self._stubs['detach_subscription'] = self.grpc_channel.unary_unary( - '/google.pubsub.v1.Publisher/DetachSubscription', - request_serializer=pubsub.DetachSubscriptionRequest.serialize, - response_deserializer=pubsub.DetachSubscriptionResponse.deserialize, - ) - return self._stubs['detach_subscription'] - - @property - def set_iam_policy( - self, - ) -> Callable[[iam_policy_pb2.SetIamPolicyRequest], policy_pb2.Policy]: - r"""Return a callable for the set iam policy method over gRPC. - Sets the IAM access control policy on the specified - function. Replaces any existing policy. - Returns: - Callable[[~.SetIamPolicyRequest], - ~.Policy]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "set_iam_policy" not in self._stubs: - self._stubs["set_iam_policy"] = self.grpc_channel.unary_unary( - "/google.iam.v1.IAMPolicy/SetIamPolicy", - request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString, - response_deserializer=policy_pb2.Policy.FromString, - ) - return self._stubs["set_iam_policy"] - - @property - def get_iam_policy( - self, - ) -> Callable[[iam_policy_pb2.GetIamPolicyRequest], policy_pb2.Policy]: - r"""Return a callable for the get iam policy method over gRPC. - Gets the IAM access control policy for a function. - Returns an empty policy if the function exists and does - not have a policy set. - Returns: - Callable[[~.GetIamPolicyRequest], - ~.Policy]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "get_iam_policy" not in self._stubs: - self._stubs["get_iam_policy"] = self.grpc_channel.unary_unary( - "/google.iam.v1.IAMPolicy/GetIamPolicy", - request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, - response_deserializer=policy_pb2.Policy.FromString, - ) - return self._stubs["get_iam_policy"] - - @property - def test_iam_permissions( - self, - ) -> Callable[ - [iam_policy_pb2.TestIamPermissionsRequest], iam_policy_pb2.TestIamPermissionsResponse - ]: - r"""Return a callable for the test iam permissions method over gRPC. - Tests the specified permissions against the IAM access control - policy for a function. If the function does not exist, this will - return an empty set of permissions, not a NOT_FOUND error. - Returns: - Callable[[~.TestIamPermissionsRequest], - ~.TestIamPermissionsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "test_iam_permissions" not in self._stubs: - self._stubs["test_iam_permissions"] = self.grpc_channel.unary_unary( - "/google.iam.v1.IAMPolicy/TestIamPermissions", - request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString, - response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString, - ) - return self._stubs["test_iam_permissions"] - - def close(self): - self.grpc_channel.close() - - @property - def kind(self) -> str: - return "grpc" - - -__all__ = ( - 'PublisherGrpcTransport', -) diff --git a/owl-bot-staging/v1/google/pubsub_v1/services/publisher/transports/grpc_asyncio.py b/owl-bot-staging/v1/google/pubsub_v1/services/publisher/transports/grpc_asyncio.py deleted file mode 100644 index 89758e071..000000000 --- a/owl-bot-staging/v1/google/pubsub_v1/services/publisher/transports/grpc_asyncio.py +++ /dev/null @@ -1,727 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import 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 - -import grpc # type: ignore -from grpc.experimental import aio # type: ignore - -from google.iam.v1 import iam_policy_pb2 # type: ignore -from google.iam.v1 import policy_pb2 # type: ignore -from google.protobuf import empty_pb2 # type: ignore -from google.pubsub_v1.types import pubsub -from .base import PublisherTransport, DEFAULT_CLIENT_INFO -from .grpc import PublisherGrpcTransport - - -class PublisherGrpcAsyncIOTransport(PublisherTransport): - """gRPC AsyncIO backend transport for Publisher. - - The service that an application uses to manipulate topics, - and to send messages to a topic. - - This 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 = 'pubsub.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> aio.Channel: - """Create and return a gRPC AsyncIO channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - aio.Channel: A gRPC AsyncIO channel object. - """ - - return grpc_helpers_async.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - def __init__(self, *, - host: str = 'pubsub.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: Optional[Union[aio.Channel, Callable[..., aio.Channel]]] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to (default: 'pubsub.googleapis.com'). - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if a ``channel`` instance is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - channel (Optional[Union[aio.Channel, Callable[..., aio.Channel]]]): - A ``Channel`` instance through which to make calls, or a Callable - that constructs and returns one. If set to None, ``self.create_channel`` - is used to create the channel. If a Callable is given, it will be called - with the same arguments as used in ``self.create_channel``. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if a ``channel`` instance is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if a ``channel`` instance or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if isinstance(channel, aio.Channel): - # Ignore credentials if a channel was passed. - credentials = None - self._ignore_credentials = True - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - # initialize with the provided callable or the default channel - channel_init = channel or type(self).create_channel - self._grpc_channel = channel_init( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._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_topic(self) -> Callable[ - [pubsub.Topic], - Awaitable[pubsub.Topic]]: - r"""Return a callable for the create topic method over gRPC. - - Creates the given topic with the given name. See the [resource - name rules] - (https://cloud.google.com/pubsub/docs/pubsub-basics#resource_names). - - Returns: - Callable[[~.Topic], - Awaitable[~.Topic]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_topic' not in self._stubs: - self._stubs['create_topic'] = self.grpc_channel.unary_unary( - '/google.pubsub.v1.Publisher/CreateTopic', - request_serializer=pubsub.Topic.serialize, - response_deserializer=pubsub.Topic.deserialize, - ) - return self._stubs['create_topic'] - - @property - def update_topic(self) -> Callable[ - [pubsub.UpdateTopicRequest], - Awaitable[pubsub.Topic]]: - r"""Return a callable for the update topic method over gRPC. - - Updates an existing topic by updating the fields - specified in the update mask. Note that certain - properties of a topic are not modifiable. - - Returns: - Callable[[~.UpdateTopicRequest], - Awaitable[~.Topic]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_topic' not in self._stubs: - self._stubs['update_topic'] = self.grpc_channel.unary_unary( - '/google.pubsub.v1.Publisher/UpdateTopic', - request_serializer=pubsub.UpdateTopicRequest.serialize, - response_deserializer=pubsub.Topic.deserialize, - ) - return self._stubs['update_topic'] - - @property - def publish(self) -> Callable[ - [pubsub.PublishRequest], - Awaitable[pubsub.PublishResponse]]: - r"""Return a callable for the publish method over gRPC. - - Adds one or more messages to the topic. Returns ``NOT_FOUND`` if - the topic does not exist. - - Returns: - Callable[[~.PublishRequest], - Awaitable[~.PublishResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'publish' not in self._stubs: - self._stubs['publish'] = self.grpc_channel.unary_unary( - '/google.pubsub.v1.Publisher/Publish', - request_serializer=pubsub.PublishRequest.serialize, - response_deserializer=pubsub.PublishResponse.deserialize, - ) - return self._stubs['publish'] - - @property - def get_topic(self) -> Callable[ - [pubsub.GetTopicRequest], - Awaitable[pubsub.Topic]]: - r"""Return a callable for the get topic method over gRPC. - - Gets the configuration of a topic. - - Returns: - Callable[[~.GetTopicRequest], - Awaitable[~.Topic]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'get_topic' not in self._stubs: - self._stubs['get_topic'] = self.grpc_channel.unary_unary( - '/google.pubsub.v1.Publisher/GetTopic', - request_serializer=pubsub.GetTopicRequest.serialize, - response_deserializer=pubsub.Topic.deserialize, - ) - return self._stubs['get_topic'] - - @property - def list_topics(self) -> Callable[ - [pubsub.ListTopicsRequest], - Awaitable[pubsub.ListTopicsResponse]]: - r"""Return a callable for the list topics method over gRPC. - - Lists matching topics. - - Returns: - Callable[[~.ListTopicsRequest], - Awaitable[~.ListTopicsResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'list_topics' not in self._stubs: - self._stubs['list_topics'] = self.grpc_channel.unary_unary( - '/google.pubsub.v1.Publisher/ListTopics', - request_serializer=pubsub.ListTopicsRequest.serialize, - response_deserializer=pubsub.ListTopicsResponse.deserialize, - ) - return self._stubs['list_topics'] - - @property - def list_topic_subscriptions(self) -> Callable[ - [pubsub.ListTopicSubscriptionsRequest], - Awaitable[pubsub.ListTopicSubscriptionsResponse]]: - r"""Return a callable for the list topic subscriptions method over gRPC. - - Lists the names of the attached subscriptions on this - topic. - - Returns: - Callable[[~.ListTopicSubscriptionsRequest], - Awaitable[~.ListTopicSubscriptionsResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'list_topic_subscriptions' not in self._stubs: - self._stubs['list_topic_subscriptions'] = self.grpc_channel.unary_unary( - '/google.pubsub.v1.Publisher/ListTopicSubscriptions', - request_serializer=pubsub.ListTopicSubscriptionsRequest.serialize, - response_deserializer=pubsub.ListTopicSubscriptionsResponse.deserialize, - ) - return self._stubs['list_topic_subscriptions'] - - @property - def list_topic_snapshots(self) -> Callable[ - [pubsub.ListTopicSnapshotsRequest], - Awaitable[pubsub.ListTopicSnapshotsResponse]]: - r"""Return a callable for the list topic snapshots method over gRPC. - - Lists the names of the snapshots on this topic. Snapshots are - used in - `Seek `__ - operations, which allow you to manage message acknowledgments in - bulk. That is, you can set the acknowledgment state of messages - in an existing subscription to the state captured by a snapshot. - - Returns: - Callable[[~.ListTopicSnapshotsRequest], - Awaitable[~.ListTopicSnapshotsResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'list_topic_snapshots' not in self._stubs: - self._stubs['list_topic_snapshots'] = self.grpc_channel.unary_unary( - '/google.pubsub.v1.Publisher/ListTopicSnapshots', - request_serializer=pubsub.ListTopicSnapshotsRequest.serialize, - response_deserializer=pubsub.ListTopicSnapshotsResponse.deserialize, - ) - return self._stubs['list_topic_snapshots'] - - @property - def delete_topic(self) -> Callable[ - [pubsub.DeleteTopicRequest], - Awaitable[empty_pb2.Empty]]: - r"""Return a callable for the delete topic method over gRPC. - - Deletes the topic with the given name. Returns ``NOT_FOUND`` if - the topic does not exist. After a topic is deleted, a new topic - may be created with the same name; this is an entirely new topic - with none of the old configuration or subscriptions. Existing - subscriptions to this topic are not deleted, but their ``topic`` - field is set to ``_deleted-topic_``. - - Returns: - Callable[[~.DeleteTopicRequest], - 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_topic' not in self._stubs: - self._stubs['delete_topic'] = self.grpc_channel.unary_unary( - '/google.pubsub.v1.Publisher/DeleteTopic', - request_serializer=pubsub.DeleteTopicRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_topic'] - - @property - def detach_subscription(self) -> Callable[ - [pubsub.DetachSubscriptionRequest], - Awaitable[pubsub.DetachSubscriptionResponse]]: - r"""Return a callable for the detach subscription method over gRPC. - - Detaches a subscription from this topic. All messages retained - in the subscription are dropped. Subsequent ``Pull`` and - ``StreamingPull`` requests will return FAILED_PRECONDITION. If - the subscription is a push subscription, pushes to the endpoint - will stop. - - Returns: - Callable[[~.DetachSubscriptionRequest], - Awaitable[~.DetachSubscriptionResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'detach_subscription' not in self._stubs: - self._stubs['detach_subscription'] = self.grpc_channel.unary_unary( - '/google.pubsub.v1.Publisher/DetachSubscription', - request_serializer=pubsub.DetachSubscriptionRequest.serialize, - response_deserializer=pubsub.DetachSubscriptionResponse.deserialize, - ) - return self._stubs['detach_subscription'] - - @property - def set_iam_policy( - self, - ) -> Callable[[iam_policy_pb2.SetIamPolicyRequest], Awaitable[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], - Awaitable[~.Policy]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "set_iam_policy" not in self._stubs: - self._stubs["set_iam_policy"] = self.grpc_channel.unary_unary( - "/google.iam.v1.IAMPolicy/SetIamPolicy", - request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString, - response_deserializer=policy_pb2.Policy.FromString, - ) - return self._stubs["set_iam_policy"] - - @property - def get_iam_policy( - self, - ) -> Callable[[iam_policy_pb2.GetIamPolicyRequest], Awaitable[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], - Awaitable[~.Policy]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "get_iam_policy" not in self._stubs: - self._stubs["get_iam_policy"] = self.grpc_channel.unary_unary( - "/google.iam.v1.IAMPolicy/GetIamPolicy", - request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, - response_deserializer=policy_pb2.Policy.FromString, - ) - return self._stubs["get_iam_policy"] - - @property - def test_iam_permissions( - self, - ) -> Callable[ - [iam_policy_pb2.TestIamPermissionsRequest], - Awaitable[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], - Awaitable[~.TestIamPermissionsResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "test_iam_permissions" not in self._stubs: - self._stubs["test_iam_permissions"] = self.grpc_channel.unary_unary( - "/google.iam.v1.IAMPolicy/TestIamPermissions", - request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString, - response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString, - ) - return self._stubs["test_iam_permissions"] - - 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_topic: gapic_v1.method_async.wrap_method( - self.create_topic, - default_retry=retries.AsyncRetry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.update_topic: gapic_v1.method_async.wrap_method( - self.update_topic, - default_retry=retries.AsyncRetry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.publish: gapic_v1.method_async.wrap_method( - self.publish, - default_retry=retries.AsyncRetry( - initial=0.1, - maximum=60.0, - multiplier=4, - predicate=retries.if_exception_type( - core_exceptions.Aborted, - core_exceptions.Cancelled, - core_exceptions.DeadlineExceeded, - core_exceptions.InternalServerError, - core_exceptions.ResourceExhausted, - core_exceptions.ServiceUnavailable, - core_exceptions.Unknown, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.get_topic: gapic_v1.method_async.wrap_method( - self.get_topic, - default_retry=retries.AsyncRetry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.Aborted, - core_exceptions.ServiceUnavailable, - core_exceptions.Unknown, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.list_topics: gapic_v1.method_async.wrap_method( - self.list_topics, - default_retry=retries.AsyncRetry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.Aborted, - core_exceptions.ServiceUnavailable, - core_exceptions.Unknown, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.list_topic_subscriptions: gapic_v1.method_async.wrap_method( - self.list_topic_subscriptions, - default_retry=retries.AsyncRetry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.Aborted, - core_exceptions.ServiceUnavailable, - core_exceptions.Unknown, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.list_topic_snapshots: gapic_v1.method_async.wrap_method( - self.list_topic_snapshots, - default_retry=retries.AsyncRetry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.Aborted, - core_exceptions.ServiceUnavailable, - core_exceptions.Unknown, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.delete_topic: gapic_v1.method_async.wrap_method( - self.delete_topic, - default_retry=retries.AsyncRetry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.detach_subscription: gapic_v1.method_async.wrap_method( - self.detach_subscription, - default_retry=retries.AsyncRetry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - } - - def close(self): - return self.grpc_channel.close() - - -__all__ = ( - 'PublisherGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v1/google/pubsub_v1/services/publisher/transports/rest.py b/owl-bot-staging/v1/google/pubsub_v1/services/publisher/transports/rest.py deleted file mode 100644 index 49df9e868..000000000 --- a/owl-bot-staging/v1/google/pubsub_v1/services/publisher/transports/rest.py +++ /dev/null @@ -1,1472 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -from google.auth.transport.requests import AuthorizedSession # type: ignore -import json # type: ignore -import grpc # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.api_core import exceptions as core_exceptions -from google.api_core import retry as retries -from google.api_core import rest_helpers -from google.api_core import rest_streaming -from google.api_core import 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 requests import __version__ as requests_version -import dataclasses -import re -from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union -import warnings - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object, None] # type: ignore - - -from google.iam.v1 import iam_policy_pb2 # type: ignore -from google.iam.v1 import policy_pb2 # type: ignore -from google.protobuf import empty_pb2 # type: ignore -from google.pubsub_v1.types import pubsub - -from .base import PublisherTransport, DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO - - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, - grpc_version=None, - rest_version=requests_version, -) - - -class PublisherRestInterceptor: - """Interceptor for Publisher. - - 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 PublisherRestTransport. - - .. code-block:: python - class MyCustomPublisherInterceptor(PublisherRestInterceptor): - def pre_create_topic(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_create_topic(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_delete_topic(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def pre_detach_subscription(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_detach_subscription(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_get_topic(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_topic(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_list_topics(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_list_topics(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_list_topic_snapshots(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_list_topic_snapshots(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_list_topic_subscriptions(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_list_topic_subscriptions(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_publish(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_publish(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_update_topic(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_update_topic(self, response): - logging.log(f"Received response: {response}") - return response - - transport = PublisherRestTransport(interceptor=MyCustomPublisherInterceptor()) - client = PublisherClient(transport=transport) - - - """ - def pre_create_topic(self, request: pubsub.Topic, metadata: Sequence[Tuple[str, str]]) -> Tuple[pubsub.Topic, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for create_topic - - Override in a subclass to manipulate the request or metadata - before they are sent to the Publisher server. - """ - return request, metadata - - def post_create_topic(self, response: pubsub.Topic) -> pubsub.Topic: - """Post-rpc interceptor for create_topic - - Override in a subclass to manipulate the response - after it is returned by the Publisher server but before - it is returned to user code. - """ - return response - def pre_delete_topic(self, request: pubsub.DeleteTopicRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[pubsub.DeleteTopicRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for delete_topic - - Override in a subclass to manipulate the request or metadata - before they are sent to the Publisher server. - """ - return request, metadata - - def pre_detach_subscription(self, request: pubsub.DetachSubscriptionRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[pubsub.DetachSubscriptionRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for detach_subscription - - Override in a subclass to manipulate the request or metadata - before they are sent to the Publisher server. - """ - return request, metadata - - def post_detach_subscription(self, response: pubsub.DetachSubscriptionResponse) -> pubsub.DetachSubscriptionResponse: - """Post-rpc interceptor for detach_subscription - - Override in a subclass to manipulate the response - after it is returned by the Publisher server but before - it is returned to user code. - """ - return response - def pre_get_topic(self, request: pubsub.GetTopicRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[pubsub.GetTopicRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_topic - - Override in a subclass to manipulate the request or metadata - before they are sent to the Publisher server. - """ - return request, metadata - - def post_get_topic(self, response: pubsub.Topic) -> pubsub.Topic: - """Post-rpc interceptor for get_topic - - Override in a subclass to manipulate the response - after it is returned by the Publisher server but before - it is returned to user code. - """ - return response - def pre_list_topics(self, request: pubsub.ListTopicsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[pubsub.ListTopicsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_topics - - Override in a subclass to manipulate the request or metadata - before they are sent to the Publisher server. - """ - return request, metadata - - def post_list_topics(self, response: pubsub.ListTopicsResponse) -> pubsub.ListTopicsResponse: - """Post-rpc interceptor for list_topics - - Override in a subclass to manipulate the response - after it is returned by the Publisher server but before - it is returned to user code. - """ - return response - def pre_list_topic_snapshots(self, request: pubsub.ListTopicSnapshotsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[pubsub.ListTopicSnapshotsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_topic_snapshots - - Override in a subclass to manipulate the request or metadata - before they are sent to the Publisher server. - """ - return request, metadata - - def post_list_topic_snapshots(self, response: pubsub.ListTopicSnapshotsResponse) -> pubsub.ListTopicSnapshotsResponse: - """Post-rpc interceptor for list_topic_snapshots - - Override in a subclass to manipulate the response - after it is returned by the Publisher server but before - it is returned to user code. - """ - return response - def pre_list_topic_subscriptions(self, request: pubsub.ListTopicSubscriptionsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[pubsub.ListTopicSubscriptionsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_topic_subscriptions - - Override in a subclass to manipulate the request or metadata - before they are sent to the Publisher server. - """ - return request, metadata - - def post_list_topic_subscriptions(self, response: pubsub.ListTopicSubscriptionsResponse) -> pubsub.ListTopicSubscriptionsResponse: - """Post-rpc interceptor for list_topic_subscriptions - - Override in a subclass to manipulate the response - after it is returned by the Publisher server but before - it is returned to user code. - """ - return response - def pre_publish(self, request: pubsub.PublishRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[pubsub.PublishRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for publish - - Override in a subclass to manipulate the request or metadata - before they are sent to the Publisher server. - """ - return request, metadata - - def post_publish(self, response: pubsub.PublishResponse) -> pubsub.PublishResponse: - """Post-rpc interceptor for publish - - Override in a subclass to manipulate the response - after it is returned by the Publisher server but before - it is returned to user code. - """ - return response - def pre_update_topic(self, request: pubsub.UpdateTopicRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[pubsub.UpdateTopicRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for update_topic - - Override in a subclass to manipulate the request or metadata - before they are sent to the Publisher server. - """ - return request, metadata - - def post_update_topic(self, response: pubsub.Topic) -> pubsub.Topic: - """Post-rpc interceptor for update_topic - - Override in a subclass to manipulate the response - after it is returned by the Publisher server but before - it is returned to user code. - """ - return response - - def pre_get_iam_policy( - self, request: iam_policy_pb2.GetIamPolicyRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[iam_policy_pb2.GetIamPolicyRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_iam_policy - - Override in a subclass to manipulate the request or metadata - before they are sent to the Publisher 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 Publisher server but before - it is returned to user code. - """ - return response - def pre_set_iam_policy( - self, request: iam_policy_pb2.SetIamPolicyRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[iam_policy_pb2.SetIamPolicyRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for set_iam_policy - - Override in a subclass to manipulate the request or metadata - before they are sent to the Publisher 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 Publisher server but before - it is returned to user code. - """ - return response - def pre_test_iam_permissions( - self, request: iam_policy_pb2.TestIamPermissionsRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[iam_policy_pb2.TestIamPermissionsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for test_iam_permissions - - Override in a subclass to manipulate the request or metadata - before they are sent to the Publisher 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 Publisher server but before - it is returned to user code. - """ - return response - - -@dataclasses.dataclass -class PublisherRestStub: - _session: AuthorizedSession - _host: str - _interceptor: PublisherRestInterceptor - - -class PublisherRestTransport(PublisherTransport): - """REST backend transport for Publisher. - - The service that an application uses to manipulate topics, - and to send messages to a topic. - - This 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 = 'pubsub.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - client_cert_source_for_mtls: Optional[Callable[[ - ], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - url_scheme: str = 'https', - interceptor: Optional[PublisherRestInterceptor] = None, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to (default: 'pubsub.googleapis.com'). - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client - certificate to configure mutual TLS HTTP channel. It is ignored - if ``channel`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you are developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - url_scheme: the protocol scheme for the API endpoint. Normally - "https", but for testing or local servers, - "http" can be specified. - """ - # Run the base constructor - # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. - # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the - # credentials object - 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 - ) - 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 PublisherRestInterceptor() - self._prep_wrapped_messages(client_info) - - class _CreateTopic(PublisherRestStub): - def __hash__(self): - return hash("CreateTopic") - - __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} - - def __call__(self, - request: pubsub.Topic, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> pubsub.Topic: - r"""Call the create topic method over HTTP. - - Args: - request (~.pubsub.Topic): - The request object. A topic resource. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.pubsub.Topic: - A topic resource. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'put', - 'uri': '/v1/{name=projects/*/topics/*}', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_create_topic(request, metadata) - pb_request = pubsub.Topic.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=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 = pubsub.Topic() - pb_resp = pubsub.Topic.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_create_topic(resp) - return resp - - class _DeleteTopic(PublisherRestStub): - def __hash__(self): - return hash("DeleteTopic") - - __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} - - def __call__(self, - request: pubsub.DeleteTopicRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ): - r"""Call the delete topic method over HTTP. - - Args: - request (~.pubsub.DeleteTopicRequest): - The request object. Request for the ``DeleteTopic`` method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'delete', - 'uri': '/v1/{topic=projects/*/topics/*}', - }, - ] - request, metadata = self._interceptor.pre_delete_topic(request, metadata) - pb_request = pubsub.DeleteTopicRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # 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 _DetachSubscription(PublisherRestStub): - def __hash__(self): - return hash("DetachSubscription") - - __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} - - def __call__(self, - request: pubsub.DetachSubscriptionRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> pubsub.DetachSubscriptionResponse: - r"""Call the detach subscription method over HTTP. - - Args: - request (~.pubsub.DetachSubscriptionRequest): - The request object. Request for the DetachSubscription - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.pubsub.DetachSubscriptionResponse: - Response for the DetachSubscription - method. Reserved for future use. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/{subscription=projects/*/subscriptions/*}:detach', - }, - ] - request, metadata = self._interceptor.pre_detach_subscription(request, metadata) - pb_request = pubsub.DetachSubscriptionRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # 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 = pubsub.DetachSubscriptionResponse() - pb_resp = pubsub.DetachSubscriptionResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_detach_subscription(resp) - return resp - - class _GetTopic(PublisherRestStub): - def __hash__(self): - return hash("GetTopic") - - __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} - - def __call__(self, - request: pubsub.GetTopicRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> pubsub.Topic: - r"""Call the get topic method over HTTP. - - Args: - request (~.pubsub.GetTopicRequest): - The request object. Request for the GetTopic method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.pubsub.Topic: - A topic resource. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{topic=projects/*/topics/*}', - }, - ] - request, metadata = self._interceptor.pre_get_topic(request, metadata) - pb_request = pubsub.GetTopicRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # 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 = pubsub.Topic() - pb_resp = pubsub.Topic.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_get_topic(resp) - return resp - - class _ListTopics(PublisherRestStub): - def __hash__(self): - return hash("ListTopics") - - __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} - - def __call__(self, - request: pubsub.ListTopicsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> pubsub.ListTopicsResponse: - r"""Call the list topics method over HTTP. - - Args: - request (~.pubsub.ListTopicsRequest): - The request object. Request for the ``ListTopics`` method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.pubsub.ListTopicsResponse: - Response for the ``ListTopics`` method. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{project=projects/*}/topics', - }, - ] - request, metadata = self._interceptor.pre_list_topics(request, metadata) - pb_request = pubsub.ListTopicsRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # 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 = pubsub.ListTopicsResponse() - pb_resp = pubsub.ListTopicsResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_list_topics(resp) - return resp - - class _ListTopicSnapshots(PublisherRestStub): - def __hash__(self): - return hash("ListTopicSnapshots") - - __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} - - def __call__(self, - request: pubsub.ListTopicSnapshotsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> pubsub.ListTopicSnapshotsResponse: - r"""Call the list topic snapshots method over HTTP. - - Args: - request (~.pubsub.ListTopicSnapshotsRequest): - The request object. Request for the ``ListTopicSnapshots`` method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.pubsub.ListTopicSnapshotsResponse: - Response for the ``ListTopicSnapshots`` method. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{topic=projects/*/topics/*}/snapshots', - }, - ] - request, metadata = self._interceptor.pre_list_topic_snapshots(request, metadata) - pb_request = pubsub.ListTopicSnapshotsRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # 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 = pubsub.ListTopicSnapshotsResponse() - pb_resp = pubsub.ListTopicSnapshotsResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_list_topic_snapshots(resp) - return resp - - class _ListTopicSubscriptions(PublisherRestStub): - def __hash__(self): - return hash("ListTopicSubscriptions") - - __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} - - def __call__(self, - request: pubsub.ListTopicSubscriptionsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> pubsub.ListTopicSubscriptionsResponse: - r"""Call the list topic subscriptions method over HTTP. - - Args: - request (~.pubsub.ListTopicSubscriptionsRequest): - The request object. Request for the ``ListTopicSubscriptions`` method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.pubsub.ListTopicSubscriptionsResponse: - Response for the ``ListTopicSubscriptions`` method. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{topic=projects/*/topics/*}/subscriptions', - }, - ] - request, metadata = self._interceptor.pre_list_topic_subscriptions(request, metadata) - pb_request = pubsub.ListTopicSubscriptionsRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # 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 = pubsub.ListTopicSubscriptionsResponse() - pb_resp = pubsub.ListTopicSubscriptionsResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_list_topic_subscriptions(resp) - return resp - - class _Publish(PublisherRestStub): - def __hash__(self): - return hash("Publish") - - __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} - - def __call__(self, - request: pubsub.PublishRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> pubsub.PublishResponse: - r"""Call the publish method over HTTP. - - Args: - request (~.pubsub.PublishRequest): - The request object. Request for the Publish method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.pubsub.PublishResponse: - Response for the ``Publish`` method. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/{topic=projects/*/topics/*}:publish', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_publish(request, metadata) - pb_request = pubsub.PublishRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=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 = pubsub.PublishResponse() - pb_resp = pubsub.PublishResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_publish(resp) - return resp - - class _UpdateTopic(PublisherRestStub): - def __hash__(self): - return hash("UpdateTopic") - - __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} - - def __call__(self, - request: pubsub.UpdateTopicRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> pubsub.Topic: - r"""Call the update topic method over HTTP. - - Args: - request (~.pubsub.UpdateTopicRequest): - The request object. Request for the UpdateTopic method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.pubsub.Topic: - A topic resource. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'patch', - 'uri': '/v1/{topic.name=projects/*/topics/*}', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_update_topic(request, metadata) - pb_request = pubsub.UpdateTopicRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=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 = pubsub.Topic() - pb_resp = pubsub.Topic.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_update_topic(resp) - return resp - - @property - def create_topic(self) -> Callable[ - [pubsub.Topic], - pubsub.Topic]: - # 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._CreateTopic(self._session, self._host, self._interceptor) # type: ignore - - @property - def delete_topic(self) -> Callable[ - [pubsub.DeleteTopicRequest], - 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._DeleteTopic(self._session, self._host, self._interceptor) # type: ignore - - @property - def detach_subscription(self) -> Callable[ - [pubsub.DetachSubscriptionRequest], - pubsub.DetachSubscriptionResponse]: - # 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._DetachSubscription(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_topic(self) -> Callable[ - [pubsub.GetTopicRequest], - pubsub.Topic]: - # 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._GetTopic(self._session, self._host, self._interceptor) # type: ignore - - @property - def list_topics(self) -> Callable[ - [pubsub.ListTopicsRequest], - pubsub.ListTopicsResponse]: - # 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._ListTopics(self._session, self._host, self._interceptor) # type: ignore - - @property - def list_topic_snapshots(self) -> Callable[ - [pubsub.ListTopicSnapshotsRequest], - pubsub.ListTopicSnapshotsResponse]: - # 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._ListTopicSnapshots(self._session, self._host, self._interceptor) # type: ignore - - @property - def list_topic_subscriptions(self) -> Callable[ - [pubsub.ListTopicSubscriptionsRequest], - pubsub.ListTopicSubscriptionsResponse]: - # 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._ListTopicSubscriptions(self._session, self._host, self._interceptor) # type: ignore - - @property - def publish(self) -> Callable[ - [pubsub.PublishRequest], - pubsub.PublishResponse]: - # 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._Publish(self._session, self._host, self._interceptor) # type: ignore - - @property - def update_topic(self) -> Callable[ - [pubsub.UpdateTopicRequest], - pubsub.Topic]: - # 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._UpdateTopic(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_iam_policy(self): - return self._GetIamPolicy(self._session, self._host, self._interceptor) # type: ignore - - class _GetIamPolicy(PublisherRestStub): - def __call__(self, - request: iam_policy_pb2.GetIamPolicyRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> policy_pb2.Policy: - - r"""Call the get iam policy method over HTTP. - - Args: - request (iam_policy_pb2.GetIamPolicyRequest): - The request object for GetIamPolicy method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - policy_pb2.Policy: Response from GetIamPolicy method. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{resource=projects/*/topics/*}:getIamPolicy', - }, -{ - 'method': 'get', - 'uri': '/v1/{resource=projects/*/subscriptions/*}:getIamPolicy', - }, -{ - 'method': 'get', - 'uri': '/v1/{resource=projects/*/snapshots/*}:getIamPolicy', - }, -{ - 'method': 'get', - 'uri': '/v1/{resource=projects/*/schemas/*}:getIamPolicy', - }, - ] - - request, metadata = self._interceptor.pre_get_iam_policy(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - resp = policy_pb2.Policy() - resp = json_format.Parse(response.content.decode("utf-8"), resp) - resp = self._interceptor.post_get_iam_policy(resp) - return resp - - @property - def set_iam_policy(self): - return self._SetIamPolicy(self._session, self._host, self._interceptor) # type: ignore - - class _SetIamPolicy(PublisherRestStub): - def __call__(self, - request: iam_policy_pb2.SetIamPolicyRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> policy_pb2.Policy: - - r"""Call the set iam policy method over HTTP. - - Args: - request (iam_policy_pb2.SetIamPolicyRequest): - The request object for SetIamPolicy method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - policy_pb2.Policy: Response from SetIamPolicy method. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/{resource=projects/*/topics/*}:setIamPolicy', - 'body': '*', - }, -{ - 'method': 'post', - 'uri': '/v1/{resource=projects/*/subscriptions/*}:setIamPolicy', - 'body': '*', - }, -{ - 'method': 'post', - 'uri': '/v1/{resource=projects/*/snapshots/*}:setIamPolicy', - 'body': '*', - }, -{ - 'method': 'post', - 'uri': '/v1/{resource=projects/*/schemas/*}:setIamPolicy', - 'body': '*', - }, - ] - - request, metadata = self._interceptor.pre_set_iam_policy(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - body = json.dumps(transcoded_request['body']) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - data=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) - - resp = policy_pb2.Policy() - resp = json_format.Parse(response.content.decode("utf-8"), resp) - resp = self._interceptor.post_set_iam_policy(resp) - return resp - - @property - def test_iam_permissions(self): - return self._TestIamPermissions(self._session, self._host, self._interceptor) # type: ignore - - class _TestIamPermissions(PublisherRestStub): - def __call__(self, - request: iam_policy_pb2.TestIamPermissionsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> iam_policy_pb2.TestIamPermissionsResponse: - - r"""Call the test iam permissions method over HTTP. - - Args: - request (iam_policy_pb2.TestIamPermissionsRequest): - The request object for TestIamPermissions method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - iam_policy_pb2.TestIamPermissionsResponse: Response from TestIamPermissions method. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/{resource=projects/*/subscriptions/*}:testIamPermissions', - 'body': '*', - }, -{ - 'method': 'post', - 'uri': '/v1/{resource=projects/*/topics/*}:testIamPermissions', - 'body': '*', - }, -{ - 'method': 'post', - 'uri': '/v1/{resource=projects/*/snapshots/*}:testIamPermissions', - 'body': '*', - }, -{ - 'method': 'post', - 'uri': '/v1/{resource=projects/*/schemas/*}:testIamPermissions', - 'body': '*', - }, - ] - - request, metadata = self._interceptor.pre_test_iam_permissions(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - body = json.dumps(transcoded_request['body']) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - data=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) - - resp = iam_policy_pb2.TestIamPermissionsResponse() - resp = json_format.Parse(response.content.decode("utf-8"), resp) - resp = self._interceptor.post_test_iam_permissions(resp) - return resp - - @property - def kind(self) -> str: - return "rest" - - def close(self): - self._session.close() - - -__all__=( - 'PublisherRestTransport', -) diff --git a/owl-bot-staging/v1/google/pubsub_v1/services/schema_service/__init__.py b/owl-bot-staging/v1/google/pubsub_v1/services/schema_service/__init__.py deleted file mode 100644 index 402d03a89..000000000 --- a/owl-bot-staging/v1/google/pubsub_v1/services/schema_service/__init__.py +++ /dev/null @@ -1,22 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from .client import SchemaServiceClient -from .async_client import SchemaServiceAsyncClient - -__all__ = ( - 'SchemaServiceClient', - 'SchemaServiceAsyncClient', -) diff --git a/owl-bot-staging/v1/google/pubsub_v1/services/schema_service/async_client.py b/owl-bot-staging/v1/google/pubsub_v1/services/schema_service/async_client.py deleted file mode 100644 index f9823faef..000000000 --- a/owl-bot-staging/v1/google/pubsub_v1/services/schema_service/async_client.py +++ /dev/null @@ -1,1629 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import re -from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union - -from google.pubsub_v1 import gapic_version as package_version - -from google.api_core.client_options import ClientOptions -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry_async as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - - -try: - OptionalRetry = Union[retries.AsyncRetry, gapic_v1.method._MethodDefault, None] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore - -from google.iam.v1 import iam_policy_pb2 # type: ignore -from google.iam.v1 import policy_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from google.pubsub_v1.services.schema_service import pagers -from google.pubsub_v1.types import schema -from google.pubsub_v1.types import schema as gp_schema -from .transports.base import SchemaServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import SchemaServiceGrpcAsyncIOTransport -from .client import SchemaServiceClient - - -class SchemaServiceAsyncClient: - """Service for doing schema-related operations.""" - - _client: SchemaServiceClient - - # Copy defaults from the synchronous client for use here. - # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. - DEFAULT_ENDPOINT = SchemaServiceClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = SchemaServiceClient.DEFAULT_MTLS_ENDPOINT - _DEFAULT_ENDPOINT_TEMPLATE = SchemaServiceClient._DEFAULT_ENDPOINT_TEMPLATE - _DEFAULT_UNIVERSE = SchemaServiceClient._DEFAULT_UNIVERSE - - schema_path = staticmethod(SchemaServiceClient.schema_path) - parse_schema_path = staticmethod(SchemaServiceClient.parse_schema_path) - common_billing_account_path = staticmethod(SchemaServiceClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(SchemaServiceClient.parse_common_billing_account_path) - common_folder_path = staticmethod(SchemaServiceClient.common_folder_path) - parse_common_folder_path = staticmethod(SchemaServiceClient.parse_common_folder_path) - common_organization_path = staticmethod(SchemaServiceClient.common_organization_path) - parse_common_organization_path = staticmethod(SchemaServiceClient.parse_common_organization_path) - common_project_path = staticmethod(SchemaServiceClient.common_project_path) - parse_common_project_path = staticmethod(SchemaServiceClient.parse_common_project_path) - common_location_path = staticmethod(SchemaServiceClient.common_location_path) - parse_common_location_path = staticmethod(SchemaServiceClient.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: - SchemaServiceAsyncClient: The constructed client. - """ - return SchemaServiceClient.from_service_account_info.__func__(SchemaServiceAsyncClient, info, *args, **kwargs) # type: ignore - - @classmethod - def from_service_account_file(cls, filename: str, *args, **kwargs): - """Creates an instance of this client using the provided credentials - file. - - Args: - filename (str): The path to the service account private key json - file. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - SchemaServiceAsyncClient: The constructed client. - """ - return SchemaServiceClient.from_service_account_file.__func__(SchemaServiceAsyncClient, filename, *args, **kwargs) # type: ignore - - from_service_account_json = from_service_account_file - - @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[ClientOptions] = None): - """Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variable is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - return SchemaServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore - - @property - def transport(self) -> SchemaServiceTransport: - """Returns the transport used by the client instance. - - Returns: - SchemaServiceTransport: The transport used by the client instance. - """ - return self._client.transport - - @property - def api_endpoint(self): - """Return the API endpoint used by the client instance. - - Returns: - str: The API endpoint used by the client instance. - """ - return self._client._api_endpoint - - @property - def universe_domain(self) -> str: - """Return the universe domain used by the client instance. - - Returns: - str: The universe domain used - by the client instance. - """ - return self._client._universe_domain - - get_transport_class = SchemaServiceClient.get_transport_class - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, SchemaServiceTransport, Callable[..., SchemaServiceTransport]]] = "grpc_asyncio", - client_options: Optional[ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the schema service 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,SchemaServiceTransport,Callable[..., SchemaServiceTransport]]]): - 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 SchemaServiceTransport constructor. - If set to None, a transport is chosen automatically. - client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): - Custom options for the client. - - 1. The ``api_endpoint`` property can be used to override the - default endpoint provided by the client when ``transport`` is - not explicitly provided. Only if this property is not set and - ``transport`` was not explicitly provided, the endpoint is - determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment - variable, which have one of the following values: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto-switch to the - default mTLS endpoint if client certificate is present; this is - the default value). - - 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide a client certificate for mTLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - - 3. The ``universe_domain`` property can be used to override the - default "googleapis.com" universe. Note that ``api_endpoint`` - property still takes precedence; and ``universe_domain`` is - currently not supported for mTLS. - - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - """ - self._client = SchemaServiceClient( - credentials=credentials, - transport=transport, - client_options=client_options, - client_info=client_info, - - ) - - async def create_schema(self, - request: Optional[Union[gp_schema.CreateSchemaRequest, dict]] = None, - *, - parent: Optional[str] = None, - schema: Optional[gp_schema.Schema] = None, - schema_id: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gp_schema.Schema: - r"""Creates a schema. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require 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 pubsub_v1 - - async def sample_create_schema(): - # Create a client - client = pubsub_v1.SchemaServiceAsyncClient() - - # Initialize request argument(s) - schema = pubsub_v1.Schema() - schema.name = "name_value" - - request = pubsub_v1.CreateSchemaRequest( - parent="parent_value", - schema=schema, - ) - - # Make the request - response = await client.create_schema(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.pubsub_v1.types.CreateSchemaRequest, dict]]): - The request object. Request for the CreateSchema method. - parent (:class:`str`): - Required. The name of the project in which to create the - schema. Format is ``projects/{project-id}``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - schema (:class:`google.pubsub_v1.types.Schema`): - Required. The schema object to create. - - This schema's ``name`` parameter is ignored. The schema - object returned by CreateSchema will have a ``name`` - made using the given ``parent`` and ``schema_id``. - - This corresponds to the ``schema`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - schema_id (:class:`str`): - The ID to use for the schema, which will become the - final component of the schema's resource name. - - See - https://cloud.google.com/pubsub/docs/pubsub-basics#resource_names - for resource name constraints. - - This corresponds to the ``schema_id`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.pubsub_v1.types.Schema: - A schema resource. - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, schema, schema_id]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, gp_schema.CreateSchemaRequest): - request = gp_schema.CreateSchemaRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if schema is not None: - request.schema = schema - if schema_id is not None: - request.schema_id = schema_id - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.create_schema] - - # Certain 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_schema(self, - request: Optional[Union[schema.GetSchemaRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> schema.Schema: - r"""Gets a schema. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require 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 pubsub_v1 - - async def sample_get_schema(): - # Create a client - client = pubsub_v1.SchemaServiceAsyncClient() - - # Initialize request argument(s) - request = pubsub_v1.GetSchemaRequest( - name="name_value", - ) - - # Make the request - response = await client.get_schema(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.pubsub_v1.types.GetSchemaRequest, dict]]): - The request object. Request for the GetSchema method. - name (:class:`str`): - Required. The name of the schema to get. Format is - ``projects/{project}/schemas/{schema}``. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.pubsub_v1.types.Schema: - A schema resource. - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, schema.GetSchemaRequest): - request = schema.GetSchemaRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - 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_schema] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def list_schemas(self, - request: Optional[Union[schema.ListSchemasRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListSchemasAsyncPager: - r"""Lists schemas in a project. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require 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 pubsub_v1 - - async def sample_list_schemas(): - # Create a client - client = pubsub_v1.SchemaServiceAsyncClient() - - # Initialize request argument(s) - request = pubsub_v1.ListSchemasRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_schemas(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.pubsub_v1.types.ListSchemasRequest, dict]]): - The request object. Request for the ``ListSchemas`` method. - parent (:class:`str`): - Required. The name of the project in which to list - schemas. Format is ``projects/{project-id}``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.pubsub_v1.services.schema_service.pagers.ListSchemasAsyncPager: - Response for the ListSchemas method. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, schema.ListSchemasRequest): - request = schema.ListSchemasRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply 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_schemas] - - # Certain 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.ListSchemasAsyncPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def list_schema_revisions(self, - request: Optional[Union[schema.ListSchemaRevisionsRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListSchemaRevisionsAsyncPager: - r"""Lists all schema revisions for the named schema. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require 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 pubsub_v1 - - async def sample_list_schema_revisions(): - # Create a client - client = pubsub_v1.SchemaServiceAsyncClient() - - # Initialize request argument(s) - request = pubsub_v1.ListSchemaRevisionsRequest( - name="name_value", - ) - - # Make the request - page_result = client.list_schema_revisions(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.pubsub_v1.types.ListSchemaRevisionsRequest, dict]]): - The request object. Request for the ``ListSchemaRevisions`` method. - name (:class:`str`): - Required. The name of the schema to - list revisions for. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.pubsub_v1.services.schema_service.pagers.ListSchemaRevisionsAsyncPager: - Response for the ListSchemaRevisions method. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, schema.ListSchemaRevisionsRequest): - request = schema.ListSchemaRevisionsRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - 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.list_schema_revisions] - - # Certain 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, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__aiter__` convenience method. - response = pagers.ListSchemaRevisionsAsyncPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def commit_schema(self, - request: Optional[Union[gp_schema.CommitSchemaRequest, dict]] = None, - *, - name: Optional[str] = None, - schema: Optional[gp_schema.Schema] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gp_schema.Schema: - r"""Commits a new schema revision to an existing schema. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require 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 pubsub_v1 - - async def sample_commit_schema(): - # Create a client - client = pubsub_v1.SchemaServiceAsyncClient() - - # Initialize request argument(s) - schema = pubsub_v1.Schema() - schema.name = "name_value" - - request = pubsub_v1.CommitSchemaRequest( - name="name_value", - schema=schema, - ) - - # Make the request - response = await client.commit_schema(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.pubsub_v1.types.CommitSchemaRequest, dict]]): - The request object. Request for CommitSchema method. - name (:class:`str`): - Required. The name of the schema we are revising. Format - is ``projects/{project}/schemas/{schema}``. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - schema (:class:`google.pubsub_v1.types.Schema`): - Required. The schema revision to - commit. - - This corresponds to the ``schema`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.pubsub_v1.types.Schema: - A schema resource. - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name, schema]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, gp_schema.CommitSchemaRequest): - request = gp_schema.CommitSchemaRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - if schema is not None: - request.schema = schema - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.commit_schema] - - # Certain 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 rollback_schema(self, - request: Optional[Union[schema.RollbackSchemaRequest, dict]] = None, - *, - name: Optional[str] = None, - revision_id: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> schema.Schema: - r"""Creates a new schema revision that is a copy of the provided - revision_id. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require 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 pubsub_v1 - - async def sample_rollback_schema(): - # Create a client - client = pubsub_v1.SchemaServiceAsyncClient() - - # Initialize request argument(s) - request = pubsub_v1.RollbackSchemaRequest( - name="name_value", - revision_id="revision_id_value", - ) - - # Make the request - response = await client.rollback_schema(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.pubsub_v1.types.RollbackSchemaRequest, dict]]): - The request object. Request for the ``RollbackSchema`` method. - name (:class:`str`): - Required. The schema being rolled - back with revision id. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - revision_id (:class:`str`): - Required. The revision ID to roll - back to. It must be a revision of the - same schema. - - Example: c7cfa2a8 - - This corresponds to the ``revision_id`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.pubsub_v1.types.Schema: - A schema resource. - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name, revision_id]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, schema.RollbackSchemaRequest): - request = schema.RollbackSchemaRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - if revision_id is not None: - request.revision_id = revision_id - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.rollback_schema] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def delete_schema_revision(self, - request: Optional[Union[schema.DeleteSchemaRevisionRequest, dict]] = None, - *, - name: Optional[str] = None, - revision_id: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> schema.Schema: - r"""Deletes a specific schema revision. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require 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 pubsub_v1 - - async def sample_delete_schema_revision(): - # Create a client - client = pubsub_v1.SchemaServiceAsyncClient() - - # Initialize request argument(s) - request = pubsub_v1.DeleteSchemaRevisionRequest( - name="name_value", - ) - - # Make the request - response = await client.delete_schema_revision(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.pubsub_v1.types.DeleteSchemaRevisionRequest, dict]]): - The request object. Request for the ``DeleteSchemaRevision`` method. - name (:class:`str`): - Required. The name of the schema revision to be deleted, - with a revision ID explicitly included. - - Example: ``projects/123/schemas/my-schema@c7cfa2a8`` - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - revision_id (:class:`str`): - Optional. This field is deprecated and should not be - used for specifying the revision ID. The revision ID - should be specified via the ``name`` parameter. - - This corresponds to the ``revision_id`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.pubsub_v1.types.Schema: - A schema resource. - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name, revision_id]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, schema.DeleteSchemaRevisionRequest): - request = schema.DeleteSchemaRevisionRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - if revision_id is not None: - request.revision_id = revision_id - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.delete_schema_revision] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def delete_schema(self, - request: Optional[Union[schema.DeleteSchemaRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes a schema. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require 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 pubsub_v1 - - async def sample_delete_schema(): - # Create a client - client = pubsub_v1.SchemaServiceAsyncClient() - - # Initialize request argument(s) - request = pubsub_v1.DeleteSchemaRequest( - name="name_value", - ) - - # Make the request - await client.delete_schema(request=request) - - Args: - request (Optional[Union[google.pubsub_v1.types.DeleteSchemaRequest, dict]]): - The request object. Request for the ``DeleteSchema`` method. - name (:class:`str`): - Required. Name of the schema to delete. Format is - ``projects/{project}/schemas/{schema}``. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, schema.DeleteSchemaRequest): - request = schema.DeleteSchemaRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - 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_schema] - - # Certain 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 validate_schema(self, - request: Optional[Union[gp_schema.ValidateSchemaRequest, dict]] = None, - *, - parent: Optional[str] = None, - schema: Optional[gp_schema.Schema] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gp_schema.ValidateSchemaResponse: - r"""Validates a schema. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require 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 pubsub_v1 - - async def sample_validate_schema(): - # Create a client - client = pubsub_v1.SchemaServiceAsyncClient() - - # Initialize request argument(s) - schema = pubsub_v1.Schema() - schema.name = "name_value" - - request = pubsub_v1.ValidateSchemaRequest( - parent="parent_value", - schema=schema, - ) - - # Make the request - response = await client.validate_schema(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.pubsub_v1.types.ValidateSchemaRequest, dict]]): - The request object. Request for the ``ValidateSchema`` method. - parent (:class:`str`): - Required. The name of the project in which to validate - schemas. Format is ``projects/{project-id}``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - schema (:class:`google.pubsub_v1.types.Schema`): - Required. The schema object to - validate. - - This corresponds to the ``schema`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.pubsub_v1.types.ValidateSchemaResponse: - Response for the ValidateSchema method. - Empty for now. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, schema]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, gp_schema.ValidateSchemaRequest): - request = gp_schema.ValidateSchemaRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if schema is not None: - request.schema = schema - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.validate_schema] - - # Certain 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 validate_message(self, - request: Optional[Union[schema.ValidateMessageRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> schema.ValidateMessageResponse: - r"""Validates a message against a schema. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require 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 pubsub_v1 - - async def sample_validate_message(): - # Create a client - client = pubsub_v1.SchemaServiceAsyncClient() - - # Initialize request argument(s) - request = pubsub_v1.ValidateMessageRequest( - name="name_value", - parent="parent_value", - ) - - # Make the request - response = await client.validate_message(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.pubsub_v1.types.ValidateMessageRequest, dict]]): - The request object. Request for the ``ValidateMessage`` method. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.pubsub_v1.types.ValidateMessageResponse: - Response for the ValidateMessage method. - Empty for now. - - """ - # 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, schema.ValidateMessageRequest): - request = schema.ValidateMessageRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.validate_message] - - # Certain 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 set_iam_policy( - self, - request: Optional[iam_policy_pb2.SetIamPolicyRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> policy_pb2.Policy: - r"""Sets the IAM access control policy on the specified function. - - Replaces any existing policy. - - Args: - request (:class:`~.policy_pb2.SetIamPolicyRequest`): - The request object. Request message for `SetIamPolicy` - method. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.policy_pb2.Policy: - Defines an Identity and Access Management (IAM) policy. - It is used to specify access control policies for Cloud - Platform resources. - A ``Policy`` is a collection of ``bindings``. A - ``binding`` binds one or more ``members`` to a single - ``role``. Members can be user accounts, service - accounts, Google groups, and domains (such as G Suite). - A ``role`` is a named list of permissions (defined by - IAM or configured by users). A ``binding`` can - optionally specify a ``condition``, which is a logic - expression that further constrains the role binding - based on attributes about the request and/or target - resource. - - **JSON Example** - - :: - { - "bindings": [ - { - "role": "roles/resourcemanager.organizationAdmin", - "members": [ - "user:mike@example.com", - "group:admins@example.com", - "domain:google.com", - "serviceAccount:my-project-id@appspot.gserviceaccount.com" - ] - }, - { - "role": "roles/resourcemanager.organizationViewer", - "members": ["user:eve@example.com"], - "condition": { - "title": "expirable access", - "description": "Does not grant access after Sep 2020", - "expression": "request.time < - timestamp('2020-10-01T00:00:00.000Z')", - } - } - ] - } - - **YAML Example** - - :: - - bindings: - - members: - - user:mike@example.com - - group:admins@example.com - - domain:google.com - - serviceAccount:my-project-id@appspot.gserviceaccount.com - role: roles/resourcemanager.organizationAdmin - - members: - - user:eve@example.com - role: roles/resourcemanager.organizationViewer - condition: - title: expirable access - description: Does not grant access after Sep 2020 - expression: request.time < timestamp('2020-10-01T00:00:00.000Z') - - For a description of IAM and its features, see the `IAM - developer's - guide `__. - """ - # Create or coerce a protobuf request object. - - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = iam_policy_pb2.SetIamPolicyRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.set_iam_policy, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("resource", request.resource),)), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - async def get_iam_policy( - self, - request: Optional[iam_policy_pb2.GetIamPolicyRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> policy_pb2.Policy: - r"""Gets the IAM access control policy for a function. - - Returns an empty policy if the function exists and does - not have a policy set. - - Args: - request (:class:`~.iam_policy_pb2.GetIamPolicyRequest`): - The request object. Request message for `GetIamPolicy` - method. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.policy_pb2.Policy: - Defines an Identity and Access Management (IAM) policy. - It is used to specify access control policies for Cloud - Platform resources. - A ``Policy`` is a collection of ``bindings``. A - ``binding`` binds one or more ``members`` to a single - ``role``. Members can be user accounts, service - accounts, Google groups, and domains (such as G Suite). - A ``role`` is a named list of permissions (defined by - IAM or configured by users). A ``binding`` can - optionally specify a ``condition``, which is a logic - expression that further constrains the role binding - based on attributes about the request and/or target - resource. - - **JSON Example** - - :: - - { - "bindings": [ - { - "role": "roles/resourcemanager.organizationAdmin", - "members": [ - "user:mike@example.com", - "group:admins@example.com", - "domain:google.com", - "serviceAccount:my-project-id@appspot.gserviceaccount.com" - ] - }, - { - "role": "roles/resourcemanager.organizationViewer", - "members": ["user:eve@example.com"], - "condition": { - "title": "expirable access", - "description": "Does not grant access after Sep 2020", - "expression": "request.time < - timestamp('2020-10-01T00:00:00.000Z')", - } - } - ] - } - - **YAML Example** - - :: - - bindings: - - members: - - user:mike@example.com - - group:admins@example.com - - domain:google.com - - serviceAccount:my-project-id@appspot.gserviceaccount.com - role: roles/resourcemanager.organizationAdmin - - members: - - user:eve@example.com - role: roles/resourcemanager.organizationViewer - condition: - title: expirable access - description: Does not grant access after Sep 2020 - expression: request.time < timestamp('2020-10-01T00:00:00.000Z') - - For a description of IAM and its features, see the `IAM - developer's - guide `__. - """ - # Create or coerce a protobuf request object. - - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = iam_policy_pb2.GetIamPolicyRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.get_iam_policy, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("resource", request.resource),)), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - async def test_iam_permissions( - self, - request: Optional[iam_policy_pb2.TestIamPermissionsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> iam_policy_pb2.TestIamPermissionsResponse: - r"""Tests the specified permissions against the IAM access control - policy for a function. - - If the function does not exist, this will - return an empty set of permissions, not a NOT_FOUND error. - - Args: - request (:class:`~.iam_policy_pb2.TestIamPermissionsRequest`): - The request object. Request message for - `TestIamPermissions` method. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~iam_policy_pb2.PolicyTestIamPermissionsResponse: - Response message for ``TestIamPermissions`` method. - """ - # Create or coerce a protobuf request object. - - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = iam_policy_pb2.TestIamPermissionsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.test_iam_permissions, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("resource", request.resource),)), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - async def __aenter__(self) -> "SchemaServiceAsyncClient": - return self - - async def __aexit__(self, exc_type, exc, tb): - await self.transport.close() - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -__all__ = ( - "SchemaServiceAsyncClient", -) diff --git a/owl-bot-staging/v1/google/pubsub_v1/services/schema_service/client.py b/owl-bot-staging/v1/google/pubsub_v1/services/schema_service/client.py deleted file mode 100644 index 6d11b3650..000000000 --- a/owl-bot-staging/v1/google/pubsub_v1/services/schema_service/client.py +++ /dev/null @@ -1,1978 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import os -import re -from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast -import warnings - -from google.pubsub_v1 import gapic_version as package_version - -from google.api_core import client_options as client_options_lib -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport import mtls # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth.exceptions import MutualTLSChannelError # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object, None] # type: ignore - -from google.iam.v1 import iam_policy_pb2 # type: ignore -from google.iam.v1 import policy_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from google.pubsub_v1.services.schema_service import pagers -from google.pubsub_v1.types import schema -from google.pubsub_v1.types import schema as gp_schema -from .transports.base import SchemaServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import SchemaServiceGrpcTransport -from .transports.grpc_asyncio import SchemaServiceGrpcAsyncIOTransport -from .transports.rest import SchemaServiceRestTransport - - -class SchemaServiceClientMeta(type): - """Metaclass for the SchemaService 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[SchemaServiceTransport]] - _transport_registry["grpc"] = SchemaServiceGrpcTransport - _transport_registry["grpc_asyncio"] = SchemaServiceGrpcAsyncIOTransport - _transport_registry["rest"] = SchemaServiceRestTransport - - def get_transport_class(cls, - label: Optional[str] = None, - ) -> Type[SchemaServiceTransport]: - """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 SchemaServiceClient(metaclass=SchemaServiceClientMeta): - """Service for doing schema-related operations.""" - - @staticmethod - def _get_default_mtls_endpoint(api_endpoint): - """Converts api endpoint to mTLS endpoint. - - Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to - "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. - Args: - api_endpoint (Optional[str]): the api endpoint to convert. - Returns: - str: converted mTLS api endpoint. - """ - if not api_endpoint: - return api_endpoint - - mtls_endpoint_re = re.compile( - r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" - ) - - m = mtls_endpoint_re.match(api_endpoint) - name, mtls, sandbox, googledomain = m.groups() - if mtls or not googledomain: - return api_endpoint - - if sandbox: - return api_endpoint.replace( - "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" - ) - - return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") - - # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. - DEFAULT_ENDPOINT = "pubsub.googleapis.com" - DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore - DEFAULT_ENDPOINT - ) - - _DEFAULT_ENDPOINT_TEMPLATE = "pubsub.{UNIVERSE_DOMAIN}" - _DEFAULT_UNIVERSE = "googleapis.com" - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - Args: - info (dict): The service account private key info. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - SchemaServiceClient: 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: - SchemaServiceClient: 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) -> SchemaServiceTransport: - """Returns the transport used by the client instance. - - Returns: - SchemaServiceTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def schema_path(project: str,schema: str,) -> str: - """Returns a fully-qualified schema string.""" - return "projects/{project}/schemas/{schema}".format(project=project, schema=schema, ) - - @staticmethod - def parse_schema_path(path: str) -> Dict[str,str]: - """Parses a schema path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/schemas/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_billing_account_path(billing_account: str, ) -> str: - """Returns a fully-qualified billing_account string.""" - return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - - @staticmethod - def parse_common_billing_account_path(path: str) -> Dict[str,str]: - """Parse a billing_account path into its component segments.""" - m = re.match(r"^billingAccounts/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_folder_path(folder: str, ) -> str: - """Returns a fully-qualified folder string.""" - return "folders/{folder}".format(folder=folder, ) - - @staticmethod - def parse_common_folder_path(path: str) -> Dict[str,str]: - """Parse a folder path into its component segments.""" - m = re.match(r"^folders/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_organization_path(organization: str, ) -> str: - """Returns a fully-qualified organization string.""" - return "organizations/{organization}".format(organization=organization, ) - - @staticmethod - def parse_common_organization_path(path: str) -> Dict[str,str]: - """Parse a organization path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_project_path(project: str, ) -> str: - """Returns a fully-qualified project string.""" - return "projects/{project}".format(project=project, ) - - @staticmethod - def parse_common_project_path(path: str) -> Dict[str,str]: - """Parse a project path into its component segments.""" - m = re.match(r"^projects/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_location_path(project: str, location: str, ) -> str: - """Returns a fully-qualified location string.""" - return "projects/{project}/locations/{location}".format(project=project, location=location, ) - - @staticmethod - def parse_common_location_path(path: str) -> Dict[str,str]: - """Parse a location path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): - """Deprecated. Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variable is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - - warnings.warn("get_mtls_endpoint_and_cert_source is deprecated. Use the api_endpoint property instead.", - DeprecationWarning) - if client_options is None: - client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") - use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") - if use_mtls_endpoint not in ("auto", "never", "always"): - raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") - - # Figure out the client cert source to use. - client_cert_source = None - if use_client_cert == "true": - if client_options.client_cert_source: - client_cert_source = client_options.client_cert_source - elif mtls.has_default_client_cert_source(): - client_cert_source = mtls.default_client_cert_source() - - # Figure out which api endpoint to use. - if client_options.api_endpoint is not None: - api_endpoint = client_options.api_endpoint - elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): - api_endpoint = cls.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = cls.DEFAULT_ENDPOINT - - return api_endpoint, client_cert_source - - @staticmethod - def _read_environment_variables(): - """Returns the environment variables used by the client. - - Returns: - Tuple[bool, str, str]: returns the GOOGLE_API_USE_CLIENT_CERTIFICATE, - GOOGLE_API_USE_MTLS_ENDPOINT, and GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variables. - - Raises: - ValueError: If GOOGLE_API_USE_CLIENT_CERTIFICATE is not - any of ["true", "false"]. - google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT - is not any of ["auto", "never", "always"]. - """ - use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false").lower() - use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto").lower() - universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") - if use_mtls_endpoint not in ("auto", "never", "always"): - raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env - - @staticmethod - def _get_client_cert_source(provided_cert_source, use_cert_flag): - """Return the client cert source to be used by the client. - - Args: - provided_cert_source (bytes): The client certificate source provided. - use_cert_flag (bool): A flag indicating whether to use the client certificate. - - Returns: - bytes or None: The client cert source to be used by the client. - """ - client_cert_source = None - if use_cert_flag: - if provided_cert_source: - client_cert_source = provided_cert_source - elif mtls.has_default_client_cert_source(): - client_cert_source = mtls.default_client_cert_source() - return client_cert_source - - @staticmethod - def _get_api_endpoint(api_override, client_cert_source, universe_domain, use_mtls_endpoint): - """Return the API endpoint used by the client. - - Args: - api_override (str): The API endpoint override. If specified, this is always - the return value of this function and the other arguments are not used. - client_cert_source (bytes): The client certificate source used by the client. - universe_domain (str): The universe domain used by the client. - use_mtls_endpoint (str): How to use the mTLS endpoint, which depends also on the other parameters. - Possible values are "always", "auto", or "never". - - Returns: - str: The API endpoint to be used by the client. - """ - if api_override is not None: - api_endpoint = api_override - elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): - _default_universe = SchemaServiceClient._DEFAULT_UNIVERSE - if universe_domain != _default_universe: - raise MutualTLSChannelError(f"mTLS is not supported in any universe other than {_default_universe}.") - api_endpoint = SchemaServiceClient.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = SchemaServiceClient._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 = SchemaServiceClient._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 - - @staticmethod - def _compare_universes(client_universe: str, - credentials: ga_credentials.Credentials) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = SchemaServiceClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError("The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default.") - return True - - 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. - """ - self._is_universe_domain_valid = (self._is_universe_domain_valid or - SchemaServiceClient._compare_universes(self.universe_domain, self.transport._credentials)) - return self._is_universe_domain_valid - - @property - def api_endpoint(self): - """Return the API endpoint used by the client instance. - - Returns: - str: The API endpoint used by the client instance. - """ - return self._api_endpoint - - @property - def universe_domain(self) -> str: - """Return the universe domain used by the client instance. - - Returns: - str: The universe domain used by the client instance. - """ - return self._universe_domain - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, SchemaServiceTransport, Callable[..., SchemaServiceTransport]]] = None, - client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the schema service client. - - Args: - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - transport (Optional[Union[str,SchemaServiceTransport,Callable[..., SchemaServiceTransport]]]): - 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 SchemaServiceTransport constructor. - If set to None, a transport is chosen automatically. - client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): - Custom options for the client. - - 1. The ``api_endpoint`` property can be used to override the - default endpoint provided by the client when ``transport`` is - not explicitly provided. Only if this property is not set and - ``transport`` was not explicitly provided, the endpoint is - determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment - variable, which have one of the following values: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto-switch to the - default mTLS endpoint if client certificate is present; this is - the default value). - - 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide a client certificate for mTLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - - 3. The ``universe_domain`` property can be used to override the - default "googleapis.com" universe. Note that the ``api_endpoint`` - property still takes precedence; and ``universe_domain`` is - currently not supported for mTLS. - - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - """ - self._client_options = client_options - if isinstance(self._client_options, dict): - self._client_options = client_options_lib.from_dict(self._client_options) - if self._client_options is None: - self._client_options = client_options_lib.ClientOptions() - self._client_options = cast(client_options_lib.ClientOptions, self._client_options) - - universe_domain_opt = getattr(self._client_options, 'universe_domain', None) - - self._use_client_cert, self._use_mtls_endpoint, self._universe_domain_env = SchemaServiceClient._read_environment_variables() - self._client_cert_source = SchemaServiceClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) - self._universe_domain = SchemaServiceClient._get_universe_domain(universe_domain_opt, self._universe_domain_env) - self._api_endpoint = None # updated below, depending on `transport` - - # Initialize the universe domain validation. - self._is_universe_domain_valid = False - - api_key_value = getattr(self._client_options, "api_key", None) - if api_key_value and credentials: - raise ValueError("client_options.api_key and credentials are mutually exclusive") - - # Save or instantiate the transport. - # Ordinarily, we provide the transport, but allowing a custom transport - # instance provides an extensibility point for unusual situations. - transport_provided = isinstance(transport, SchemaServiceTransport) - if transport_provided: - # transport is a SchemaServiceTransport 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(SchemaServiceTransport, transport) - self._api_endpoint = self._transport.host - - self._api_endpoint = (self._api_endpoint or - SchemaServiceClient._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[SchemaServiceTransport], Callable[..., SchemaServiceTransport]] = ( - SchemaServiceClient.get_transport_class(transport) - if isinstance(transport, str) or transport is None - else cast(Callable[..., SchemaServiceTransport], transport) - ) - # initialize with the provided callable or the passed in class - self._transport = transport_init( - credentials=credentials, - credentials_file=self._client_options.credentials_file, - host=self._api_endpoint, - scopes=self._client_options.scopes, - client_cert_source_for_mtls=self._client_cert_source, - quota_project_id=self._client_options.quota_project_id, - client_info=client_info, - always_use_jwt_access=True, - api_audience=self._client_options.api_audience, - ) - - def create_schema(self, - request: Optional[Union[gp_schema.CreateSchemaRequest, dict]] = None, - *, - parent: Optional[str] = None, - schema: Optional[gp_schema.Schema] = None, - schema_id: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gp_schema.Schema: - r"""Creates a schema. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require 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 pubsub_v1 - - def sample_create_schema(): - # Create a client - client = pubsub_v1.SchemaServiceClient() - - # Initialize request argument(s) - schema = pubsub_v1.Schema() - schema.name = "name_value" - - request = pubsub_v1.CreateSchemaRequest( - parent="parent_value", - schema=schema, - ) - - # Make the request - response = client.create_schema(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.pubsub_v1.types.CreateSchemaRequest, dict]): - The request object. Request for the CreateSchema method. - parent (str): - Required. The name of the project in which to create the - schema. Format is ``projects/{project-id}``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - schema (google.pubsub_v1.types.Schema): - Required. The schema object to create. - - This schema's ``name`` parameter is ignored. The schema - object returned by CreateSchema will have a ``name`` - made using the given ``parent`` and ``schema_id``. - - This corresponds to the ``schema`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - schema_id (str): - The ID to use for the schema, which will become the - final component of the schema's resource name. - - See - https://cloud.google.com/pubsub/docs/pubsub-basics#resource_names - for resource name constraints. - - This corresponds to the ``schema_id`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.pubsub_v1.types.Schema: - A schema resource. - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, schema, schema_id]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, gp_schema.CreateSchemaRequest): - request = gp_schema.CreateSchemaRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if schema is not None: - request.schema = schema - if schema_id is not None: - request.schema_id = schema_id - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_schema] - - # Certain 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_schema(self, - request: Optional[Union[schema.GetSchemaRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> schema.Schema: - r"""Gets a schema. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require 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 pubsub_v1 - - def sample_get_schema(): - # Create a client - client = pubsub_v1.SchemaServiceClient() - - # Initialize request argument(s) - request = pubsub_v1.GetSchemaRequest( - name="name_value", - ) - - # Make the request - response = client.get_schema(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.pubsub_v1.types.GetSchemaRequest, dict]): - The request object. Request for the GetSchema method. - name (str): - Required. The name of the schema to get. Format is - ``projects/{project}/schemas/{schema}``. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.pubsub_v1.types.Schema: - A schema resource. - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, schema.GetSchemaRequest): - request = schema.GetSchemaRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - 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_schema] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def list_schemas(self, - request: Optional[Union[schema.ListSchemasRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListSchemasPager: - r"""Lists schemas in a project. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require 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 pubsub_v1 - - def sample_list_schemas(): - # Create a client - client = pubsub_v1.SchemaServiceClient() - - # Initialize request argument(s) - request = pubsub_v1.ListSchemasRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_schemas(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.pubsub_v1.types.ListSchemasRequest, dict]): - The request object. Request for the ``ListSchemas`` method. - parent (str): - Required. The name of the project in which to list - schemas. Format is ``projects/{project-id}``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.pubsub_v1.services.schema_service.pagers.ListSchemasPager: - Response for the ListSchemas method. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, schema.ListSchemasRequest): - request = schema.ListSchemasRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply 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_schemas] - - # Certain 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.ListSchemasPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def list_schema_revisions(self, - request: Optional[Union[schema.ListSchemaRevisionsRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListSchemaRevisionsPager: - r"""Lists all schema revisions for the named schema. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require 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 pubsub_v1 - - def sample_list_schema_revisions(): - # Create a client - client = pubsub_v1.SchemaServiceClient() - - # Initialize request argument(s) - request = pubsub_v1.ListSchemaRevisionsRequest( - name="name_value", - ) - - # Make the request - page_result = client.list_schema_revisions(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.pubsub_v1.types.ListSchemaRevisionsRequest, dict]): - The request object. Request for the ``ListSchemaRevisions`` method. - name (str): - Required. The name of the schema to - list revisions for. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.pubsub_v1.services.schema_service.pagers.ListSchemaRevisionsPager: - Response for the ListSchemaRevisions method. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, schema.ListSchemaRevisionsRequest): - request = schema.ListSchemaRevisionsRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - 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.list_schema_revisions] - - # Certain 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, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__iter__` convenience method. - response = pagers.ListSchemaRevisionsPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def commit_schema(self, - request: Optional[Union[gp_schema.CommitSchemaRequest, dict]] = None, - *, - name: Optional[str] = None, - schema: Optional[gp_schema.Schema] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gp_schema.Schema: - r"""Commits a new schema revision to an existing schema. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require 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 pubsub_v1 - - def sample_commit_schema(): - # Create a client - client = pubsub_v1.SchemaServiceClient() - - # Initialize request argument(s) - schema = pubsub_v1.Schema() - schema.name = "name_value" - - request = pubsub_v1.CommitSchemaRequest( - name="name_value", - schema=schema, - ) - - # Make the request - response = client.commit_schema(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.pubsub_v1.types.CommitSchemaRequest, dict]): - The request object. Request for CommitSchema method. - name (str): - Required. The name of the schema we are revising. Format - is ``projects/{project}/schemas/{schema}``. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - schema (google.pubsub_v1.types.Schema): - Required. The schema revision to - commit. - - This corresponds to the ``schema`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.pubsub_v1.types.Schema: - A schema resource. - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name, schema]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, gp_schema.CommitSchemaRequest): - request = gp_schema.CommitSchemaRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - if schema is not None: - request.schema = schema - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.commit_schema] - - # Certain 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 rollback_schema(self, - request: Optional[Union[schema.RollbackSchemaRequest, dict]] = None, - *, - name: Optional[str] = None, - revision_id: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> schema.Schema: - r"""Creates a new schema revision that is a copy of the provided - revision_id. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require 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 pubsub_v1 - - def sample_rollback_schema(): - # Create a client - client = pubsub_v1.SchemaServiceClient() - - # Initialize request argument(s) - request = pubsub_v1.RollbackSchemaRequest( - name="name_value", - revision_id="revision_id_value", - ) - - # Make the request - response = client.rollback_schema(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.pubsub_v1.types.RollbackSchemaRequest, dict]): - The request object. Request for the ``RollbackSchema`` method. - name (str): - Required. The schema being rolled - back with revision id. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - revision_id (str): - Required. The revision ID to roll - back to. It must be a revision of the - same schema. - - Example: c7cfa2a8 - - This corresponds to the ``revision_id`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.pubsub_v1.types.Schema: - A schema resource. - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name, revision_id]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, schema.RollbackSchemaRequest): - request = schema.RollbackSchemaRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - if revision_id is not None: - request.revision_id = revision_id - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.rollback_schema] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def delete_schema_revision(self, - request: Optional[Union[schema.DeleteSchemaRevisionRequest, dict]] = None, - *, - name: Optional[str] = None, - revision_id: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> schema.Schema: - r"""Deletes a specific schema revision. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require 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 pubsub_v1 - - def sample_delete_schema_revision(): - # Create a client - client = pubsub_v1.SchemaServiceClient() - - # Initialize request argument(s) - request = pubsub_v1.DeleteSchemaRevisionRequest( - name="name_value", - ) - - # Make the request - response = client.delete_schema_revision(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.pubsub_v1.types.DeleteSchemaRevisionRequest, dict]): - The request object. Request for the ``DeleteSchemaRevision`` method. - name (str): - Required. The name of the schema revision to be deleted, - with a revision ID explicitly included. - - Example: ``projects/123/schemas/my-schema@c7cfa2a8`` - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - revision_id (str): - Optional. This field is deprecated and should not be - used for specifying the revision ID. The revision ID - should be specified via the ``name`` parameter. - - This corresponds to the ``revision_id`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.pubsub_v1.types.Schema: - A schema resource. - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name, revision_id]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, schema.DeleteSchemaRevisionRequest): - request = schema.DeleteSchemaRevisionRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - if revision_id is not None: - request.revision_id = revision_id - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.delete_schema_revision] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def delete_schema(self, - request: Optional[Union[schema.DeleteSchemaRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes a schema. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require 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 pubsub_v1 - - def sample_delete_schema(): - # Create a client - client = pubsub_v1.SchemaServiceClient() - - # Initialize request argument(s) - request = pubsub_v1.DeleteSchemaRequest( - name="name_value", - ) - - # Make the request - client.delete_schema(request=request) - - Args: - request (Union[google.pubsub_v1.types.DeleteSchemaRequest, dict]): - The request object. Request for the ``DeleteSchema`` method. - name (str): - Required. Name of the schema to delete. Format is - ``projects/{project}/schemas/{schema}``. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, schema.DeleteSchemaRequest): - request = schema.DeleteSchemaRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - 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_schema] - - # Certain 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 validate_schema(self, - request: Optional[Union[gp_schema.ValidateSchemaRequest, dict]] = None, - *, - parent: Optional[str] = None, - schema: Optional[gp_schema.Schema] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gp_schema.ValidateSchemaResponse: - r"""Validates a schema. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require 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 pubsub_v1 - - def sample_validate_schema(): - # Create a client - client = pubsub_v1.SchemaServiceClient() - - # Initialize request argument(s) - schema = pubsub_v1.Schema() - schema.name = "name_value" - - request = pubsub_v1.ValidateSchemaRequest( - parent="parent_value", - schema=schema, - ) - - # Make the request - response = client.validate_schema(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.pubsub_v1.types.ValidateSchemaRequest, dict]): - The request object. Request for the ``ValidateSchema`` method. - parent (str): - Required. The name of the project in which to validate - schemas. Format is ``projects/{project-id}``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - schema (google.pubsub_v1.types.Schema): - Required. The schema object to - validate. - - This corresponds to the ``schema`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.pubsub_v1.types.ValidateSchemaResponse: - Response for the ValidateSchema method. - Empty for now. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, schema]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, gp_schema.ValidateSchemaRequest): - request = gp_schema.ValidateSchemaRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if schema is not None: - request.schema = schema - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.validate_schema] - - # Certain 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 validate_message(self, - request: Optional[Union[schema.ValidateMessageRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> schema.ValidateMessageResponse: - r"""Validates a message against a schema. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require 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 pubsub_v1 - - def sample_validate_message(): - # Create a client - client = pubsub_v1.SchemaServiceClient() - - # Initialize request argument(s) - request = pubsub_v1.ValidateMessageRequest( - name="name_value", - parent="parent_value", - ) - - # Make the request - response = client.validate_message(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.pubsub_v1.types.ValidateMessageRequest, dict]): - The request object. Request for the ``ValidateMessage`` method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.pubsub_v1.types.ValidateMessageResponse: - Response for the ValidateMessage method. - Empty for now. - - """ - # 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, schema.ValidateMessageRequest): - request = schema.ValidateMessageRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.validate_message] - - # Certain 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 __enter__(self) -> "SchemaServiceClient": - 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 set_iam_policy( - self, - request: Optional[iam_policy_pb2.SetIamPolicyRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> policy_pb2.Policy: - r"""Sets the IAM access control policy on the specified function. - - Replaces any existing policy. - - Args: - request (:class:`~.iam_policy_pb2.SetIamPolicyRequest`): - The request object. Request message for `SetIamPolicy` - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.policy_pb2.Policy: - Defines an Identity and Access Management (IAM) policy. - It is used to specify access control policies for Cloud - Platform resources. - A ``Policy`` is a collection of ``bindings``. A - ``binding`` binds one or more ``members`` to a single - ``role``. Members can be user accounts, service - accounts, Google groups, and domains (such as G Suite). - A ``role`` is a named list of permissions (defined by - IAM or configured by users). A ``binding`` can - optionally specify a ``condition``, which is a logic - expression that further constrains the role binding - based on attributes about the request and/or target - resource. - - **JSON Example** - - :: - - { - "bindings": [ - { - "role": "roles/resourcemanager.organizationAdmin", - "members": [ - "user:mike@example.com", - "group:admins@example.com", - "domain:google.com", - "serviceAccount:my-project-id@appspot.gserviceaccount.com" - ] - }, - { - "role": "roles/resourcemanager.organizationViewer", - "members": ["user:eve@example.com"], - "condition": { - "title": "expirable access", - "description": "Does not grant access after Sep 2020", - "expression": "request.time < - timestamp('2020-10-01T00:00:00.000Z')", - } - } - ] - } - - **YAML Example** - - :: - - bindings: - - members: - - user:mike@example.com - - group:admins@example.com - - domain:google.com - - serviceAccount:my-project-id@appspot.gserviceaccount.com - role: roles/resourcemanager.organizationAdmin - - members: - - user:eve@example.com - role: roles/resourcemanager.organizationViewer - condition: - title: expirable access - description: Does not grant access after Sep 2020 - expression: request.time < timestamp('2020-10-01T00:00:00.000Z') - - For a description of IAM and its features, see the `IAM - developer's - guide `__. - """ - # Create or coerce a protobuf request object. - - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = iam_policy_pb2.SetIamPolicyRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.set_iam_policy, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("resource", request.resource),)), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - def get_iam_policy( - self, - request: Optional[iam_policy_pb2.GetIamPolicyRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> policy_pb2.Policy: - r"""Gets the IAM access control policy for a function. - - Returns an empty policy if the function exists and does not have a - policy set. - - Args: - request (:class:`~.iam_policy_pb2.GetIamPolicyRequest`): - The request object. Request message for `GetIamPolicy` - method. - retry (google.api_core.retry.Retry): Designation of what errors, if - any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.policy_pb2.Policy: - Defines an Identity and Access Management (IAM) policy. - It is used to specify access control policies for Cloud - Platform resources. - A ``Policy`` is a collection of ``bindings``. A - ``binding`` binds one or more ``members`` to a single - ``role``. Members can be user accounts, service - accounts, Google groups, and domains (such as G Suite). - A ``role`` is a named list of permissions (defined by - IAM or configured by users). A ``binding`` can - optionally specify a ``condition``, which is a logic - expression that further constrains the role binding - based on attributes about the request and/or target - resource. - - **JSON Example** - - :: - - { - "bindings": [ - { - "role": "roles/resourcemanager.organizationAdmin", - "members": [ - "user:mike@example.com", - "group:admins@example.com", - "domain:google.com", - "serviceAccount:my-project-id@appspot.gserviceaccount.com" - ] - }, - { - "role": "roles/resourcemanager.organizationViewer", - "members": ["user:eve@example.com"], - "condition": { - "title": "expirable access", - "description": "Does not grant access after Sep 2020", - "expression": "request.time < - timestamp('2020-10-01T00:00:00.000Z')", - } - } - ] - } - - **YAML Example** - - :: - - bindings: - - members: - - user:mike@example.com - - group:admins@example.com - - domain:google.com - - serviceAccount:my-project-id@appspot.gserviceaccount.com - role: roles/resourcemanager.organizationAdmin - - members: - - user:eve@example.com - role: roles/resourcemanager.organizationViewer - condition: - title: expirable access - description: Does not grant access after Sep 2020 - expression: request.time < timestamp('2020-10-01T00:00:00.000Z') - - For a description of IAM and its features, see the `IAM - developer's - guide `__. - """ - # Create or coerce a protobuf request object. - - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = iam_policy_pb2.GetIamPolicyRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.get_iam_policy, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("resource", request.resource),)), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - def test_iam_permissions( - self, - request: Optional[iam_policy_pb2.TestIamPermissionsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> iam_policy_pb2.TestIamPermissionsResponse: - r"""Tests the specified IAM permissions against the IAM access control - policy for a function. - - If the function does not exist, this will return an empty set - of permissions, not a NOT_FOUND error. - - Args: - request (:class:`~.iam_policy_pb2.TestIamPermissionsRequest`): - The request object. Request message for - `TestIamPermissions` method. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.iam_policy_pb2.TestIamPermissionsResponse: - Response message for ``TestIamPermissions`` method. - """ - # Create or coerce a protobuf request object. - - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = iam_policy_pb2.TestIamPermissionsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.test_iam_permissions, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("resource", request.resource),)), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -__all__ = ( - "SchemaServiceClient", -) diff --git a/owl-bot-staging/v1/google/pubsub_v1/services/schema_service/pagers.py b/owl-bot-staging/v1/google/pubsub_v1/services/schema_service/pagers.py deleted file mode 100644 index 6e4fe5222..000000000 --- a/owl-bot-staging/v1/google/pubsub_v1/services/schema_service/pagers.py +++ /dev/null @@ -1,297 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.api_core import retry_async as retries_async -from typing import Any, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator, Union -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] - OptionalAsyncRetry = Union[retries_async.AsyncRetry, gapic_v1.method._MethodDefault, None] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object, None] # type: ignore - OptionalAsyncRetry = Union[retries_async.AsyncRetry, object, None] # type: ignore - -from google.pubsub_v1.types import schema - - -class ListSchemasPager: - """A pager for iterating through ``list_schemas`` requests. - - This class thinly wraps an initial - :class:`google.pubsub_v1.types.ListSchemasResponse` object, and - provides an ``__iter__`` method to iterate through its - ``schemas`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListSchemas`` requests and continue to iterate - through the ``schemas`` field on the - corresponding responses. - - All the usual :class:`google.pubsub_v1.types.ListSchemasResponse` - attributes are available on the pager. If multiple requests are made, only - the most recent response is retained, and thus used for attribute lookup. - """ - def __init__(self, - method: Callable[..., schema.ListSchemasResponse], - request: schema.ListSchemasRequest, - response: schema.ListSchemasResponse, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiate the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.pubsub_v1.types.ListSchemasRequest): - The initial request object. - response (google.pubsub_v1.types.ListSchemasResponse): - The initial response object. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = schema.ListSchemasRequest(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[schema.ListSchemasResponse]: - 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[schema.Schema]: - for page in self.pages: - yield from page.schemas - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListSchemasAsyncPager: - """A pager for iterating through ``list_schemas`` requests. - - This class thinly wraps an initial - :class:`google.pubsub_v1.types.ListSchemasResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``schemas`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListSchemas`` requests and continue to iterate - through the ``schemas`` field on the - corresponding responses. - - All the usual :class:`google.pubsub_v1.types.ListSchemasResponse` - attributes are available on the 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[schema.ListSchemasResponse]], - request: schema.ListSchemasRequest, - response: schema.ListSchemasResponse, - *, - retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiates the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.pubsub_v1.types.ListSchemasRequest): - The initial request object. - response (google.pubsub_v1.types.ListSchemasResponse): - The initial response object. - retry (google.api_core.retry.AsyncRetry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = schema.ListSchemasRequest(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[schema.ListSchemasResponse]: - 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[schema.Schema]: - async def async_generator(): - async for page in self.pages: - for response in page.schemas: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListSchemaRevisionsPager: - """A pager for iterating through ``list_schema_revisions`` requests. - - This class thinly wraps an initial - :class:`google.pubsub_v1.types.ListSchemaRevisionsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``schemas`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListSchemaRevisions`` requests and continue to iterate - through the ``schemas`` field on the - corresponding responses. - - All the usual :class:`google.pubsub_v1.types.ListSchemaRevisionsResponse` - attributes are available on the pager. If multiple requests are made, only - the most recent response is retained, and thus used for attribute lookup. - """ - def __init__(self, - method: Callable[..., schema.ListSchemaRevisionsResponse], - request: schema.ListSchemaRevisionsRequest, - response: schema.ListSchemaRevisionsResponse, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiate the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.pubsub_v1.types.ListSchemaRevisionsRequest): - The initial request object. - response (google.pubsub_v1.types.ListSchemaRevisionsResponse): - The initial response object. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = schema.ListSchemaRevisionsRequest(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[schema.ListSchemaRevisionsResponse]: - 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[schema.Schema]: - for page in self.pages: - yield from page.schemas - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListSchemaRevisionsAsyncPager: - """A pager for iterating through ``list_schema_revisions`` requests. - - This class thinly wraps an initial - :class:`google.pubsub_v1.types.ListSchemaRevisionsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``schemas`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListSchemaRevisions`` requests and continue to iterate - through the ``schemas`` field on the - corresponding responses. - - All the usual :class:`google.pubsub_v1.types.ListSchemaRevisionsResponse` - attributes are available on the 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[schema.ListSchemaRevisionsResponse]], - request: schema.ListSchemaRevisionsRequest, - response: schema.ListSchemaRevisionsResponse, - *, - retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiates the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.pubsub_v1.types.ListSchemaRevisionsRequest): - The initial request object. - response (google.pubsub_v1.types.ListSchemaRevisionsResponse): - The initial response object. - retry (google.api_core.retry.AsyncRetry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = schema.ListSchemaRevisionsRequest(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[schema.ListSchemaRevisionsResponse]: - 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[schema.Schema]: - async def async_generator(): - async for page in self.pages: - for response in page.schemas: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) diff --git a/owl-bot-staging/v1/google/pubsub_v1/services/schema_service/transports/__init__.py b/owl-bot-staging/v1/google/pubsub_v1/services/schema_service/transports/__init__.py deleted file mode 100644 index 7b0674681..000000000 --- a/owl-bot-staging/v1/google/pubsub_v1/services/schema_service/transports/__init__.py +++ /dev/null @@ -1,38 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -from typing import Dict, Type - -from .base import SchemaServiceTransport -from .grpc import SchemaServiceGrpcTransport -from .grpc_asyncio import SchemaServiceGrpcAsyncIOTransport -from .rest import SchemaServiceRestTransport -from .rest import SchemaServiceRestInterceptor - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[SchemaServiceTransport]] -_transport_registry['grpc'] = SchemaServiceGrpcTransport -_transport_registry['grpc_asyncio'] = SchemaServiceGrpcAsyncIOTransport -_transport_registry['rest'] = SchemaServiceRestTransport - -__all__ = ( - 'SchemaServiceTransport', - 'SchemaServiceGrpcTransport', - 'SchemaServiceGrpcAsyncIOTransport', - 'SchemaServiceRestTransport', - 'SchemaServiceRestInterceptor', -) diff --git a/owl-bot-staging/v1/google/pubsub_v1/services/schema_service/transports/base.py b/owl-bot-staging/v1/google/pubsub_v1/services/schema_service/transports/base.py deleted file mode 100644 index e63e6cf55..000000000 --- a/owl-bot-staging/v1/google/pubsub_v1/services/schema_service/transports/base.py +++ /dev/null @@ -1,405 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import abc -from typing import Awaitable, Callable, Dict, Optional, Sequence, Union - -from google.pubsub_v1 import gapic_version as package_version - -import google.auth # type: ignore -import google.api_core -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.iam.v1 import iam_policy_pb2 # type: ignore -from google.iam.v1 import policy_pb2 # type: ignore -from google.protobuf import empty_pb2 # type: ignore -from google.pubsub_v1.types import schema -from google.pubsub_v1.types import schema as gp_schema - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -class SchemaServiceTransport(abc.ABC): - """Abstract transport class for SchemaService.""" - - AUTH_SCOPES = ( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/pubsub', - ) - - DEFAULT_HOST: str = 'pubsub.googleapis.com' - def __init__( - self, *, - host: str = DEFAULT_HOST, - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - **kwargs, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to (default: 'pubsub.googleapis.com'). - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A list of scopes. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - """ - - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - - # Save the scopes. - self._scopes = scopes - if not hasattr(self, "_ignore_credentials"): - self._ignore_credentials: bool = False - - # If no credentials are provided, then determine the appropriate - # defaults. - if credentials and credentials_file: - raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") - - if credentials_file is not None: - credentials, _ = google.auth.load_credentials_from_file( - credentials_file, - **scopes_kwargs, - quota_project_id=quota_project_id - ) - elif credentials is None and not self._ignore_credentials: - credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) - # Don't apply audience if the credentials file passed from user. - if hasattr(credentials, "with_gdch_audience"): - credentials = credentials.with_gdch_audience(api_audience if api_audience else host) - - # If the credentials are service account credentials, then always try to use self signed JWT. - if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): - credentials = credentials.with_always_use_jwt_access(True) - - # Save the credentials. - self._credentials = credentials - - # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ':' not in host: - host += ':443' - self._host = host - - @property - def host(self): - return self._host - - def _prep_wrapped_messages(self, client_info): - # Precompute the wrapped methods. - self._wrapped_methods = { - self.create_schema: gapic_v1.method.wrap_method( - self.create_schema, - default_retry=retries.Retry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.get_schema: gapic_v1.method.wrap_method( - self.get_schema, - default_retry=retries.Retry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.list_schemas: gapic_v1.method.wrap_method( - self.list_schemas, - default_retry=retries.Retry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.list_schema_revisions: gapic_v1.method.wrap_method( - self.list_schema_revisions, - default_retry=retries.Retry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.commit_schema: gapic_v1.method.wrap_method( - self.commit_schema, - default_retry=retries.Retry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.rollback_schema: gapic_v1.method.wrap_method( - self.rollback_schema, - default_retry=retries.Retry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.delete_schema_revision: gapic_v1.method.wrap_method( - self.delete_schema_revision, - default_retry=retries.Retry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.delete_schema: gapic_v1.method.wrap_method( - self.delete_schema, - default_retry=retries.Retry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.validate_schema: gapic_v1.method.wrap_method( - self.validate_schema, - default_retry=retries.Retry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.validate_message: gapic_v1.method.wrap_method( - self.validate_message, - default_retry=retries.Retry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - 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_schema(self) -> Callable[ - [gp_schema.CreateSchemaRequest], - Union[ - gp_schema.Schema, - Awaitable[gp_schema.Schema] - ]]: - raise NotImplementedError() - - @property - def get_schema(self) -> Callable[ - [schema.GetSchemaRequest], - Union[ - schema.Schema, - Awaitable[schema.Schema] - ]]: - raise NotImplementedError() - - @property - def list_schemas(self) -> Callable[ - [schema.ListSchemasRequest], - Union[ - schema.ListSchemasResponse, - Awaitable[schema.ListSchemasResponse] - ]]: - raise NotImplementedError() - - @property - def list_schema_revisions(self) -> Callable[ - [schema.ListSchemaRevisionsRequest], - Union[ - schema.ListSchemaRevisionsResponse, - Awaitable[schema.ListSchemaRevisionsResponse] - ]]: - raise NotImplementedError() - - @property - def commit_schema(self) -> Callable[ - [gp_schema.CommitSchemaRequest], - Union[ - gp_schema.Schema, - Awaitable[gp_schema.Schema] - ]]: - raise NotImplementedError() - - @property - def rollback_schema(self) -> Callable[ - [schema.RollbackSchemaRequest], - Union[ - schema.Schema, - Awaitable[schema.Schema] - ]]: - raise NotImplementedError() - - @property - def delete_schema_revision(self) -> Callable[ - [schema.DeleteSchemaRevisionRequest], - Union[ - schema.Schema, - Awaitable[schema.Schema] - ]]: - raise NotImplementedError() - - @property - def delete_schema(self) -> Callable[ - [schema.DeleteSchemaRequest], - Union[ - empty_pb2.Empty, - Awaitable[empty_pb2.Empty] - ]]: - raise NotImplementedError() - - @property - def validate_schema(self) -> Callable[ - [gp_schema.ValidateSchemaRequest], - Union[ - gp_schema.ValidateSchemaResponse, - Awaitable[gp_schema.ValidateSchemaResponse] - ]]: - raise NotImplementedError() - - @property - def validate_message(self) -> Callable[ - [schema.ValidateMessageRequest], - Union[ - schema.ValidateMessageResponse, - Awaitable[schema.ValidateMessageResponse] - ]]: - 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 kind(self) -> str: - raise NotImplementedError() - - -__all__ = ( - 'SchemaServiceTransport', -) diff --git a/owl-bot-staging/v1/google/pubsub_v1/services/schema_service/transports/grpc.py b/owl-bot-staging/v1/google/pubsub_v1/services/schema_service/transports/grpc.py deleted file mode 100644 index bb2165014..000000000 --- a/owl-bot-staging/v1/google/pubsub_v1/services/schema_service/transports/grpc.py +++ /dev/null @@ -1,588 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import grpc_helpers -from google.api_core import gapic_v1 -import google.auth # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore - -from google.iam.v1 import iam_policy_pb2 # type: ignore -from google.iam.v1 import policy_pb2 # type: ignore -from google.protobuf import empty_pb2 # type: ignore -from google.pubsub_v1.types import schema -from google.pubsub_v1.types import schema as gp_schema -from .base import SchemaServiceTransport, DEFAULT_CLIENT_INFO - - -class SchemaServiceGrpcTransport(SchemaServiceTransport): - """gRPC backend transport for SchemaService. - - Service for doing schema-related operations. - - This 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 = 'pubsub.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to (default: 'pubsub.googleapis.com'). - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if a ``channel`` instance is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if a ``channel`` instance is provided. - channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): - A ``Channel`` instance through which to make calls, or a Callable - that constructs and returns one. If set to None, ``self.create_channel`` - is used to create the channel. If a Callable is given, it will be called - with the same arguments as used in ``self.create_channel``. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if a ``channel`` instance is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if a ``channel`` instance or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if isinstance(channel, grpc.Channel): - # Ignore credentials if a channel was passed. - credentials = None - self._ignore_credentials = True - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - # initialize with the provided callable or the default channel - channel_init = channel or type(self).create_channel - self._grpc_channel = channel_init( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @classmethod - def create_channel(cls, - host: str = 'pubsub.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> grpc.Channel: - """Create and return a gRPC channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - grpc.Channel: A gRPC channel object. - - Raises: - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - - return grpc_helpers.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - @property - def grpc_channel(self) -> grpc.Channel: - """Return the channel designed to connect to this service. - """ - return self._grpc_channel - - @property - def create_schema(self) -> Callable[ - [gp_schema.CreateSchemaRequest], - gp_schema.Schema]: - r"""Return a callable for the create schema method over gRPC. - - Creates a schema. - - Returns: - Callable[[~.CreateSchemaRequest], - ~.Schema]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_schema' not in self._stubs: - self._stubs['create_schema'] = self.grpc_channel.unary_unary( - '/google.pubsub.v1.SchemaService/CreateSchema', - request_serializer=gp_schema.CreateSchemaRequest.serialize, - response_deserializer=gp_schema.Schema.deserialize, - ) - return self._stubs['create_schema'] - - @property - def get_schema(self) -> Callable[ - [schema.GetSchemaRequest], - schema.Schema]: - r"""Return a callable for the get schema method over gRPC. - - Gets a schema. - - Returns: - Callable[[~.GetSchemaRequest], - ~.Schema]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'get_schema' not in self._stubs: - self._stubs['get_schema'] = self.grpc_channel.unary_unary( - '/google.pubsub.v1.SchemaService/GetSchema', - request_serializer=schema.GetSchemaRequest.serialize, - response_deserializer=schema.Schema.deserialize, - ) - return self._stubs['get_schema'] - - @property - def list_schemas(self) -> Callable[ - [schema.ListSchemasRequest], - schema.ListSchemasResponse]: - r"""Return a callable for the list schemas method over gRPC. - - Lists schemas in a project. - - Returns: - Callable[[~.ListSchemasRequest], - ~.ListSchemasResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'list_schemas' not in self._stubs: - self._stubs['list_schemas'] = self.grpc_channel.unary_unary( - '/google.pubsub.v1.SchemaService/ListSchemas', - request_serializer=schema.ListSchemasRequest.serialize, - response_deserializer=schema.ListSchemasResponse.deserialize, - ) - return self._stubs['list_schemas'] - - @property - def list_schema_revisions(self) -> Callable[ - [schema.ListSchemaRevisionsRequest], - schema.ListSchemaRevisionsResponse]: - r"""Return a callable for the list schema revisions method over gRPC. - - Lists all schema revisions for the named schema. - - Returns: - Callable[[~.ListSchemaRevisionsRequest], - ~.ListSchemaRevisionsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'list_schema_revisions' not in self._stubs: - self._stubs['list_schema_revisions'] = self.grpc_channel.unary_unary( - '/google.pubsub.v1.SchemaService/ListSchemaRevisions', - request_serializer=schema.ListSchemaRevisionsRequest.serialize, - response_deserializer=schema.ListSchemaRevisionsResponse.deserialize, - ) - return self._stubs['list_schema_revisions'] - - @property - def commit_schema(self) -> Callable[ - [gp_schema.CommitSchemaRequest], - gp_schema.Schema]: - r"""Return a callable for the commit schema method over gRPC. - - Commits a new schema revision to an existing schema. - - Returns: - Callable[[~.CommitSchemaRequest], - ~.Schema]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'commit_schema' not in self._stubs: - self._stubs['commit_schema'] = self.grpc_channel.unary_unary( - '/google.pubsub.v1.SchemaService/CommitSchema', - request_serializer=gp_schema.CommitSchemaRequest.serialize, - response_deserializer=gp_schema.Schema.deserialize, - ) - return self._stubs['commit_schema'] - - @property - def rollback_schema(self) -> Callable[ - [schema.RollbackSchemaRequest], - schema.Schema]: - r"""Return a callable for the rollback schema method over gRPC. - - Creates a new schema revision that is a copy of the provided - revision_id. - - Returns: - Callable[[~.RollbackSchemaRequest], - ~.Schema]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'rollback_schema' not in self._stubs: - self._stubs['rollback_schema'] = self.grpc_channel.unary_unary( - '/google.pubsub.v1.SchemaService/RollbackSchema', - request_serializer=schema.RollbackSchemaRequest.serialize, - response_deserializer=schema.Schema.deserialize, - ) - return self._stubs['rollback_schema'] - - @property - def delete_schema_revision(self) -> Callable[ - [schema.DeleteSchemaRevisionRequest], - schema.Schema]: - r"""Return a callable for the delete schema revision method over gRPC. - - Deletes a specific schema revision. - - Returns: - Callable[[~.DeleteSchemaRevisionRequest], - ~.Schema]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_schema_revision' not in self._stubs: - self._stubs['delete_schema_revision'] = self.grpc_channel.unary_unary( - '/google.pubsub.v1.SchemaService/DeleteSchemaRevision', - request_serializer=schema.DeleteSchemaRevisionRequest.serialize, - response_deserializer=schema.Schema.deserialize, - ) - return self._stubs['delete_schema_revision'] - - @property - def delete_schema(self) -> Callable[ - [schema.DeleteSchemaRequest], - empty_pb2.Empty]: - r"""Return a callable for the delete schema method over gRPC. - - Deletes a schema. - - Returns: - Callable[[~.DeleteSchemaRequest], - ~.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_schema' not in self._stubs: - self._stubs['delete_schema'] = self.grpc_channel.unary_unary( - '/google.pubsub.v1.SchemaService/DeleteSchema', - request_serializer=schema.DeleteSchemaRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_schema'] - - @property - def validate_schema(self) -> Callable[ - [gp_schema.ValidateSchemaRequest], - gp_schema.ValidateSchemaResponse]: - r"""Return a callable for the validate schema method over gRPC. - - Validates a schema. - - Returns: - Callable[[~.ValidateSchemaRequest], - ~.ValidateSchemaResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'validate_schema' not in self._stubs: - self._stubs['validate_schema'] = self.grpc_channel.unary_unary( - '/google.pubsub.v1.SchemaService/ValidateSchema', - request_serializer=gp_schema.ValidateSchemaRequest.serialize, - response_deserializer=gp_schema.ValidateSchemaResponse.deserialize, - ) - return self._stubs['validate_schema'] - - @property - def validate_message(self) -> Callable[ - [schema.ValidateMessageRequest], - schema.ValidateMessageResponse]: - r"""Return a callable for the validate message method over gRPC. - - Validates a message against a schema. - - Returns: - Callable[[~.ValidateMessageRequest], - ~.ValidateMessageResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'validate_message' not in self._stubs: - self._stubs['validate_message'] = self.grpc_channel.unary_unary( - '/google.pubsub.v1.SchemaService/ValidateMessage', - request_serializer=schema.ValidateMessageRequest.serialize, - response_deserializer=schema.ValidateMessageResponse.deserialize, - ) - return self._stubs['validate_message'] - - @property - def set_iam_policy( - self, - ) -> Callable[[iam_policy_pb2.SetIamPolicyRequest], policy_pb2.Policy]: - r"""Return a callable for the set iam policy method over gRPC. - Sets the IAM access control policy on the specified - function. Replaces any existing policy. - Returns: - Callable[[~.SetIamPolicyRequest], - ~.Policy]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "set_iam_policy" not in self._stubs: - self._stubs["set_iam_policy"] = self.grpc_channel.unary_unary( - "/google.iam.v1.IAMPolicy/SetIamPolicy", - request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString, - response_deserializer=policy_pb2.Policy.FromString, - ) - return self._stubs["set_iam_policy"] - - @property - def get_iam_policy( - self, - ) -> Callable[[iam_policy_pb2.GetIamPolicyRequest], policy_pb2.Policy]: - r"""Return a callable for the get iam policy method over gRPC. - Gets the IAM access control policy for a function. - Returns an empty policy if the function exists and does - not have a policy set. - Returns: - Callable[[~.GetIamPolicyRequest], - ~.Policy]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "get_iam_policy" not in self._stubs: - self._stubs["get_iam_policy"] = self.grpc_channel.unary_unary( - "/google.iam.v1.IAMPolicy/GetIamPolicy", - request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, - response_deserializer=policy_pb2.Policy.FromString, - ) - return self._stubs["get_iam_policy"] - - @property - def test_iam_permissions( - self, - ) -> Callable[ - [iam_policy_pb2.TestIamPermissionsRequest], iam_policy_pb2.TestIamPermissionsResponse - ]: - r"""Return a callable for the test iam permissions method over gRPC. - Tests the specified permissions against the IAM access control - policy for a function. If the function does not exist, this will - return an empty set of permissions, not a NOT_FOUND error. - Returns: - Callable[[~.TestIamPermissionsRequest], - ~.TestIamPermissionsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "test_iam_permissions" not in self._stubs: - self._stubs["test_iam_permissions"] = self.grpc_channel.unary_unary( - "/google.iam.v1.IAMPolicy/TestIamPermissions", - request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString, - response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString, - ) - return self._stubs["test_iam_permissions"] - - def close(self): - self.grpc_channel.close() - - @property - def kind(self) -> str: - return "grpc" - - -__all__ = ( - 'SchemaServiceGrpcTransport', -) diff --git a/owl-bot-staging/v1/google/pubsub_v1/services/schema_service/transports/grpc_asyncio.py b/owl-bot-staging/v1/google/pubsub_v1/services/schema_service/transports/grpc_asyncio.py deleted file mode 100644 index f18da44c6..000000000 --- a/owl-bot-staging/v1/google/pubsub_v1/services/schema_service/transports/grpc_asyncio.py +++ /dev/null @@ -1,734 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import 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 - -import grpc # type: ignore -from grpc.experimental import aio # type: ignore - -from google.iam.v1 import iam_policy_pb2 # type: ignore -from google.iam.v1 import policy_pb2 # type: ignore -from google.protobuf import empty_pb2 # type: ignore -from google.pubsub_v1.types import schema -from google.pubsub_v1.types import schema as gp_schema -from .base import SchemaServiceTransport, DEFAULT_CLIENT_INFO -from .grpc import SchemaServiceGrpcTransport - - -class SchemaServiceGrpcAsyncIOTransport(SchemaServiceTransport): - """gRPC AsyncIO backend transport for SchemaService. - - Service for doing schema-related operations. - - This 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 = 'pubsub.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> aio.Channel: - """Create and return a gRPC AsyncIO channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - aio.Channel: A gRPC AsyncIO channel object. - """ - - return grpc_helpers_async.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - def __init__(self, *, - host: str = 'pubsub.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: Optional[Union[aio.Channel, Callable[..., aio.Channel]]] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to (default: 'pubsub.googleapis.com'). - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if a ``channel`` instance is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - channel (Optional[Union[aio.Channel, Callable[..., aio.Channel]]]): - A ``Channel`` instance through which to make calls, or a Callable - that constructs and returns one. If set to None, ``self.create_channel`` - is used to create the channel. If a Callable is given, it will be called - with the same arguments as used in ``self.create_channel``. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if a ``channel`` instance is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if a ``channel`` instance or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if isinstance(channel, aio.Channel): - # Ignore credentials if a channel was passed. - credentials = None - self._ignore_credentials = True - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - # initialize with the provided callable or the default channel - channel_init = channel or type(self).create_channel - self._grpc_channel = channel_init( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._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_schema(self) -> Callable[ - [gp_schema.CreateSchemaRequest], - Awaitable[gp_schema.Schema]]: - r"""Return a callable for the create schema method over gRPC. - - Creates a schema. - - Returns: - Callable[[~.CreateSchemaRequest], - Awaitable[~.Schema]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_schema' not in self._stubs: - self._stubs['create_schema'] = self.grpc_channel.unary_unary( - '/google.pubsub.v1.SchemaService/CreateSchema', - request_serializer=gp_schema.CreateSchemaRequest.serialize, - response_deserializer=gp_schema.Schema.deserialize, - ) - return self._stubs['create_schema'] - - @property - def get_schema(self) -> Callable[ - [schema.GetSchemaRequest], - Awaitable[schema.Schema]]: - r"""Return a callable for the get schema method over gRPC. - - Gets a schema. - - Returns: - Callable[[~.GetSchemaRequest], - Awaitable[~.Schema]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'get_schema' not in self._stubs: - self._stubs['get_schema'] = self.grpc_channel.unary_unary( - '/google.pubsub.v1.SchemaService/GetSchema', - request_serializer=schema.GetSchemaRequest.serialize, - response_deserializer=schema.Schema.deserialize, - ) - return self._stubs['get_schema'] - - @property - def list_schemas(self) -> Callable[ - [schema.ListSchemasRequest], - Awaitable[schema.ListSchemasResponse]]: - r"""Return a callable for the list schemas method over gRPC. - - Lists schemas in a project. - - Returns: - Callable[[~.ListSchemasRequest], - Awaitable[~.ListSchemasResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'list_schemas' not in self._stubs: - self._stubs['list_schemas'] = self.grpc_channel.unary_unary( - '/google.pubsub.v1.SchemaService/ListSchemas', - request_serializer=schema.ListSchemasRequest.serialize, - response_deserializer=schema.ListSchemasResponse.deserialize, - ) - return self._stubs['list_schemas'] - - @property - def list_schema_revisions(self) -> Callable[ - [schema.ListSchemaRevisionsRequest], - Awaitable[schema.ListSchemaRevisionsResponse]]: - r"""Return a callable for the list schema revisions method over gRPC. - - Lists all schema revisions for the named schema. - - Returns: - Callable[[~.ListSchemaRevisionsRequest], - Awaitable[~.ListSchemaRevisionsResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'list_schema_revisions' not in self._stubs: - self._stubs['list_schema_revisions'] = self.grpc_channel.unary_unary( - '/google.pubsub.v1.SchemaService/ListSchemaRevisions', - request_serializer=schema.ListSchemaRevisionsRequest.serialize, - response_deserializer=schema.ListSchemaRevisionsResponse.deserialize, - ) - return self._stubs['list_schema_revisions'] - - @property - def commit_schema(self) -> Callable[ - [gp_schema.CommitSchemaRequest], - Awaitable[gp_schema.Schema]]: - r"""Return a callable for the commit schema method over gRPC. - - Commits a new schema revision to an existing schema. - - Returns: - Callable[[~.CommitSchemaRequest], - Awaitable[~.Schema]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'commit_schema' not in self._stubs: - self._stubs['commit_schema'] = self.grpc_channel.unary_unary( - '/google.pubsub.v1.SchemaService/CommitSchema', - request_serializer=gp_schema.CommitSchemaRequest.serialize, - response_deserializer=gp_schema.Schema.deserialize, - ) - return self._stubs['commit_schema'] - - @property - def rollback_schema(self) -> Callable[ - [schema.RollbackSchemaRequest], - Awaitable[schema.Schema]]: - r"""Return a callable for the rollback schema method over gRPC. - - Creates a new schema revision that is a copy of the provided - revision_id. - - Returns: - Callable[[~.RollbackSchemaRequest], - Awaitable[~.Schema]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'rollback_schema' not in self._stubs: - self._stubs['rollback_schema'] = self.grpc_channel.unary_unary( - '/google.pubsub.v1.SchemaService/RollbackSchema', - request_serializer=schema.RollbackSchemaRequest.serialize, - response_deserializer=schema.Schema.deserialize, - ) - return self._stubs['rollback_schema'] - - @property - def delete_schema_revision(self) -> Callable[ - [schema.DeleteSchemaRevisionRequest], - Awaitable[schema.Schema]]: - r"""Return a callable for the delete schema revision method over gRPC. - - Deletes a specific schema revision. - - Returns: - Callable[[~.DeleteSchemaRevisionRequest], - Awaitable[~.Schema]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_schema_revision' not in self._stubs: - self._stubs['delete_schema_revision'] = self.grpc_channel.unary_unary( - '/google.pubsub.v1.SchemaService/DeleteSchemaRevision', - request_serializer=schema.DeleteSchemaRevisionRequest.serialize, - response_deserializer=schema.Schema.deserialize, - ) - return self._stubs['delete_schema_revision'] - - @property - def delete_schema(self) -> Callable[ - [schema.DeleteSchemaRequest], - Awaitable[empty_pb2.Empty]]: - r"""Return a callable for the delete schema method over gRPC. - - Deletes a schema. - - Returns: - Callable[[~.DeleteSchemaRequest], - 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_schema' not in self._stubs: - self._stubs['delete_schema'] = self.grpc_channel.unary_unary( - '/google.pubsub.v1.SchemaService/DeleteSchema', - request_serializer=schema.DeleteSchemaRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_schema'] - - @property - def validate_schema(self) -> Callable[ - [gp_schema.ValidateSchemaRequest], - Awaitable[gp_schema.ValidateSchemaResponse]]: - r"""Return a callable for the validate schema method over gRPC. - - Validates a schema. - - Returns: - Callable[[~.ValidateSchemaRequest], - Awaitable[~.ValidateSchemaResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'validate_schema' not in self._stubs: - self._stubs['validate_schema'] = self.grpc_channel.unary_unary( - '/google.pubsub.v1.SchemaService/ValidateSchema', - request_serializer=gp_schema.ValidateSchemaRequest.serialize, - response_deserializer=gp_schema.ValidateSchemaResponse.deserialize, - ) - return self._stubs['validate_schema'] - - @property - def validate_message(self) -> Callable[ - [schema.ValidateMessageRequest], - Awaitable[schema.ValidateMessageResponse]]: - r"""Return a callable for the validate message method over gRPC. - - Validates a message against a schema. - - Returns: - Callable[[~.ValidateMessageRequest], - Awaitable[~.ValidateMessageResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'validate_message' not in self._stubs: - self._stubs['validate_message'] = self.grpc_channel.unary_unary( - '/google.pubsub.v1.SchemaService/ValidateMessage', - request_serializer=schema.ValidateMessageRequest.serialize, - response_deserializer=schema.ValidateMessageResponse.deserialize, - ) - return self._stubs['validate_message'] - - @property - def set_iam_policy( - self, - ) -> Callable[[iam_policy_pb2.SetIamPolicyRequest], Awaitable[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], - Awaitable[~.Policy]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "set_iam_policy" not in self._stubs: - self._stubs["set_iam_policy"] = self.grpc_channel.unary_unary( - "/google.iam.v1.IAMPolicy/SetIamPolicy", - request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString, - response_deserializer=policy_pb2.Policy.FromString, - ) - return self._stubs["set_iam_policy"] - - @property - def get_iam_policy( - self, - ) -> Callable[[iam_policy_pb2.GetIamPolicyRequest], Awaitable[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], - Awaitable[~.Policy]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "get_iam_policy" not in self._stubs: - self._stubs["get_iam_policy"] = self.grpc_channel.unary_unary( - "/google.iam.v1.IAMPolicy/GetIamPolicy", - request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, - response_deserializer=policy_pb2.Policy.FromString, - ) - return self._stubs["get_iam_policy"] - - @property - def test_iam_permissions( - self, - ) -> Callable[ - [iam_policy_pb2.TestIamPermissionsRequest], - Awaitable[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], - Awaitable[~.TestIamPermissionsResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "test_iam_permissions" not in self._stubs: - self._stubs["test_iam_permissions"] = self.grpc_channel.unary_unary( - "/google.iam.v1.IAMPolicy/TestIamPermissions", - request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString, - response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString, - ) - return self._stubs["test_iam_permissions"] - - 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_schema: gapic_v1.method_async.wrap_method( - self.create_schema, - default_retry=retries.AsyncRetry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.get_schema: gapic_v1.method_async.wrap_method( - self.get_schema, - default_retry=retries.AsyncRetry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.list_schemas: gapic_v1.method_async.wrap_method( - self.list_schemas, - default_retry=retries.AsyncRetry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.list_schema_revisions: gapic_v1.method_async.wrap_method( - self.list_schema_revisions, - default_retry=retries.AsyncRetry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.commit_schema: gapic_v1.method_async.wrap_method( - self.commit_schema, - default_retry=retries.AsyncRetry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.rollback_schema: gapic_v1.method_async.wrap_method( - self.rollback_schema, - default_retry=retries.AsyncRetry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.delete_schema_revision: gapic_v1.method_async.wrap_method( - self.delete_schema_revision, - default_retry=retries.AsyncRetry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.delete_schema: gapic_v1.method_async.wrap_method( - self.delete_schema, - default_retry=retries.AsyncRetry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.validate_schema: gapic_v1.method_async.wrap_method( - self.validate_schema, - default_retry=retries.AsyncRetry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.validate_message: gapic_v1.method_async.wrap_method( - self.validate_message, - default_retry=retries.AsyncRetry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - } - - def close(self): - return self.grpc_channel.close() - - -__all__ = ( - 'SchemaServiceGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v1/google/pubsub_v1/services/schema_service/transports/rest.py b/owl-bot-staging/v1/google/pubsub_v1/services/schema_service/transports/rest.py deleted file mode 100644 index ace1d7e41..000000000 --- a/owl-bot-staging/v1/google/pubsub_v1/services/schema_service/transports/rest.py +++ /dev/null @@ -1,1598 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -from google.auth.transport.requests import AuthorizedSession # type: ignore -import json # type: ignore -import grpc # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.api_core import exceptions as core_exceptions -from google.api_core import retry as retries -from google.api_core import rest_helpers -from google.api_core import rest_streaming -from google.api_core import 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 requests import __version__ as requests_version -import dataclasses -import re -from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union -import warnings - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object, None] # type: ignore - - -from google.iam.v1 import iam_policy_pb2 # type: ignore -from google.iam.v1 import policy_pb2 # type: ignore -from google.protobuf import empty_pb2 # type: ignore -from google.pubsub_v1.types import schema -from google.pubsub_v1.types import schema as gp_schema - -from .base import SchemaServiceTransport, DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO - - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, - grpc_version=None, - rest_version=requests_version, -) - - -class SchemaServiceRestInterceptor: - """Interceptor for SchemaService. - - 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 SchemaServiceRestTransport. - - .. code-block:: python - class MyCustomSchemaServiceInterceptor(SchemaServiceRestInterceptor): - def pre_commit_schema(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_commit_schema(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_create_schema(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_create_schema(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_delete_schema(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def pre_delete_schema_revision(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_delete_schema_revision(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_get_schema(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_schema(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_list_schema_revisions(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_list_schema_revisions(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_list_schemas(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_list_schemas(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_rollback_schema(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_rollback_schema(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_validate_message(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_validate_message(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_validate_schema(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_validate_schema(self, response): - logging.log(f"Received response: {response}") - return response - - transport = SchemaServiceRestTransport(interceptor=MyCustomSchemaServiceInterceptor()) - client = SchemaServiceClient(transport=transport) - - - """ - def pre_commit_schema(self, request: gp_schema.CommitSchemaRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[gp_schema.CommitSchemaRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for commit_schema - - Override in a subclass to manipulate the request or metadata - before they are sent to the SchemaService server. - """ - return request, metadata - - def post_commit_schema(self, response: gp_schema.Schema) -> gp_schema.Schema: - """Post-rpc interceptor for commit_schema - - Override in a subclass to manipulate the response - after it is returned by the SchemaService server but before - it is returned to user code. - """ - return response - def pre_create_schema(self, request: gp_schema.CreateSchemaRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[gp_schema.CreateSchemaRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for create_schema - - Override in a subclass to manipulate the request or metadata - before they are sent to the SchemaService server. - """ - return request, metadata - - def post_create_schema(self, response: gp_schema.Schema) -> gp_schema.Schema: - """Post-rpc interceptor for create_schema - - Override in a subclass to manipulate the response - after it is returned by the SchemaService server but before - it is returned to user code. - """ - return response - def pre_delete_schema(self, request: schema.DeleteSchemaRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[schema.DeleteSchemaRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for delete_schema - - Override in a subclass to manipulate the request or metadata - before they are sent to the SchemaService server. - """ - return request, metadata - - def pre_delete_schema_revision(self, request: schema.DeleteSchemaRevisionRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[schema.DeleteSchemaRevisionRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for delete_schema_revision - - Override in a subclass to manipulate the request or metadata - before they are sent to the SchemaService server. - """ - return request, metadata - - def post_delete_schema_revision(self, response: schema.Schema) -> schema.Schema: - """Post-rpc interceptor for delete_schema_revision - - Override in a subclass to manipulate the response - after it is returned by the SchemaService server but before - it is returned to user code. - """ - return response - def pre_get_schema(self, request: schema.GetSchemaRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[schema.GetSchemaRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_schema - - Override in a subclass to manipulate the request or metadata - before they are sent to the SchemaService server. - """ - return request, metadata - - def post_get_schema(self, response: schema.Schema) -> schema.Schema: - """Post-rpc interceptor for get_schema - - Override in a subclass to manipulate the response - after it is returned by the SchemaService server but before - it is returned to user code. - """ - return response - def pre_list_schema_revisions(self, request: schema.ListSchemaRevisionsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[schema.ListSchemaRevisionsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_schema_revisions - - Override in a subclass to manipulate the request or metadata - before they are sent to the SchemaService server. - """ - return request, metadata - - def post_list_schema_revisions(self, response: schema.ListSchemaRevisionsResponse) -> schema.ListSchemaRevisionsResponse: - """Post-rpc interceptor for list_schema_revisions - - Override in a subclass to manipulate the response - after it is returned by the SchemaService server but before - it is returned to user code. - """ - return response - def pre_list_schemas(self, request: schema.ListSchemasRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[schema.ListSchemasRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_schemas - - Override in a subclass to manipulate the request or metadata - before they are sent to the SchemaService server. - """ - return request, metadata - - def post_list_schemas(self, response: schema.ListSchemasResponse) -> schema.ListSchemasResponse: - """Post-rpc interceptor for list_schemas - - Override in a subclass to manipulate the response - after it is returned by the SchemaService server but before - it is returned to user code. - """ - return response - def pre_rollback_schema(self, request: schema.RollbackSchemaRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[schema.RollbackSchemaRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for rollback_schema - - Override in a subclass to manipulate the request or metadata - before they are sent to the SchemaService server. - """ - return request, metadata - - def post_rollback_schema(self, response: schema.Schema) -> schema.Schema: - """Post-rpc interceptor for rollback_schema - - Override in a subclass to manipulate the response - after it is returned by the SchemaService server but before - it is returned to user code. - """ - return response - def pre_validate_message(self, request: schema.ValidateMessageRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[schema.ValidateMessageRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for validate_message - - Override in a subclass to manipulate the request or metadata - before they are sent to the SchemaService server. - """ - return request, metadata - - def post_validate_message(self, response: schema.ValidateMessageResponse) -> schema.ValidateMessageResponse: - """Post-rpc interceptor for validate_message - - Override in a subclass to manipulate the response - after it is returned by the SchemaService server but before - it is returned to user code. - """ - return response - def pre_validate_schema(self, request: gp_schema.ValidateSchemaRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[gp_schema.ValidateSchemaRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for validate_schema - - Override in a subclass to manipulate the request or metadata - before they are sent to the SchemaService server. - """ - return request, metadata - - def post_validate_schema(self, response: gp_schema.ValidateSchemaResponse) -> gp_schema.ValidateSchemaResponse: - """Post-rpc interceptor for validate_schema - - Override in a subclass to manipulate the response - after it is returned by the SchemaService server but before - it is returned to user code. - """ - return response - - def pre_get_iam_policy( - self, request: iam_policy_pb2.GetIamPolicyRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[iam_policy_pb2.GetIamPolicyRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_iam_policy - - Override in a subclass to manipulate the request or metadata - before they are sent to the SchemaService 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 SchemaService server but before - it is returned to user code. - """ - return response - def pre_set_iam_policy( - self, request: iam_policy_pb2.SetIamPolicyRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[iam_policy_pb2.SetIamPolicyRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for set_iam_policy - - Override in a subclass to manipulate the request or metadata - before they are sent to the SchemaService 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 SchemaService server but before - it is returned to user code. - """ - return response - def pre_test_iam_permissions( - self, request: iam_policy_pb2.TestIamPermissionsRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[iam_policy_pb2.TestIamPermissionsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for test_iam_permissions - - Override in a subclass to manipulate the request or metadata - before they are sent to the SchemaService 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 SchemaService server but before - it is returned to user code. - """ - return response - - -@dataclasses.dataclass -class SchemaServiceRestStub: - _session: AuthorizedSession - _host: str - _interceptor: SchemaServiceRestInterceptor - - -class SchemaServiceRestTransport(SchemaServiceTransport): - """REST backend transport for SchemaService. - - Service for doing schema-related operations. - - This 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 = 'pubsub.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - client_cert_source_for_mtls: Optional[Callable[[ - ], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - url_scheme: str = 'https', - interceptor: Optional[SchemaServiceRestInterceptor] = None, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to (default: 'pubsub.googleapis.com'). - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client - certificate to configure mutual TLS HTTP channel. It is ignored - if ``channel`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you are developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - url_scheme: the protocol scheme for the API endpoint. Normally - "https", but for testing or local servers, - "http" can be specified. - """ - # Run the base constructor - # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. - # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the - # credentials object - 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 - ) - 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 SchemaServiceRestInterceptor() - self._prep_wrapped_messages(client_info) - - class _CommitSchema(SchemaServiceRestStub): - def __hash__(self): - return hash("CommitSchema") - - __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} - - def __call__(self, - request: gp_schema.CommitSchemaRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> gp_schema.Schema: - r"""Call the commit schema method over HTTP. - - Args: - request (~.gp_schema.CommitSchemaRequest): - The request object. Request for CommitSchema method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.gp_schema.Schema: - A schema resource. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/{name=projects/*/schemas/*}:commit', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_commit_schema(request, metadata) - pb_request = gp_schema.CommitSchemaRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=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 = gp_schema.Schema() - pb_resp = gp_schema.Schema.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_commit_schema(resp) - return resp - - class _CreateSchema(SchemaServiceRestStub): - def __hash__(self): - return hash("CreateSchema") - - __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} - - def __call__(self, - request: gp_schema.CreateSchemaRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> gp_schema.Schema: - r"""Call the create schema method over HTTP. - - Args: - request (~.gp_schema.CreateSchemaRequest): - The request object. Request for the CreateSchema method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.gp_schema.Schema: - A schema resource. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/{parent=projects/*}/schemas', - 'body': 'schema', - }, - ] - request, metadata = self._interceptor.pre_create_schema(request, metadata) - pb_request = gp_schema.CreateSchemaRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=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 = gp_schema.Schema() - pb_resp = gp_schema.Schema.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_create_schema(resp) - return resp - - class _DeleteSchema(SchemaServiceRestStub): - def __hash__(self): - return hash("DeleteSchema") - - __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} - - def __call__(self, - request: schema.DeleteSchemaRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ): - r"""Call the delete schema method over HTTP. - - Args: - request (~.schema.DeleteSchemaRequest): - The request object. Request for the ``DeleteSchema`` method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'delete', - 'uri': '/v1/{name=projects/*/schemas/*}', - }, - ] - request, metadata = self._interceptor.pre_delete_schema(request, metadata) - pb_request = schema.DeleteSchemaRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # 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 _DeleteSchemaRevision(SchemaServiceRestStub): - def __hash__(self): - return hash("DeleteSchemaRevision") - - __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} - - def __call__(self, - request: schema.DeleteSchemaRevisionRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> schema.Schema: - r"""Call the delete schema revision method over HTTP. - - Args: - request (~.schema.DeleteSchemaRevisionRequest): - The request object. Request for the ``DeleteSchemaRevision`` method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.schema.Schema: - A schema resource. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'delete', - 'uri': '/v1/{name=projects/*/schemas/*}:deleteRevision', - }, - ] - request, metadata = self._interceptor.pre_delete_schema_revision(request, metadata) - pb_request = schema.DeleteSchemaRevisionRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # 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 = schema.Schema() - pb_resp = schema.Schema.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_delete_schema_revision(resp) - return resp - - class _GetSchema(SchemaServiceRestStub): - def __hash__(self): - return hash("GetSchema") - - __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} - - def __call__(self, - request: schema.GetSchemaRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> schema.Schema: - r"""Call the get schema method over HTTP. - - Args: - request (~.schema.GetSchemaRequest): - The request object. Request for the GetSchema method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.schema.Schema: - A schema resource. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/schemas/*}', - }, - ] - request, metadata = self._interceptor.pre_get_schema(request, metadata) - pb_request = schema.GetSchemaRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # 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 = schema.Schema() - pb_resp = schema.Schema.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_get_schema(resp) - return resp - - class _ListSchemaRevisions(SchemaServiceRestStub): - def __hash__(self): - return hash("ListSchemaRevisions") - - __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} - - def __call__(self, - request: schema.ListSchemaRevisionsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> schema.ListSchemaRevisionsResponse: - r"""Call the list schema revisions method over HTTP. - - Args: - request (~.schema.ListSchemaRevisionsRequest): - The request object. Request for the ``ListSchemaRevisions`` method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.schema.ListSchemaRevisionsResponse: - Response for the ``ListSchemaRevisions`` method. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/schemas/*}:listRevisions', - }, - ] - request, metadata = self._interceptor.pre_list_schema_revisions(request, metadata) - pb_request = schema.ListSchemaRevisionsRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # 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 = schema.ListSchemaRevisionsResponse() - pb_resp = schema.ListSchemaRevisionsResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_list_schema_revisions(resp) - return resp - - class _ListSchemas(SchemaServiceRestStub): - def __hash__(self): - return hash("ListSchemas") - - __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} - - def __call__(self, - request: schema.ListSchemasRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> schema.ListSchemasResponse: - r"""Call the list schemas method over HTTP. - - Args: - request (~.schema.ListSchemasRequest): - The request object. Request for the ``ListSchemas`` method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.schema.ListSchemasResponse: - Response for the ``ListSchemas`` method. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{parent=projects/*}/schemas', - }, - ] - request, metadata = self._interceptor.pre_list_schemas(request, metadata) - pb_request = schema.ListSchemasRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # 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 = schema.ListSchemasResponse() - pb_resp = schema.ListSchemasResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_list_schemas(resp) - return resp - - class _RollbackSchema(SchemaServiceRestStub): - def __hash__(self): - return hash("RollbackSchema") - - __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} - - def __call__(self, - request: schema.RollbackSchemaRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> schema.Schema: - r"""Call the rollback schema method over HTTP. - - Args: - request (~.schema.RollbackSchemaRequest): - The request object. Request for the ``RollbackSchema`` method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.schema.Schema: - A schema resource. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/{name=projects/*/schemas/*}:rollback', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_rollback_schema(request, metadata) - pb_request = schema.RollbackSchemaRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=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 = schema.Schema() - pb_resp = schema.Schema.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_rollback_schema(resp) - return resp - - class _ValidateMessage(SchemaServiceRestStub): - def __hash__(self): - return hash("ValidateMessage") - - __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} - - def __call__(self, - request: schema.ValidateMessageRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> schema.ValidateMessageResponse: - r"""Call the validate message method over HTTP. - - Args: - request (~.schema.ValidateMessageRequest): - The request object. Request for the ``ValidateMessage`` method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.schema.ValidateMessageResponse: - Response for the ``ValidateMessage`` method. Empty for - now. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/{parent=projects/*}/schemas:validateMessage', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_validate_message(request, metadata) - pb_request = schema.ValidateMessageRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=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 = schema.ValidateMessageResponse() - pb_resp = schema.ValidateMessageResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_validate_message(resp) - return resp - - class _ValidateSchema(SchemaServiceRestStub): - def __hash__(self): - return hash("ValidateSchema") - - __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} - - def __call__(self, - request: gp_schema.ValidateSchemaRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> gp_schema.ValidateSchemaResponse: - r"""Call the validate schema method over HTTP. - - Args: - request (~.gp_schema.ValidateSchemaRequest): - The request object. Request for the ``ValidateSchema`` method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.gp_schema.ValidateSchemaResponse: - Response for the ``ValidateSchema`` method. Empty for - now. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/{parent=projects/*}/schemas:validate', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_validate_schema(request, metadata) - pb_request = gp_schema.ValidateSchemaRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=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 = gp_schema.ValidateSchemaResponse() - pb_resp = gp_schema.ValidateSchemaResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_validate_schema(resp) - return resp - - @property - def commit_schema(self) -> Callable[ - [gp_schema.CommitSchemaRequest], - gp_schema.Schema]: - # 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._CommitSchema(self._session, self._host, self._interceptor) # type: ignore - - @property - def create_schema(self) -> Callable[ - [gp_schema.CreateSchemaRequest], - gp_schema.Schema]: - # 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._CreateSchema(self._session, self._host, self._interceptor) # type: ignore - - @property - def delete_schema(self) -> Callable[ - [schema.DeleteSchemaRequest], - 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._DeleteSchema(self._session, self._host, self._interceptor) # type: ignore - - @property - def delete_schema_revision(self) -> Callable[ - [schema.DeleteSchemaRevisionRequest], - schema.Schema]: - # 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._DeleteSchemaRevision(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_schema(self) -> Callable[ - [schema.GetSchemaRequest], - schema.Schema]: - # 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._GetSchema(self._session, self._host, self._interceptor) # type: ignore - - @property - def list_schema_revisions(self) -> Callable[ - [schema.ListSchemaRevisionsRequest], - schema.ListSchemaRevisionsResponse]: - # 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._ListSchemaRevisions(self._session, self._host, self._interceptor) # type: ignore - - @property - def list_schemas(self) -> Callable[ - [schema.ListSchemasRequest], - schema.ListSchemasResponse]: - # 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._ListSchemas(self._session, self._host, self._interceptor) # type: ignore - - @property - def rollback_schema(self) -> Callable[ - [schema.RollbackSchemaRequest], - schema.Schema]: - # 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._RollbackSchema(self._session, self._host, self._interceptor) # type: ignore - - @property - def validate_message(self) -> Callable[ - [schema.ValidateMessageRequest], - schema.ValidateMessageResponse]: - # 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._ValidateMessage(self._session, self._host, self._interceptor) # type: ignore - - @property - def validate_schema(self) -> Callable[ - [gp_schema.ValidateSchemaRequest], - gp_schema.ValidateSchemaResponse]: - # 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._ValidateSchema(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_iam_policy(self): - return self._GetIamPolicy(self._session, self._host, self._interceptor) # type: ignore - - class _GetIamPolicy(SchemaServiceRestStub): - def __call__(self, - request: iam_policy_pb2.GetIamPolicyRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> policy_pb2.Policy: - - r"""Call the get iam policy method over HTTP. - - Args: - request (iam_policy_pb2.GetIamPolicyRequest): - The request object for GetIamPolicy method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - policy_pb2.Policy: Response from GetIamPolicy method. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{resource=projects/*/topics/*}:getIamPolicy', - }, -{ - 'method': 'get', - 'uri': '/v1/{resource=projects/*/subscriptions/*}:getIamPolicy', - }, -{ - 'method': 'get', - 'uri': '/v1/{resource=projects/*/snapshots/*}:getIamPolicy', - }, -{ - 'method': 'get', - 'uri': '/v1/{resource=projects/*/schemas/*}:getIamPolicy', - }, - ] - - request, metadata = self._interceptor.pre_get_iam_policy(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - resp = policy_pb2.Policy() - resp = json_format.Parse(response.content.decode("utf-8"), resp) - resp = self._interceptor.post_get_iam_policy(resp) - return resp - - @property - def set_iam_policy(self): - return self._SetIamPolicy(self._session, self._host, self._interceptor) # type: ignore - - class _SetIamPolicy(SchemaServiceRestStub): - def __call__(self, - request: iam_policy_pb2.SetIamPolicyRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> policy_pb2.Policy: - - r"""Call the set iam policy method over HTTP. - - Args: - request (iam_policy_pb2.SetIamPolicyRequest): - The request object for SetIamPolicy method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - policy_pb2.Policy: Response from SetIamPolicy method. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/{resource=projects/*/topics/*}:setIamPolicy', - 'body': '*', - }, -{ - 'method': 'post', - 'uri': '/v1/{resource=projects/*/subscriptions/*}:setIamPolicy', - 'body': '*', - }, -{ - 'method': 'post', - 'uri': '/v1/{resource=projects/*/snapshots/*}:setIamPolicy', - 'body': '*', - }, -{ - 'method': 'post', - 'uri': '/v1/{resource=projects/*/schemas/*}:setIamPolicy', - 'body': '*', - }, - ] - - request, metadata = self._interceptor.pre_set_iam_policy(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - body = json.dumps(transcoded_request['body']) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - data=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) - - resp = policy_pb2.Policy() - resp = json_format.Parse(response.content.decode("utf-8"), resp) - resp = self._interceptor.post_set_iam_policy(resp) - return resp - - @property - def test_iam_permissions(self): - return self._TestIamPermissions(self._session, self._host, self._interceptor) # type: ignore - - class _TestIamPermissions(SchemaServiceRestStub): - def __call__(self, - request: iam_policy_pb2.TestIamPermissionsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> iam_policy_pb2.TestIamPermissionsResponse: - - r"""Call the test iam permissions method over HTTP. - - Args: - request (iam_policy_pb2.TestIamPermissionsRequest): - The request object for TestIamPermissions method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - iam_policy_pb2.TestIamPermissionsResponse: Response from TestIamPermissions method. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/{resource=projects/*/subscriptions/*}:testIamPermissions', - 'body': '*', - }, -{ - 'method': 'post', - 'uri': '/v1/{resource=projects/*/topics/*}:testIamPermissions', - 'body': '*', - }, -{ - 'method': 'post', - 'uri': '/v1/{resource=projects/*/snapshots/*}:testIamPermissions', - 'body': '*', - }, -{ - 'method': 'post', - 'uri': '/v1/{resource=projects/*/schemas/*}:testIamPermissions', - 'body': '*', - }, - ] - - request, metadata = self._interceptor.pre_test_iam_permissions(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - body = json.dumps(transcoded_request['body']) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - data=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) - - resp = iam_policy_pb2.TestIamPermissionsResponse() - resp = json_format.Parse(response.content.decode("utf-8"), resp) - resp = self._interceptor.post_test_iam_permissions(resp) - return resp - - @property - def kind(self) -> str: - return "rest" - - def close(self): - self._session.close() - - -__all__=( - 'SchemaServiceRestTransport', -) diff --git a/owl-bot-staging/v1/google/pubsub_v1/services/subscriber/__init__.py b/owl-bot-staging/v1/google/pubsub_v1/services/subscriber/__init__.py deleted file mode 100644 index da863be4d..000000000 --- a/owl-bot-staging/v1/google/pubsub_v1/services/subscriber/__init__.py +++ /dev/null @@ -1,22 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from .client import SubscriberClient -from .async_client import SubscriberAsyncClient - -__all__ = ( - 'SubscriberClient', - 'SubscriberAsyncClient', -) diff --git a/owl-bot-staging/v1/google/pubsub_v1/services/subscriber/async_client.py b/owl-bot-staging/v1/google/pubsub_v1/services/subscriber/async_client.py deleted file mode 100644 index 6efa2ce1c..000000000 --- a/owl-bot-staging/v1/google/pubsub_v1/services/subscriber/async_client.py +++ /dev/null @@ -1,2426 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import re -from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, AsyncIterable, Awaitable, AsyncIterator, Sequence, Tuple, Type, Union - -from google.pubsub_v1 import gapic_version as package_version - -from google.api_core.client_options import ClientOptions -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry_async as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - - -try: - OptionalRetry = Union[retries.AsyncRetry, gapic_v1.method._MethodDefault, None] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore - -from google.iam.v1 import iam_policy_pb2 # type: ignore -from google.iam.v1 import policy_pb2 # type: ignore -from google.protobuf import duration_pb2 # type: ignore -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from google.pubsub_v1.services.subscriber import pagers -from google.pubsub_v1.types import pubsub -from .transports.base import SubscriberTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import SubscriberGrpcAsyncIOTransport -from .client import SubscriberClient - - -class SubscriberAsyncClient: - """The service that an application uses to manipulate subscriptions and - to consume messages from a subscription via the ``Pull`` method or - by establishing a bi-directional stream using the ``StreamingPull`` - method. - """ - - _client: SubscriberClient - - # Copy defaults from the synchronous client for use here. - # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. - DEFAULT_ENDPOINT = SubscriberClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = SubscriberClient.DEFAULT_MTLS_ENDPOINT - _DEFAULT_ENDPOINT_TEMPLATE = SubscriberClient._DEFAULT_ENDPOINT_TEMPLATE - _DEFAULT_UNIVERSE = SubscriberClient._DEFAULT_UNIVERSE - - snapshot_path = staticmethod(SubscriberClient.snapshot_path) - parse_snapshot_path = staticmethod(SubscriberClient.parse_snapshot_path) - subscription_path = staticmethod(SubscriberClient.subscription_path) - parse_subscription_path = staticmethod(SubscriberClient.parse_subscription_path) - topic_path = staticmethod(SubscriberClient.topic_path) - parse_topic_path = staticmethod(SubscriberClient.parse_topic_path) - common_billing_account_path = staticmethod(SubscriberClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(SubscriberClient.parse_common_billing_account_path) - common_folder_path = staticmethod(SubscriberClient.common_folder_path) - parse_common_folder_path = staticmethod(SubscriberClient.parse_common_folder_path) - common_organization_path = staticmethod(SubscriberClient.common_organization_path) - parse_common_organization_path = staticmethod(SubscriberClient.parse_common_organization_path) - common_project_path = staticmethod(SubscriberClient.common_project_path) - parse_common_project_path = staticmethod(SubscriberClient.parse_common_project_path) - common_location_path = staticmethod(SubscriberClient.common_location_path) - parse_common_location_path = staticmethod(SubscriberClient.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: - SubscriberAsyncClient: The constructed client. - """ - return SubscriberClient.from_service_account_info.__func__(SubscriberAsyncClient, info, *args, **kwargs) # type: ignore - - @classmethod - def from_service_account_file(cls, filename: str, *args, **kwargs): - """Creates an instance of this client using the provided credentials - file. - - Args: - filename (str): The path to the service account private key json - file. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - SubscriberAsyncClient: The constructed client. - """ - return SubscriberClient.from_service_account_file.__func__(SubscriberAsyncClient, filename, *args, **kwargs) # type: ignore - - from_service_account_json = from_service_account_file - - @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[ClientOptions] = None): - """Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variable is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - return SubscriberClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore - - @property - def transport(self) -> SubscriberTransport: - """Returns the transport used by the client instance. - - Returns: - SubscriberTransport: The transport used by the client instance. - """ - return self._client.transport - - @property - def api_endpoint(self): - """Return the API endpoint used by the client instance. - - Returns: - str: The API endpoint used by the client instance. - """ - return self._client._api_endpoint - - @property - def universe_domain(self) -> str: - """Return the universe domain used by the client instance. - - Returns: - str: The universe domain used - by the client instance. - """ - return self._client._universe_domain - - get_transport_class = SubscriberClient.get_transport_class - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, SubscriberTransport, Callable[..., SubscriberTransport]]] = "grpc_asyncio", - client_options: Optional[ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the subscriber 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,SubscriberTransport,Callable[..., SubscriberTransport]]]): - 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 SubscriberTransport constructor. - If set to None, a transport is chosen automatically. - client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): - Custom options for the client. - - 1. The ``api_endpoint`` property can be used to override the - default endpoint provided by the client when ``transport`` is - not explicitly provided. Only if this property is not set and - ``transport`` was not explicitly provided, the endpoint is - determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment - variable, which have one of the following values: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto-switch to the - default mTLS endpoint if client certificate is present; this is - the default value). - - 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide a client certificate for mTLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - - 3. The ``universe_domain`` property can be used to override the - default "googleapis.com" universe. Note that ``api_endpoint`` - property still takes precedence; and ``universe_domain`` is - currently not supported for mTLS. - - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - """ - self._client = SubscriberClient( - credentials=credentials, - transport=transport, - client_options=client_options, - client_info=client_info, - - ) - - async def create_subscription(self, - request: Optional[Union[pubsub.Subscription, dict]] = None, - *, - name: Optional[str] = None, - topic: Optional[str] = None, - push_config: Optional[pubsub.PushConfig] = None, - ack_deadline_seconds: Optional[int] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pubsub.Subscription: - r"""Creates a subscription to a given topic. See the [resource name - rules] - (https://cloud.google.com/pubsub/docs/pubsub-basics#resource_names). - If the subscription already exists, returns ``ALREADY_EXISTS``. - If the corresponding topic doesn't exist, returns ``NOT_FOUND``. - - If the name is not provided in the request, the server will - assign a random name for this subscription on the same project - as the topic, conforming to the [resource name format] - (https://cloud.google.com/pubsub/docs/pubsub-basics#resource_names). - The generated name is populated in the returned Subscription - object. Note that for REST API requests, you must specify a name - in the request. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require 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 pubsub_v1 - - async def sample_create_subscription(): - # Create a client - client = pubsub_v1.SubscriberAsyncClient() - - # Initialize request argument(s) - request = pubsub_v1.Subscription( - name="name_value", - topic="topic_value", - ) - - # Make the request - response = await client.create_subscription(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.pubsub_v1.types.Subscription, dict]]): - The request object. A subscription resource. If none of ``push_config``, - ``bigquery_config``, or ``cloud_storage_config`` is set, - then the subscriber will pull and ack messages using API - methods. At most one of these fields may be set. - name (:class:`str`): - Required. The name of the subscription. It must have the - format - ``"projects/{project}/subscriptions/{subscription}"``. - ``{subscription}`` must start with a letter, and contain - only letters (``[A-Za-z]``), numbers (``[0-9]``), dashes - (``-``), underscores (``_``), periods (``.``), tildes - (``~``), plus (``+``) or percent signs (``%``). It must - be between 3 and 255 characters in length, and it must - not start with ``"goog"``. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - topic (:class:`str`): - Required. The name of the topic from which this - subscription is receiving messages. Format is - ``projects/{project}/topics/{topic}``. The value of this - field will be ``_deleted-topic_`` if the topic has been - deleted. - - This corresponds to the ``topic`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - push_config (:class:`google.pubsub_v1.types.PushConfig`): - Optional. If push delivery is used - with this subscription, this field is - used to configure it. - - This corresponds to the ``push_config`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - ack_deadline_seconds (:class:`int`): - Optional. The approximate amount of time (on a - best-effort basis) Pub/Sub waits for the subscriber to - acknowledge receipt before resending the message. In the - interval after the message is delivered and before it is - acknowledged, it is considered to be *outstanding*. - During that time period, the message will not be - redelivered (on a best-effort basis). - - For pull subscriptions, this value is used as the - initial value for the ack deadline. To override this - value for a given message, call ``ModifyAckDeadline`` - with the corresponding ``ack_id`` if using non-streaming - pull or send the ``ack_id`` in a - ``StreamingModifyAckDeadlineRequest`` if using streaming - pull. The minimum custom deadline you can specify is 10 - seconds. The maximum custom deadline you can specify is - 600 seconds (10 minutes). If this parameter is 0, a - default value of 10 seconds is used. - - For push delivery, this value is also used to set the - request timeout for the call to the push endpoint. - - If the subscriber never acknowledges the message, the - Pub/Sub system will eventually redeliver the message. - - This corresponds to the ``ack_deadline_seconds`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.pubsub_v1.types.Subscription: - A subscription resource. If none of push_config, bigquery_config, or - cloud_storage_config is set, then the subscriber will - pull and ack messages using API methods. At most one - of these fields may be set. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name, topic, push_config, ack_deadline_seconds]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, pubsub.Subscription): - request = pubsub.Subscription(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - if topic is not None: - request.topic = topic - if push_config is not None: - request.push_config = push_config - if ack_deadline_seconds is not None: - request.ack_deadline_seconds = ack_deadline_seconds - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.create_subscription] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def get_subscription(self, - request: Optional[Union[pubsub.GetSubscriptionRequest, dict]] = None, - *, - subscription: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pubsub.Subscription: - r"""Gets the configuration details of a subscription. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require 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 pubsub_v1 - - async def sample_get_subscription(): - # Create a client - client = pubsub_v1.SubscriberAsyncClient() - - # Initialize request argument(s) - request = pubsub_v1.GetSubscriptionRequest( - subscription="subscription_value", - ) - - # Make the request - response = await client.get_subscription(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.pubsub_v1.types.GetSubscriptionRequest, dict]]): - The request object. Request for the GetSubscription - method. - subscription (:class:`str`): - Required. The name of the subscription to get. Format is - ``projects/{project}/subscriptions/{sub}``. - - This corresponds to the ``subscription`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.pubsub_v1.types.Subscription: - A subscription resource. If none of push_config, bigquery_config, or - cloud_storage_config is set, then the subscriber will - pull and ack messages using API methods. At most one - of these fields may be set. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([subscription]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, pubsub.GetSubscriptionRequest): - request = pubsub.GetSubscriptionRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if subscription is not None: - request.subscription = subscription - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.get_subscription] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("subscription", request.subscription), - )), - ) - - # 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_subscription(self, - request: Optional[Union[pubsub.UpdateSubscriptionRequest, dict]] = None, - *, - subscription: Optional[pubsub.Subscription] = None, - update_mask: Optional[field_mask_pb2.FieldMask] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pubsub.Subscription: - r"""Updates an existing subscription by updating the - fields specified in the update mask. Note that certain - properties of a subscription, such as its topic, are not - modifiable. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require 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 pubsub_v1 - - async def sample_update_subscription(): - # Create a client - client = pubsub_v1.SubscriberAsyncClient() - - # Initialize request argument(s) - subscription = pubsub_v1.Subscription() - subscription.name = "name_value" - subscription.topic = "topic_value" - - request = pubsub_v1.UpdateSubscriptionRequest( - subscription=subscription, - ) - - # Make the request - response = await client.update_subscription(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.pubsub_v1.types.UpdateSubscriptionRequest, dict]]): - The request object. Request for the UpdateSubscription - method. - subscription (:class:`google.pubsub_v1.types.Subscription`): - Required. The updated subscription - object. - - This corresponds to the ``subscription`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): - Required. Indicates which fields in - the provided subscription to update. - Must be specified and non-empty. - - This corresponds to the ``update_mask`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.pubsub_v1.types.Subscription: - A subscription resource. If none of push_config, bigquery_config, or - cloud_storage_config is set, then the subscriber will - pull and ack messages using API methods. At most one - of these fields may be set. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([subscription, update_mask]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, pubsub.UpdateSubscriptionRequest): - request = pubsub.UpdateSubscriptionRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if subscription is not None: - request.subscription = subscription - if update_mask is not None: - request.update_mask = update_mask - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.update_subscription] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("subscription.name", request.subscription.name), - )), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def list_subscriptions(self, - request: Optional[Union[pubsub.ListSubscriptionsRequest, dict]] = None, - *, - project: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListSubscriptionsAsyncPager: - r"""Lists matching subscriptions. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require 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 pubsub_v1 - - async def sample_list_subscriptions(): - # Create a client - client = pubsub_v1.SubscriberAsyncClient() - - # Initialize request argument(s) - request = pubsub_v1.ListSubscriptionsRequest( - project="project_value", - ) - - # Make the request - page_result = client.list_subscriptions(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.pubsub_v1.types.ListSubscriptionsRequest, dict]]): - The request object. Request for the ``ListSubscriptions`` method. - project (:class:`str`): - Required. The name of the project in which to list - subscriptions. Format is ``projects/{project-id}``. - - This corresponds to the ``project`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.pubsub_v1.services.subscriber.pagers.ListSubscriptionsAsyncPager: - Response for the ListSubscriptions method. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([project]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, pubsub.ListSubscriptionsRequest): - request = pubsub.ListSubscriptionsRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if project is not None: - request.project = project - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.list_subscriptions] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("project", request.project), - )), - ) - - # 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.ListSubscriptionsAsyncPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def delete_subscription(self, - request: Optional[Union[pubsub.DeleteSubscriptionRequest, dict]] = None, - *, - subscription: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes an existing subscription. All messages retained in the - subscription are immediately dropped. Calls to ``Pull`` after - deletion will return ``NOT_FOUND``. After a subscription is - deleted, a new one may be created with the same name, but the - new one has no association with the old subscription or its - topic unless the same topic is specified. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require 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 pubsub_v1 - - async def sample_delete_subscription(): - # Create a client - client = pubsub_v1.SubscriberAsyncClient() - - # Initialize request argument(s) - request = pubsub_v1.DeleteSubscriptionRequest( - subscription="subscription_value", - ) - - # Make the request - await client.delete_subscription(request=request) - - Args: - request (Optional[Union[google.pubsub_v1.types.DeleteSubscriptionRequest, dict]]): - The request object. Request for the DeleteSubscription - method. - subscription (:class:`str`): - Required. The subscription to delete. Format is - ``projects/{project}/subscriptions/{sub}``. - - This corresponds to the ``subscription`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([subscription]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, pubsub.DeleteSubscriptionRequest): - request = pubsub.DeleteSubscriptionRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if subscription is not None: - request.subscription = subscription - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.delete_subscription] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("subscription", request.subscription), - )), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - async def modify_ack_deadline(self, - request: Optional[Union[pubsub.ModifyAckDeadlineRequest, dict]] = None, - *, - subscription: Optional[str] = None, - ack_ids: Optional[MutableSequence[str]] = None, - ack_deadline_seconds: Optional[int] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Modifies the ack deadline for a specific message. This method is - useful to indicate that more time is needed to process a message - by the subscriber, or to make the message available for - redelivery if the processing was interrupted. Note that this - does not modify the subscription-level ``ackDeadlineSeconds`` - used for subsequent 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 pubsub_v1 - - async def sample_modify_ack_deadline(): - # Create a client - client = pubsub_v1.SubscriberAsyncClient() - - # Initialize request argument(s) - request = pubsub_v1.ModifyAckDeadlineRequest( - subscription="subscription_value", - ack_ids=['ack_ids_value1', 'ack_ids_value2'], - ack_deadline_seconds=2066, - ) - - # Make the request - await client.modify_ack_deadline(request=request) - - Args: - request (Optional[Union[google.pubsub_v1.types.ModifyAckDeadlineRequest, dict]]): - The request object. Request for the ModifyAckDeadline - method. - subscription (:class:`str`): - Required. The name of the subscription. Format is - ``projects/{project}/subscriptions/{sub}``. - - This corresponds to the ``subscription`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - ack_ids (:class:`MutableSequence[str]`): - Required. List of acknowledgment IDs. - This corresponds to the ``ack_ids`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - ack_deadline_seconds (:class:`int`): - Required. The new ack deadline with respect to the time - this request was sent to the Pub/Sub system. For - example, if the value is 10, the new ack deadline will - expire 10 seconds after the ``ModifyAckDeadline`` call - was made. Specifying zero might immediately make the - message available for delivery to another subscriber - client. This typically results in an increase in the - rate of message redeliveries (that is, duplicates). The - minimum deadline you can specify is 0 seconds. The - maximum deadline you can specify in a single request is - 600 seconds (10 minutes). - - This corresponds to the ``ack_deadline_seconds`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([subscription, ack_ids, ack_deadline_seconds]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, pubsub.ModifyAckDeadlineRequest): - request = pubsub.ModifyAckDeadlineRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if subscription is not None: - request.subscription = subscription - if ack_deadline_seconds is not None: - request.ack_deadline_seconds = ack_deadline_seconds - if ack_ids: - request.ack_ids.extend(ack_ids) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.modify_ack_deadline] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("subscription", request.subscription), - )), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - async def acknowledge(self, - request: Optional[Union[pubsub.AcknowledgeRequest, dict]] = None, - *, - subscription: Optional[str] = None, - ack_ids: Optional[MutableSequence[str]] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Acknowledges the messages associated with the ``ack_ids`` in the - ``AcknowledgeRequest``. The Pub/Sub system can remove the - relevant messages from the subscription. - - Acknowledging a message whose ack deadline has expired may - succeed, but such a message may be redelivered later. - Acknowledging a message more than once will not result in 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 pubsub_v1 - - async def sample_acknowledge(): - # Create a client - client = pubsub_v1.SubscriberAsyncClient() - - # Initialize request argument(s) - request = pubsub_v1.AcknowledgeRequest( - subscription="subscription_value", - ack_ids=['ack_ids_value1', 'ack_ids_value2'], - ) - - # Make the request - await client.acknowledge(request=request) - - Args: - request (Optional[Union[google.pubsub_v1.types.AcknowledgeRequest, dict]]): - The request object. Request for the Acknowledge method. - subscription (:class:`str`): - Required. The subscription whose message is being - acknowledged. Format is - ``projects/{project}/subscriptions/{sub}``. - - This corresponds to the ``subscription`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - ack_ids (:class:`MutableSequence[str]`): - Required. The acknowledgment ID for the messages being - acknowledged that was returned by the Pub/Sub system in - the ``Pull`` response. Must not be empty. - - This corresponds to the ``ack_ids`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([subscription, ack_ids]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, pubsub.AcknowledgeRequest): - request = pubsub.AcknowledgeRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if subscription is not None: - request.subscription = subscription - if ack_ids: - request.ack_ids.extend(ack_ids) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.acknowledge] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("subscription", request.subscription), - )), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - async def pull(self, - request: Optional[Union[pubsub.PullRequest, dict]] = None, - *, - subscription: Optional[str] = None, - return_immediately: Optional[bool] = None, - max_messages: Optional[int] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pubsub.PullResponse: - r"""Pulls messages from the server. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require 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 pubsub_v1 - - async def sample_pull(): - # Create a client - client = pubsub_v1.SubscriberAsyncClient() - - # Initialize request argument(s) - request = pubsub_v1.PullRequest( - subscription="subscription_value", - max_messages=1277, - ) - - # Make the request - response = await client.pull(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.pubsub_v1.types.PullRequest, dict]]): - The request object. Request for the ``Pull`` method. - subscription (:class:`str`): - Required. The subscription from which messages should be - pulled. Format is - ``projects/{project}/subscriptions/{sub}``. - - This corresponds to the ``subscription`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - return_immediately (:class:`bool`): - Optional. If this field set to true, the system will - respond immediately even if it there are no messages - available to return in the ``Pull`` response. Otherwise, - the system may wait (for a bounded amount of time) until - at least one message is available, rather than returning - no messages. Warning: setting this field to ``true`` is - discouraged because it adversely impacts the performance - of ``Pull`` operations. We recommend that users do not - set this field. - - This corresponds to the ``return_immediately`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - max_messages (:class:`int`): - Required. The maximum number of - messages to return for this request. - Must be a positive integer. The Pub/Sub - system may return fewer than the number - specified. - - This corresponds to the ``max_messages`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.pubsub_v1.types.PullResponse: - Response for the Pull 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. - has_flattened_params = any([subscription, return_immediately, max_messages]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, pubsub.PullRequest): - request = pubsub.PullRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if subscription is not None: - request.subscription = subscription - if return_immediately is not None: - request.return_immediately = return_immediately - if max_messages is not None: - request.max_messages = max_messages - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.pull] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("subscription", request.subscription), - )), - ) - - # 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 streaming_pull(self, - requests: Optional[AsyncIterator[pubsub.StreamingPullRequest]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> Awaitable[AsyncIterable[pubsub.StreamingPullResponse]]: - r"""Establishes a stream with the server, which sends messages down - to the client. The client streams acknowledgements and ack - deadline modifications back to the server. The server will close - the stream and return the status on any error. The server may - close the stream with status ``UNAVAILABLE`` to reassign - server-side resources, in which case, the client should - re-establish the stream. Flow control can be achieved by - configuring the underlying RPC channel. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google import pubsub_v1 - - async def sample_streaming_pull(): - # Create a client - client = pubsub_v1.SubscriberAsyncClient() - - # Initialize request argument(s) - request = pubsub_v1.StreamingPullRequest( - subscription="subscription_value", - stream_ack_deadline_seconds=2813, - ) - - # This method expects an iterator which contains - # 'pubsub_v1.StreamingPullRequest' 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.streaming_pull(requests=request_generator()) - - # Handle the response - async for response in stream: - print(response) - - Args: - requests (AsyncIterator[`google.pubsub_v1.types.StreamingPullRequest`]): - The request object AsyncIterator. Request for the ``StreamingPull`` streaming RPC method. - This request is used to establish the initial stream as - well as to stream acknowledgements and ack deadline - modifications from the client to the server. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - AsyncIterable[google.pubsub_v1.types.StreamingPullResponse]: - Response for the StreamingPull method. This response is used to stream - messages from the server to the client. - - """ - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.streaming_pull] - - # 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 modify_push_config(self, - request: Optional[Union[pubsub.ModifyPushConfigRequest, dict]] = None, - *, - subscription: Optional[str] = None, - push_config: Optional[pubsub.PushConfig] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Modifies the ``PushConfig`` for a specified subscription. - - This may be used to change a push subscription to a pull one - (signified by an empty ``PushConfig``) or vice versa, or change - the endpoint URL and other attributes of a push subscription. - Messages will accumulate for delivery continuously through the - call regardless of changes to the ``PushConfig``. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require 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 pubsub_v1 - - async def sample_modify_push_config(): - # Create a client - client = pubsub_v1.SubscriberAsyncClient() - - # Initialize request argument(s) - request = pubsub_v1.ModifyPushConfigRequest( - subscription="subscription_value", - ) - - # Make the request - await client.modify_push_config(request=request) - - Args: - request (Optional[Union[google.pubsub_v1.types.ModifyPushConfigRequest, dict]]): - The request object. Request for the ModifyPushConfig - method. - subscription (:class:`str`): - Required. The name of the subscription. Format is - ``projects/{project}/subscriptions/{sub}``. - - This corresponds to the ``subscription`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - push_config (:class:`google.pubsub_v1.types.PushConfig`): - Required. The push configuration for future deliveries. - - An empty ``pushConfig`` indicates that the Pub/Sub - system should stop pushing messages from the given - subscription and allow messages to be pulled and - acknowledged - effectively pausing the subscription if - ``Pull`` or ``StreamingPull`` is not called. - - This corresponds to the ``push_config`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([subscription, push_config]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, pubsub.ModifyPushConfigRequest): - request = pubsub.ModifyPushConfigRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if subscription is not None: - request.subscription = subscription - if push_config is not None: - request.push_config = push_config - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.modify_push_config] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("subscription", request.subscription), - )), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - async def get_snapshot(self, - request: Optional[Union[pubsub.GetSnapshotRequest, dict]] = None, - *, - snapshot: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pubsub.Snapshot: - r"""Gets the configuration details of a snapshot. Snapshots are used - in - `Seek `__ - operations, which allow you to manage message acknowledgments in - bulk. That is, you can set the acknowledgment state of messages - in an existing subscription to the state captured by a snapshot. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require 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 pubsub_v1 - - async def sample_get_snapshot(): - # Create a client - client = pubsub_v1.SubscriberAsyncClient() - - # Initialize request argument(s) - request = pubsub_v1.GetSnapshotRequest( - snapshot="snapshot_value", - ) - - # Make the request - response = await client.get_snapshot(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.pubsub_v1.types.GetSnapshotRequest, dict]]): - The request object. Request for the GetSnapshot method. - snapshot (:class:`str`): - Required. The name of the snapshot to get. Format is - ``projects/{project}/snapshots/{snap}``. - - This corresponds to the ``snapshot`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.pubsub_v1.types.Snapshot: - A snapshot resource. Snapshots are used in - [Seek](https://cloud.google.com/pubsub/docs/replay-overview) - operations, which allow you to manage message - acknowledgments in bulk. That is, you can set the - acknowledgment state of messages in an existing - subscription to the state captured by a snapshot. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([snapshot]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, pubsub.GetSnapshotRequest): - request = pubsub.GetSnapshotRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if snapshot is not None: - request.snapshot = snapshot - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.get_snapshot] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("snapshot", request.snapshot), - )), - ) - - # 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_snapshots(self, - request: Optional[Union[pubsub.ListSnapshotsRequest, dict]] = None, - *, - project: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListSnapshotsAsyncPager: - r"""Lists the existing snapshots. Snapshots are used in - `Seek `__ - operations, which allow you to manage message acknowledgments in - bulk. That is, you can set the acknowledgment state of messages - in an existing subscription to the state captured by a snapshot. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require 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 pubsub_v1 - - async def sample_list_snapshots(): - # Create a client - client = pubsub_v1.SubscriberAsyncClient() - - # Initialize request argument(s) - request = pubsub_v1.ListSnapshotsRequest( - project="project_value", - ) - - # Make the request - page_result = client.list_snapshots(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.pubsub_v1.types.ListSnapshotsRequest, dict]]): - The request object. Request for the ``ListSnapshots`` method. - project (:class:`str`): - Required. The name of the project in which to list - snapshots. Format is ``projects/{project-id}``. - - This corresponds to the ``project`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.pubsub_v1.services.subscriber.pagers.ListSnapshotsAsyncPager: - Response for the ListSnapshots method. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([project]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, pubsub.ListSnapshotsRequest): - request = pubsub.ListSnapshotsRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if project is not None: - request.project = project - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.list_snapshots] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("project", request.project), - )), - ) - - # 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.ListSnapshotsAsyncPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def create_snapshot(self, - request: Optional[Union[pubsub.CreateSnapshotRequest, dict]] = None, - *, - name: Optional[str] = None, - subscription: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pubsub.Snapshot: - r"""Creates a snapshot from the requested subscription. Snapshots - are used in - `Seek `__ - operations, which allow you to manage message acknowledgments in - bulk. That is, you can set the acknowledgment state of messages - in an existing subscription to the state captured by a snapshot. - If the snapshot already exists, returns ``ALREADY_EXISTS``. If - the requested subscription doesn't exist, returns ``NOT_FOUND``. - If the backlog in the subscription is too old -- and the - resulting snapshot would expire in less than 1 hour -- then - ``FAILED_PRECONDITION`` is returned. See also the - ``Snapshot.expire_time`` field. If the name is not provided in - the request, the server will assign a random name for this - snapshot on the same project as the subscription, conforming to - the [resource name format] - (https://cloud.google.com/pubsub/docs/pubsub-basics#resource_names). - The generated name is populated in the returned Snapshot object. - Note that for REST API requests, you must specify a name in the - request. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require 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 pubsub_v1 - - async def sample_create_snapshot(): - # Create a client - client = pubsub_v1.SubscriberAsyncClient() - - # Initialize request argument(s) - request = pubsub_v1.CreateSnapshotRequest( - name="name_value", - subscription="subscription_value", - ) - - # Make the request - response = await client.create_snapshot(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.pubsub_v1.types.CreateSnapshotRequest, dict]]): - The request object. Request for the ``CreateSnapshot`` method. - name (:class:`str`): - Required. User-provided name for this snapshot. If the - name is not provided in the request, the server will - assign a random name for this snapshot on the same - project as the subscription. Note that for REST API - requests, you must specify a name. See the `resource - name - rules `__. - Format is ``projects/{project}/snapshots/{snap}``. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - subscription (:class:`str`): - Required. The subscription whose backlog the snapshot - retains. Specifically, the created snapshot is - guaranteed to retain: (a) The existing backlog on the - subscription. More precisely, this is defined as the - messages in the subscription's backlog that are - unacknowledged upon the successful completion of the - ``CreateSnapshot`` request; as well as: (b) Any messages - published to the subscription's topic following the - successful completion of the CreateSnapshot request. - Format is ``projects/{project}/subscriptions/{sub}``. - - This corresponds to the ``subscription`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.pubsub_v1.types.Snapshot: - A snapshot resource. Snapshots are used in - [Seek](https://cloud.google.com/pubsub/docs/replay-overview) - operations, which allow you to manage message - acknowledgments in bulk. That is, you can set the - acknowledgment state of messages in an existing - subscription to the state captured by a snapshot. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name, subscription]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, pubsub.CreateSnapshotRequest): - request = pubsub.CreateSnapshotRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - if subscription is not None: - request.subscription = subscription - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.create_snapshot] - - # Certain 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_snapshot(self, - request: Optional[Union[pubsub.UpdateSnapshotRequest, dict]] = None, - *, - snapshot: Optional[pubsub.Snapshot] = None, - update_mask: Optional[field_mask_pb2.FieldMask] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pubsub.Snapshot: - r"""Updates an existing snapshot by updating the fields specified in - the update mask. Snapshots are used in - `Seek `__ - operations, which allow you to manage message acknowledgments in - bulk. That is, you can set the acknowledgment state of messages - in an existing subscription to the state captured by a snapshot. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require 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 pubsub_v1 - - async def sample_update_snapshot(): - # Create a client - client = pubsub_v1.SubscriberAsyncClient() - - # Initialize request argument(s) - request = pubsub_v1.UpdateSnapshotRequest( - ) - - # Make the request - response = await client.update_snapshot(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.pubsub_v1.types.UpdateSnapshotRequest, dict]]): - The request object. Request for the UpdateSnapshot - method. - snapshot (:class:`google.pubsub_v1.types.Snapshot`): - Required. The updated snapshot - object. - - This corresponds to the ``snapshot`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): - Required. Indicates which fields in - the provided snapshot to update. Must be - specified and non-empty. - - This corresponds to the ``update_mask`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.pubsub_v1.types.Snapshot: - A snapshot resource. Snapshots are used in - [Seek](https://cloud.google.com/pubsub/docs/replay-overview) - operations, which allow you to manage message - acknowledgments in bulk. That is, you can set the - acknowledgment state of messages in an existing - subscription to the state captured by a snapshot. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([snapshot, update_mask]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, pubsub.UpdateSnapshotRequest): - request = pubsub.UpdateSnapshotRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if snapshot is not None: - request.snapshot = snapshot - if update_mask is not None: - request.update_mask = update_mask - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.update_snapshot] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("snapshot.name", request.snapshot.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_snapshot(self, - request: Optional[Union[pubsub.DeleteSnapshotRequest, dict]] = None, - *, - snapshot: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Removes an existing snapshot. Snapshots are used in [Seek] - (https://cloud.google.com/pubsub/docs/replay-overview) - operations, which allow you to manage message acknowledgments in - bulk. That is, you can set the acknowledgment state of messages - in an existing subscription to the state captured by a snapshot. - When the snapshot is deleted, all messages retained in the - snapshot are immediately dropped. After a snapshot is deleted, a - new one may be created with the same name, but the new one has - no association with the old snapshot or its subscription, unless - the same subscription is specified. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require 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 pubsub_v1 - - async def sample_delete_snapshot(): - # Create a client - client = pubsub_v1.SubscriberAsyncClient() - - # Initialize request argument(s) - request = pubsub_v1.DeleteSnapshotRequest( - snapshot="snapshot_value", - ) - - # Make the request - await client.delete_snapshot(request=request) - - Args: - request (Optional[Union[google.pubsub_v1.types.DeleteSnapshotRequest, dict]]): - The request object. Request for the ``DeleteSnapshot`` method. - snapshot (:class:`str`): - Required. The name of the snapshot to delete. Format is - ``projects/{project}/snapshots/{snap}``. - - This corresponds to the ``snapshot`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([snapshot]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, pubsub.DeleteSnapshotRequest): - request = pubsub.DeleteSnapshotRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if snapshot is not None: - request.snapshot = snapshot - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.delete_snapshot] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("snapshot", request.snapshot), - )), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - async def seek(self, - request: Optional[Union[pubsub.SeekRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pubsub.SeekResponse: - r"""Seeks an existing subscription to a point in time or to a given - snapshot, whichever is provided in the request. Snapshots are - used in [Seek] - (https://cloud.google.com/pubsub/docs/replay-overview) - operations, which allow you to manage message acknowledgments in - bulk. That is, you can set the acknowledgment state of messages - in an existing subscription to the state captured by a snapshot. - Note that both the subscription and the snapshot must be on the - same topic. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require 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 pubsub_v1 - - async def sample_seek(): - # Create a client - client = pubsub_v1.SubscriberAsyncClient() - - # Initialize request argument(s) - request = pubsub_v1.SeekRequest( - subscription="subscription_value", - ) - - # Make the request - response = await client.seek(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.pubsub_v1.types.SeekRequest, dict]]): - The request object. Request for the ``Seek`` method. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.pubsub_v1.types.SeekResponse: - Response for the Seek method (this response is empty). - """ - # 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, pubsub.SeekRequest): - request = pubsub.SeekRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.seek] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("subscription", request.subscription), - )), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def set_iam_policy( - self, - request: Optional[iam_policy_pb2.SetIamPolicyRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> policy_pb2.Policy: - r"""Sets the IAM access control policy on the specified function. - - Replaces any existing policy. - - Args: - request (:class:`~.policy_pb2.SetIamPolicyRequest`): - The request object. Request message for `SetIamPolicy` - method. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.policy_pb2.Policy: - Defines an Identity and Access Management (IAM) policy. - It is used to specify access control policies for Cloud - Platform resources. - A ``Policy`` is a collection of ``bindings``. A - ``binding`` binds one or more ``members`` to a single - ``role``. Members can be user accounts, service - accounts, Google groups, and domains (such as G Suite). - A ``role`` is a named list of permissions (defined by - IAM or configured by users). A ``binding`` can - optionally specify a ``condition``, which is a logic - expression that further constrains the role binding - based on attributes about the request and/or target - resource. - - **JSON Example** - - :: - { - "bindings": [ - { - "role": "roles/resourcemanager.organizationAdmin", - "members": [ - "user:mike@example.com", - "group:admins@example.com", - "domain:google.com", - "serviceAccount:my-project-id@appspot.gserviceaccount.com" - ] - }, - { - "role": "roles/resourcemanager.organizationViewer", - "members": ["user:eve@example.com"], - "condition": { - "title": "expirable access", - "description": "Does not grant access after Sep 2020", - "expression": "request.time < - timestamp('2020-10-01T00:00:00.000Z')", - } - } - ] - } - - **YAML Example** - - :: - - bindings: - - members: - - user:mike@example.com - - group:admins@example.com - - domain:google.com - - serviceAccount:my-project-id@appspot.gserviceaccount.com - role: roles/resourcemanager.organizationAdmin - - members: - - user:eve@example.com - role: roles/resourcemanager.organizationViewer - condition: - title: expirable access - description: Does not grant access after Sep 2020 - expression: request.time < timestamp('2020-10-01T00:00:00.000Z') - - For a description of IAM and its features, see the `IAM - developer's - guide `__. - """ - # Create or coerce a protobuf request object. - - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = iam_policy_pb2.SetIamPolicyRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.set_iam_policy, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("resource", request.resource),)), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - async def get_iam_policy( - self, - request: Optional[iam_policy_pb2.GetIamPolicyRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> policy_pb2.Policy: - r"""Gets the IAM access control policy for a function. - - Returns an empty policy if the function exists and does - not have a policy set. - - Args: - request (:class:`~.iam_policy_pb2.GetIamPolicyRequest`): - The request object. Request message for `GetIamPolicy` - method. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.policy_pb2.Policy: - Defines an Identity and Access Management (IAM) policy. - It is used to specify access control policies for Cloud - Platform resources. - A ``Policy`` is a collection of ``bindings``. A - ``binding`` binds one or more ``members`` to a single - ``role``. Members can be user accounts, service - accounts, Google groups, and domains (such as G Suite). - A ``role`` is a named list of permissions (defined by - IAM or configured by users). A ``binding`` can - optionally specify a ``condition``, which is a logic - expression that further constrains the role binding - based on attributes about the request and/or target - resource. - - **JSON Example** - - :: - - { - "bindings": [ - { - "role": "roles/resourcemanager.organizationAdmin", - "members": [ - "user:mike@example.com", - "group:admins@example.com", - "domain:google.com", - "serviceAccount:my-project-id@appspot.gserviceaccount.com" - ] - }, - { - "role": "roles/resourcemanager.organizationViewer", - "members": ["user:eve@example.com"], - "condition": { - "title": "expirable access", - "description": "Does not grant access after Sep 2020", - "expression": "request.time < - timestamp('2020-10-01T00:00:00.000Z')", - } - } - ] - } - - **YAML Example** - - :: - - bindings: - - members: - - user:mike@example.com - - group:admins@example.com - - domain:google.com - - serviceAccount:my-project-id@appspot.gserviceaccount.com - role: roles/resourcemanager.organizationAdmin - - members: - - user:eve@example.com - role: roles/resourcemanager.organizationViewer - condition: - title: expirable access - description: Does not grant access after Sep 2020 - expression: request.time < timestamp('2020-10-01T00:00:00.000Z') - - For a description of IAM and its features, see the `IAM - developer's - guide `__. - """ - # Create or coerce a protobuf request object. - - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = iam_policy_pb2.GetIamPolicyRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.get_iam_policy, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("resource", request.resource),)), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - async def test_iam_permissions( - self, - request: Optional[iam_policy_pb2.TestIamPermissionsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> iam_policy_pb2.TestIamPermissionsResponse: - r"""Tests the specified permissions against the IAM access control - policy for a function. - - If the function does not exist, this will - return an empty set of permissions, not a NOT_FOUND error. - - Args: - request (:class:`~.iam_policy_pb2.TestIamPermissionsRequest`): - The request object. Request message for - `TestIamPermissions` method. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~iam_policy_pb2.PolicyTestIamPermissionsResponse: - Response message for ``TestIamPermissions`` method. - """ - # Create or coerce a protobuf request object. - - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = iam_policy_pb2.TestIamPermissionsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.test_iam_permissions, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("resource", request.resource),)), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - async def __aenter__(self) -> "SubscriberAsyncClient": - return self - - async def __aexit__(self, exc_type, exc, tb): - await self.transport.close() - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -__all__ = ( - "SubscriberAsyncClient", -) diff --git a/owl-bot-staging/v1/google/pubsub_v1/services/subscriber/client.py b/owl-bot-staging/v1/google/pubsub_v1/services/subscriber/client.py deleted file mode 100644 index 30825a5e0..000000000 --- a/owl-bot-staging/v1/google/pubsub_v1/services/subscriber/client.py +++ /dev/null @@ -1,2788 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import os -import re -from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Iterable, Iterator, Sequence, Tuple, Type, Union, cast -import warnings - -from google.pubsub_v1 import gapic_version as package_version - -from google.api_core import client_options as client_options_lib -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport import mtls # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth.exceptions import MutualTLSChannelError # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object, None] # type: ignore - -from google.iam.v1 import iam_policy_pb2 # type: ignore -from google.iam.v1 import policy_pb2 # type: ignore -from google.protobuf import duration_pb2 # type: ignore -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from google.pubsub_v1.services.subscriber import pagers -from google.pubsub_v1.types import pubsub -from .transports.base import SubscriberTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import SubscriberGrpcTransport -from .transports.grpc_asyncio import SubscriberGrpcAsyncIOTransport -from .transports.rest import SubscriberRestTransport - - -class SubscriberClientMeta(type): - """Metaclass for the Subscriber 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[SubscriberTransport]] - _transport_registry["grpc"] = SubscriberGrpcTransport - _transport_registry["grpc_asyncio"] = SubscriberGrpcAsyncIOTransport - _transport_registry["rest"] = SubscriberRestTransport - - def get_transport_class(cls, - label: Optional[str] = None, - ) -> Type[SubscriberTransport]: - """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 SubscriberClient(metaclass=SubscriberClientMeta): - """The service that an application uses to manipulate subscriptions and - to consume messages from a subscription via the ``Pull`` method or - by establishing a bi-directional stream using the ``StreamingPull`` - method. - """ - - @staticmethod - def _get_default_mtls_endpoint(api_endpoint): - """Converts api endpoint to mTLS endpoint. - - Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to - "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. - Args: - api_endpoint (Optional[str]): the api endpoint to convert. - Returns: - str: converted mTLS api endpoint. - """ - if not api_endpoint: - return api_endpoint - - mtls_endpoint_re = re.compile( - r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" - ) - - m = mtls_endpoint_re.match(api_endpoint) - name, mtls, sandbox, googledomain = m.groups() - if mtls or not googledomain: - return api_endpoint - - if sandbox: - return api_endpoint.replace( - "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" - ) - - return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") - - # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. - DEFAULT_ENDPOINT = "pubsub.googleapis.com" - DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore - DEFAULT_ENDPOINT - ) - - _DEFAULT_ENDPOINT_TEMPLATE = "pubsub.{UNIVERSE_DOMAIN}" - _DEFAULT_UNIVERSE = "googleapis.com" - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - Args: - info (dict): The service account private key info. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - SubscriberClient: 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: - SubscriberClient: 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) -> SubscriberTransport: - """Returns the transport used by the client instance. - - Returns: - SubscriberTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def snapshot_path(project: str,snapshot: str,) -> str: - """Returns a fully-qualified snapshot string.""" - return "projects/{project}/snapshots/{snapshot}".format(project=project, snapshot=snapshot, ) - - @staticmethod - def parse_snapshot_path(path: str) -> Dict[str,str]: - """Parses a snapshot path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/snapshots/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def subscription_path(project: str,subscription: str,) -> str: - """Returns a fully-qualified subscription string.""" - return "projects/{project}/subscriptions/{subscription}".format(project=project, subscription=subscription, ) - - @staticmethod - def parse_subscription_path(path: str) -> Dict[str,str]: - """Parses a subscription path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/subscriptions/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def topic_path(project: str,topic: str,) -> str: - """Returns a fully-qualified topic string.""" - return "projects/{project}/topics/{topic}".format(project=project, topic=topic, ) - - @staticmethod - def parse_topic_path(path: str) -> Dict[str,str]: - """Parses a topic path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/topics/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_billing_account_path(billing_account: str, ) -> str: - """Returns a fully-qualified billing_account string.""" - return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - - @staticmethod - def parse_common_billing_account_path(path: str) -> Dict[str,str]: - """Parse a billing_account path into its component segments.""" - m = re.match(r"^billingAccounts/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_folder_path(folder: str, ) -> str: - """Returns a fully-qualified folder string.""" - return "folders/{folder}".format(folder=folder, ) - - @staticmethod - def parse_common_folder_path(path: str) -> Dict[str,str]: - """Parse a folder path into its component segments.""" - m = re.match(r"^folders/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_organization_path(organization: str, ) -> str: - """Returns a fully-qualified organization string.""" - return "organizations/{organization}".format(organization=organization, ) - - @staticmethod - def parse_common_organization_path(path: str) -> Dict[str,str]: - """Parse a organization path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_project_path(project: str, ) -> str: - """Returns a fully-qualified project string.""" - return "projects/{project}".format(project=project, ) - - @staticmethod - def parse_common_project_path(path: str) -> Dict[str,str]: - """Parse a project path into its component segments.""" - m = re.match(r"^projects/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_location_path(project: str, location: str, ) -> str: - """Returns a fully-qualified location string.""" - return "projects/{project}/locations/{location}".format(project=project, location=location, ) - - @staticmethod - def parse_common_location_path(path: str) -> Dict[str,str]: - """Parse a location path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): - """Deprecated. Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variable is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - - warnings.warn("get_mtls_endpoint_and_cert_source is deprecated. Use the api_endpoint property instead.", - DeprecationWarning) - if client_options is None: - client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") - use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") - if use_mtls_endpoint not in ("auto", "never", "always"): - raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") - - # Figure out the client cert source to use. - client_cert_source = None - if use_client_cert == "true": - if client_options.client_cert_source: - client_cert_source = client_options.client_cert_source - elif mtls.has_default_client_cert_source(): - client_cert_source = mtls.default_client_cert_source() - - # Figure out which api endpoint to use. - if client_options.api_endpoint is not None: - api_endpoint = client_options.api_endpoint - elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): - api_endpoint = cls.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = cls.DEFAULT_ENDPOINT - - return api_endpoint, client_cert_source - - @staticmethod - def _read_environment_variables(): - """Returns the environment variables used by the client. - - Returns: - Tuple[bool, str, str]: returns the GOOGLE_API_USE_CLIENT_CERTIFICATE, - GOOGLE_API_USE_MTLS_ENDPOINT, and GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variables. - - Raises: - ValueError: If GOOGLE_API_USE_CLIENT_CERTIFICATE is not - any of ["true", "false"]. - google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT - is not any of ["auto", "never", "always"]. - """ - use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false").lower() - use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto").lower() - universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") - if use_mtls_endpoint not in ("auto", "never", "always"): - raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env - - @staticmethod - def _get_client_cert_source(provided_cert_source, use_cert_flag): - """Return the client cert source to be used by the client. - - Args: - provided_cert_source (bytes): The client certificate source provided. - use_cert_flag (bool): A flag indicating whether to use the client certificate. - - Returns: - bytes or None: The client cert source to be used by the client. - """ - client_cert_source = None - if use_cert_flag: - if provided_cert_source: - client_cert_source = provided_cert_source - elif mtls.has_default_client_cert_source(): - client_cert_source = mtls.default_client_cert_source() - return client_cert_source - - @staticmethod - def _get_api_endpoint(api_override, client_cert_source, universe_domain, use_mtls_endpoint): - """Return the API endpoint used by the client. - - Args: - api_override (str): The API endpoint override. If specified, this is always - the return value of this function and the other arguments are not used. - client_cert_source (bytes): The client certificate source used by the client. - universe_domain (str): The universe domain used by the client. - use_mtls_endpoint (str): How to use the mTLS endpoint, which depends also on the other parameters. - Possible values are "always", "auto", or "never". - - Returns: - str: The API endpoint to be used by the client. - """ - if api_override is not None: - api_endpoint = api_override - elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): - _default_universe = SubscriberClient._DEFAULT_UNIVERSE - if universe_domain != _default_universe: - raise MutualTLSChannelError(f"mTLS is not supported in any universe other than {_default_universe}.") - api_endpoint = SubscriberClient.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = SubscriberClient._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 = SubscriberClient._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 - - @staticmethod - def _compare_universes(client_universe: str, - credentials: ga_credentials.Credentials) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = SubscriberClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError("The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default.") - return True - - 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. - """ - self._is_universe_domain_valid = (self._is_universe_domain_valid or - SubscriberClient._compare_universes(self.universe_domain, self.transport._credentials)) - return self._is_universe_domain_valid - - @property - def api_endpoint(self): - """Return the API endpoint used by the client instance. - - Returns: - str: The API endpoint used by the client instance. - """ - return self._api_endpoint - - @property - def universe_domain(self) -> str: - """Return the universe domain used by the client instance. - - Returns: - str: The universe domain used by the client instance. - """ - return self._universe_domain - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, SubscriberTransport, Callable[..., SubscriberTransport]]] = None, - client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the subscriber 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,SubscriberTransport,Callable[..., SubscriberTransport]]]): - 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 SubscriberTransport constructor. - If set to None, a transport is chosen automatically. - client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): - Custom options for the client. - - 1. The ``api_endpoint`` property can be used to override the - default endpoint provided by the client when ``transport`` is - not explicitly provided. Only if this property is not set and - ``transport`` was not explicitly provided, the endpoint is - determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment - variable, which have one of the following values: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto-switch to the - default mTLS endpoint if client certificate is present; this is - the default value). - - 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide a client certificate for mTLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - - 3. The ``universe_domain`` property can be used to override the - default "googleapis.com" universe. Note that the ``api_endpoint`` - property still takes precedence; and ``universe_domain`` is - currently not supported for mTLS. - - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - """ - self._client_options = client_options - if isinstance(self._client_options, dict): - self._client_options = client_options_lib.from_dict(self._client_options) - if self._client_options is None: - self._client_options = client_options_lib.ClientOptions() - self._client_options = cast(client_options_lib.ClientOptions, self._client_options) - - universe_domain_opt = getattr(self._client_options, 'universe_domain', None) - - self._use_client_cert, self._use_mtls_endpoint, self._universe_domain_env = SubscriberClient._read_environment_variables() - self._client_cert_source = SubscriberClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) - self._universe_domain = SubscriberClient._get_universe_domain(universe_domain_opt, self._universe_domain_env) - self._api_endpoint = None # updated below, depending on `transport` - - # Initialize the universe domain validation. - self._is_universe_domain_valid = False - - api_key_value = getattr(self._client_options, "api_key", None) - if api_key_value and credentials: - raise ValueError("client_options.api_key and credentials are mutually exclusive") - - # Save or instantiate the transport. - # Ordinarily, we provide the transport, but allowing a custom transport - # instance provides an extensibility point for unusual situations. - transport_provided = isinstance(transport, SubscriberTransport) - if transport_provided: - # transport is a SubscriberTransport 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(SubscriberTransport, transport) - self._api_endpoint = self._transport.host - - self._api_endpoint = (self._api_endpoint or - SubscriberClient._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[SubscriberTransport], Callable[..., SubscriberTransport]] = ( - SubscriberClient.get_transport_class(transport) - if isinstance(transport, str) or transport is None - else cast(Callable[..., SubscriberTransport], transport) - ) - # initialize with the provided callable or the passed in class - self._transport = transport_init( - credentials=credentials, - credentials_file=self._client_options.credentials_file, - host=self._api_endpoint, - scopes=self._client_options.scopes, - client_cert_source_for_mtls=self._client_cert_source, - quota_project_id=self._client_options.quota_project_id, - client_info=client_info, - always_use_jwt_access=True, - api_audience=self._client_options.api_audience, - ) - - def create_subscription(self, - request: Optional[Union[pubsub.Subscription, dict]] = None, - *, - name: Optional[str] = None, - topic: Optional[str] = None, - push_config: Optional[pubsub.PushConfig] = None, - ack_deadline_seconds: Optional[int] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pubsub.Subscription: - r"""Creates a subscription to a given topic. See the [resource name - rules] - (https://cloud.google.com/pubsub/docs/pubsub-basics#resource_names). - If the subscription already exists, returns ``ALREADY_EXISTS``. - If the corresponding topic doesn't exist, returns ``NOT_FOUND``. - - If the name is not provided in the request, the server will - assign a random name for this subscription on the same project - as the topic, conforming to the [resource name format] - (https://cloud.google.com/pubsub/docs/pubsub-basics#resource_names). - The generated name is populated in the returned Subscription - object. Note that for REST API requests, you must specify a name - in the request. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require 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 pubsub_v1 - - def sample_create_subscription(): - # Create a client - client = pubsub_v1.SubscriberClient() - - # Initialize request argument(s) - request = pubsub_v1.Subscription( - name="name_value", - topic="topic_value", - ) - - # Make the request - response = client.create_subscription(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.pubsub_v1.types.Subscription, dict]): - The request object. A subscription resource. If none of ``push_config``, - ``bigquery_config``, or ``cloud_storage_config`` is set, - then the subscriber will pull and ack messages using API - methods. At most one of these fields may be set. - name (str): - Required. The name of the subscription. It must have the - format - ``"projects/{project}/subscriptions/{subscription}"``. - ``{subscription}`` must start with a letter, and contain - only letters (``[A-Za-z]``), numbers (``[0-9]``), dashes - (``-``), underscores (``_``), periods (``.``), tildes - (``~``), plus (``+``) or percent signs (``%``). It must - be between 3 and 255 characters in length, and it must - not start with ``"goog"``. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - topic (str): - Required. The name of the topic from which this - subscription is receiving messages. Format is - ``projects/{project}/topics/{topic}``. The value of this - field will be ``_deleted-topic_`` if the topic has been - deleted. - - This corresponds to the ``topic`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - push_config (google.pubsub_v1.types.PushConfig): - Optional. If push delivery is used - with this subscription, this field is - used to configure it. - - This corresponds to the ``push_config`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - ack_deadline_seconds (int): - Optional. The approximate amount of time (on a - best-effort basis) Pub/Sub waits for the subscriber to - acknowledge receipt before resending the message. In the - interval after the message is delivered and before it is - acknowledged, it is considered to be *outstanding*. - During that time period, the message will not be - redelivered (on a best-effort basis). - - For pull subscriptions, this value is used as the - initial value for the ack deadline. To override this - value for a given message, call ``ModifyAckDeadline`` - with the corresponding ``ack_id`` if using non-streaming - pull or send the ``ack_id`` in a - ``StreamingModifyAckDeadlineRequest`` if using streaming - pull. The minimum custom deadline you can specify is 10 - seconds. The maximum custom deadline you can specify is - 600 seconds (10 minutes). If this parameter is 0, a - default value of 10 seconds is used. - - For push delivery, this value is also used to set the - request timeout for the call to the push endpoint. - - If the subscriber never acknowledges the message, the - Pub/Sub system will eventually redeliver the message. - - This corresponds to the ``ack_deadline_seconds`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.pubsub_v1.types.Subscription: - A subscription resource. If none of push_config, bigquery_config, or - cloud_storage_config is set, then the subscriber will - pull and ack messages using API methods. At most one - of these fields may be set. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name, topic, push_config, ack_deadline_seconds]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, pubsub.Subscription): - request = pubsub.Subscription(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - if topic is not None: - request.topic = topic - if push_config is not None: - request.push_config = push_config - if ack_deadline_seconds is not None: - request.ack_deadline_seconds = ack_deadline_seconds - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_subscription] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def get_subscription(self, - request: Optional[Union[pubsub.GetSubscriptionRequest, dict]] = None, - *, - subscription: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pubsub.Subscription: - r"""Gets the configuration details of a subscription. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require 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 pubsub_v1 - - def sample_get_subscription(): - # Create a client - client = pubsub_v1.SubscriberClient() - - # Initialize request argument(s) - request = pubsub_v1.GetSubscriptionRequest( - subscription="subscription_value", - ) - - # Make the request - response = client.get_subscription(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.pubsub_v1.types.GetSubscriptionRequest, dict]): - The request object. Request for the GetSubscription - method. - subscription (str): - Required. The name of the subscription to get. Format is - ``projects/{project}/subscriptions/{sub}``. - - This corresponds to the ``subscription`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.pubsub_v1.types.Subscription: - A subscription resource. If none of push_config, bigquery_config, or - cloud_storage_config is set, then the subscriber will - pull and ack messages using API methods. At most one - of these fields may be set. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([subscription]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, pubsub.GetSubscriptionRequest): - request = pubsub.GetSubscriptionRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if subscription is not None: - request.subscription = subscription - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.get_subscription] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("subscription", request.subscription), - )), - ) - - # 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_subscription(self, - request: Optional[Union[pubsub.UpdateSubscriptionRequest, dict]] = None, - *, - subscription: Optional[pubsub.Subscription] = None, - update_mask: Optional[field_mask_pb2.FieldMask] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pubsub.Subscription: - r"""Updates an existing subscription by updating the - fields specified in the update mask. Note that certain - properties of a subscription, such as its topic, are not - modifiable. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require 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 pubsub_v1 - - def sample_update_subscription(): - # Create a client - client = pubsub_v1.SubscriberClient() - - # Initialize request argument(s) - subscription = pubsub_v1.Subscription() - subscription.name = "name_value" - subscription.topic = "topic_value" - - request = pubsub_v1.UpdateSubscriptionRequest( - subscription=subscription, - ) - - # Make the request - response = client.update_subscription(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.pubsub_v1.types.UpdateSubscriptionRequest, dict]): - The request object. Request for the UpdateSubscription - method. - subscription (google.pubsub_v1.types.Subscription): - Required. The updated subscription - object. - - This corresponds to the ``subscription`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Required. Indicates which fields in - the provided subscription to update. - Must be specified and non-empty. - - This corresponds to the ``update_mask`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.pubsub_v1.types.Subscription: - A subscription resource. If none of push_config, bigquery_config, or - cloud_storage_config is set, then the subscriber will - pull and ack messages using API methods. At most one - of these fields may be set. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([subscription, update_mask]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, pubsub.UpdateSubscriptionRequest): - request = pubsub.UpdateSubscriptionRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if subscription is not None: - request.subscription = subscription - if update_mask is not None: - request.update_mask = update_mask - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.update_subscription] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("subscription.name", request.subscription.name), - )), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def list_subscriptions(self, - request: Optional[Union[pubsub.ListSubscriptionsRequest, dict]] = None, - *, - project: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListSubscriptionsPager: - r"""Lists matching subscriptions. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require 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 pubsub_v1 - - def sample_list_subscriptions(): - # Create a client - client = pubsub_v1.SubscriberClient() - - # Initialize request argument(s) - request = pubsub_v1.ListSubscriptionsRequest( - project="project_value", - ) - - # Make the request - page_result = client.list_subscriptions(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.pubsub_v1.types.ListSubscriptionsRequest, dict]): - The request object. Request for the ``ListSubscriptions`` method. - project (str): - Required. The name of the project in which to list - subscriptions. Format is ``projects/{project-id}``. - - This corresponds to the ``project`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.pubsub_v1.services.subscriber.pagers.ListSubscriptionsPager: - Response for the ListSubscriptions method. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([project]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, pubsub.ListSubscriptionsRequest): - request = pubsub.ListSubscriptionsRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if project is not None: - request.project = project - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.list_subscriptions] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("project", request.project), - )), - ) - - # 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.ListSubscriptionsPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def delete_subscription(self, - request: Optional[Union[pubsub.DeleteSubscriptionRequest, dict]] = None, - *, - subscription: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes an existing subscription. All messages retained in the - subscription are immediately dropped. Calls to ``Pull`` after - deletion will return ``NOT_FOUND``. After a subscription is - deleted, a new one may be created with the same name, but the - new one has no association with the old subscription or its - topic unless the same topic is specified. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require 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 pubsub_v1 - - def sample_delete_subscription(): - # Create a client - client = pubsub_v1.SubscriberClient() - - # Initialize request argument(s) - request = pubsub_v1.DeleteSubscriptionRequest( - subscription="subscription_value", - ) - - # Make the request - client.delete_subscription(request=request) - - Args: - request (Union[google.pubsub_v1.types.DeleteSubscriptionRequest, dict]): - The request object. Request for the DeleteSubscription - method. - subscription (str): - Required. The subscription to delete. Format is - ``projects/{project}/subscriptions/{sub}``. - - This corresponds to the ``subscription`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([subscription]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, pubsub.DeleteSubscriptionRequest): - request = pubsub.DeleteSubscriptionRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if subscription is not None: - request.subscription = subscription - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.delete_subscription] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("subscription", request.subscription), - )), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - def modify_ack_deadline(self, - request: Optional[Union[pubsub.ModifyAckDeadlineRequest, dict]] = None, - *, - subscription: Optional[str] = None, - ack_ids: Optional[MutableSequence[str]] = None, - ack_deadline_seconds: Optional[int] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Modifies the ack deadline for a specific message. This method is - useful to indicate that more time is needed to process a message - by the subscriber, or to make the message available for - redelivery if the processing was interrupted. Note that this - does not modify the subscription-level ``ackDeadlineSeconds`` - used for subsequent 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 pubsub_v1 - - def sample_modify_ack_deadline(): - # Create a client - client = pubsub_v1.SubscriberClient() - - # Initialize request argument(s) - request = pubsub_v1.ModifyAckDeadlineRequest( - subscription="subscription_value", - ack_ids=['ack_ids_value1', 'ack_ids_value2'], - ack_deadline_seconds=2066, - ) - - # Make the request - client.modify_ack_deadline(request=request) - - Args: - request (Union[google.pubsub_v1.types.ModifyAckDeadlineRequest, dict]): - The request object. Request for the ModifyAckDeadline - method. - subscription (str): - Required. The name of the subscription. Format is - ``projects/{project}/subscriptions/{sub}``. - - This corresponds to the ``subscription`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - ack_ids (MutableSequence[str]): - Required. List of acknowledgment IDs. - This corresponds to the ``ack_ids`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - ack_deadline_seconds (int): - Required. The new ack deadline with respect to the time - this request was sent to the Pub/Sub system. For - example, if the value is 10, the new ack deadline will - expire 10 seconds after the ``ModifyAckDeadline`` call - was made. Specifying zero might immediately make the - message available for delivery to another subscriber - client. This typically results in an increase in the - rate of message redeliveries (that is, duplicates). The - minimum deadline you can specify is 0 seconds. The - maximum deadline you can specify in a single request is - 600 seconds (10 minutes). - - This corresponds to the ``ack_deadline_seconds`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([subscription, ack_ids, ack_deadline_seconds]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, pubsub.ModifyAckDeadlineRequest): - request = pubsub.ModifyAckDeadlineRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if subscription is not None: - request.subscription = subscription - if ack_ids is not None: - request.ack_ids = ack_ids - if ack_deadline_seconds is not None: - request.ack_deadline_seconds = ack_deadline_seconds - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.modify_ack_deadline] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("subscription", request.subscription), - )), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - def acknowledge(self, - request: Optional[Union[pubsub.AcknowledgeRequest, dict]] = None, - *, - subscription: Optional[str] = None, - ack_ids: Optional[MutableSequence[str]] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Acknowledges the messages associated with the ``ack_ids`` in the - ``AcknowledgeRequest``. The Pub/Sub system can remove the - relevant messages from the subscription. - - Acknowledging a message whose ack deadline has expired may - succeed, but such a message may be redelivered later. - Acknowledging a message more than once will not result in 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 pubsub_v1 - - def sample_acknowledge(): - # Create a client - client = pubsub_v1.SubscriberClient() - - # Initialize request argument(s) - request = pubsub_v1.AcknowledgeRequest( - subscription="subscription_value", - ack_ids=['ack_ids_value1', 'ack_ids_value2'], - ) - - # Make the request - client.acknowledge(request=request) - - Args: - request (Union[google.pubsub_v1.types.AcknowledgeRequest, dict]): - The request object. Request for the Acknowledge method. - subscription (str): - Required. The subscription whose message is being - acknowledged. Format is - ``projects/{project}/subscriptions/{sub}``. - - This corresponds to the ``subscription`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - ack_ids (MutableSequence[str]): - Required. The acknowledgment ID for the messages being - acknowledged that was returned by the Pub/Sub system in - the ``Pull`` response. Must not be empty. - - This corresponds to the ``ack_ids`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([subscription, ack_ids]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, pubsub.AcknowledgeRequest): - request = pubsub.AcknowledgeRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if subscription is not None: - request.subscription = subscription - if ack_ids is not None: - request.ack_ids = ack_ids - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.acknowledge] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("subscription", request.subscription), - )), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - def pull(self, - request: Optional[Union[pubsub.PullRequest, dict]] = None, - *, - subscription: Optional[str] = None, - return_immediately: Optional[bool] = None, - max_messages: Optional[int] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pubsub.PullResponse: - r"""Pulls messages from the server. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require 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 pubsub_v1 - - def sample_pull(): - # Create a client - client = pubsub_v1.SubscriberClient() - - # Initialize request argument(s) - request = pubsub_v1.PullRequest( - subscription="subscription_value", - max_messages=1277, - ) - - # Make the request - response = client.pull(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.pubsub_v1.types.PullRequest, dict]): - The request object. Request for the ``Pull`` method. - subscription (str): - Required. The subscription from which messages should be - pulled. Format is - ``projects/{project}/subscriptions/{sub}``. - - This corresponds to the ``subscription`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - return_immediately (bool): - Optional. If this field set to true, the system will - respond immediately even if it there are no messages - available to return in the ``Pull`` response. Otherwise, - the system may wait (for a bounded amount of time) until - at least one message is available, rather than returning - no messages. Warning: setting this field to ``true`` is - discouraged because it adversely impacts the performance - of ``Pull`` operations. We recommend that users do not - set this field. - - This corresponds to the ``return_immediately`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - max_messages (int): - Required. The maximum number of - messages to return for this request. - Must be a positive integer. The Pub/Sub - system may return fewer than the number - specified. - - This corresponds to the ``max_messages`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.pubsub_v1.types.PullResponse: - Response for the Pull 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. - has_flattened_params = any([subscription, return_immediately, max_messages]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, pubsub.PullRequest): - request = pubsub.PullRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if subscription is not None: - request.subscription = subscription - if return_immediately is not None: - request.return_immediately = return_immediately - if max_messages is not None: - request.max_messages = max_messages - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.pull] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("subscription", request.subscription), - )), - ) - - # 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 streaming_pull(self, - requests: Optional[Iterator[pubsub.StreamingPullRequest]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> Iterable[pubsub.StreamingPullResponse]: - r"""Establishes a stream with the server, which sends messages down - to the client. The client streams acknowledgements and ack - deadline modifications back to the server. The server will close - the stream and return the status on any error. The server may - close the stream with status ``UNAVAILABLE`` to reassign - server-side resources, in which case, the client should - re-establish the stream. Flow control can be achieved by - configuring the underlying RPC channel. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google import pubsub_v1 - - def sample_streaming_pull(): - # Create a client - client = pubsub_v1.SubscriberClient() - - # Initialize request argument(s) - request = pubsub_v1.StreamingPullRequest( - subscription="subscription_value", - stream_ack_deadline_seconds=2813, - ) - - # This method expects an iterator which contains - # 'pubsub_v1.StreamingPullRequest' 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.streaming_pull(requests=request_generator()) - - # Handle the response - for response in stream: - print(response) - - Args: - requests (Iterator[google.pubsub_v1.types.StreamingPullRequest]): - The request object iterator. Request for the ``StreamingPull`` streaming RPC method. - This request is used to establish the initial stream as - well as to stream acknowledgements and ack deadline - modifications from the client to the server. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - Iterable[google.pubsub_v1.types.StreamingPullResponse]: - Response for the StreamingPull method. This response is used to stream - messages from the server to the client. - - """ - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.streaming_pull] - - # 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 modify_push_config(self, - request: Optional[Union[pubsub.ModifyPushConfigRequest, dict]] = None, - *, - subscription: Optional[str] = None, - push_config: Optional[pubsub.PushConfig] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Modifies the ``PushConfig`` for a specified subscription. - - This may be used to change a push subscription to a pull one - (signified by an empty ``PushConfig``) or vice versa, or change - the endpoint URL and other attributes of a push subscription. - Messages will accumulate for delivery continuously through the - call regardless of changes to the ``PushConfig``. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require 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 pubsub_v1 - - def sample_modify_push_config(): - # Create a client - client = pubsub_v1.SubscriberClient() - - # Initialize request argument(s) - request = pubsub_v1.ModifyPushConfigRequest( - subscription="subscription_value", - ) - - # Make the request - client.modify_push_config(request=request) - - Args: - request (Union[google.pubsub_v1.types.ModifyPushConfigRequest, dict]): - The request object. Request for the ModifyPushConfig - method. - subscription (str): - Required. The name of the subscription. Format is - ``projects/{project}/subscriptions/{sub}``. - - This corresponds to the ``subscription`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - push_config (google.pubsub_v1.types.PushConfig): - Required. The push configuration for future deliveries. - - An empty ``pushConfig`` indicates that the Pub/Sub - system should stop pushing messages from the given - subscription and allow messages to be pulled and - acknowledged - effectively pausing the subscription if - ``Pull`` or ``StreamingPull`` is not called. - - This corresponds to the ``push_config`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([subscription, push_config]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, pubsub.ModifyPushConfigRequest): - request = pubsub.ModifyPushConfigRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if subscription is not None: - request.subscription = subscription - if push_config is not None: - request.push_config = push_config - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.modify_push_config] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("subscription", request.subscription), - )), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - def get_snapshot(self, - request: Optional[Union[pubsub.GetSnapshotRequest, dict]] = None, - *, - snapshot: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pubsub.Snapshot: - r"""Gets the configuration details of a snapshot. Snapshots are used - in - `Seek `__ - operations, which allow you to manage message acknowledgments in - bulk. That is, you can set the acknowledgment state of messages - in an existing subscription to the state captured by a snapshot. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require 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 pubsub_v1 - - def sample_get_snapshot(): - # Create a client - client = pubsub_v1.SubscriberClient() - - # Initialize request argument(s) - request = pubsub_v1.GetSnapshotRequest( - snapshot="snapshot_value", - ) - - # Make the request - response = client.get_snapshot(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.pubsub_v1.types.GetSnapshotRequest, dict]): - The request object. Request for the GetSnapshot method. - snapshot (str): - Required. The name of the snapshot to get. Format is - ``projects/{project}/snapshots/{snap}``. - - This corresponds to the ``snapshot`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.pubsub_v1.types.Snapshot: - A snapshot resource. Snapshots are used in - [Seek](https://cloud.google.com/pubsub/docs/replay-overview) - operations, which allow you to manage message - acknowledgments in bulk. That is, you can set the - acknowledgment state of messages in an existing - subscription to the state captured by a snapshot. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([snapshot]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, pubsub.GetSnapshotRequest): - request = pubsub.GetSnapshotRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if snapshot is not None: - request.snapshot = snapshot - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.get_snapshot] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("snapshot", request.snapshot), - )), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def list_snapshots(self, - request: Optional[Union[pubsub.ListSnapshotsRequest, dict]] = None, - *, - project: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListSnapshotsPager: - r"""Lists the existing snapshots. Snapshots are used in - `Seek `__ - operations, which allow you to manage message acknowledgments in - bulk. That is, you can set the acknowledgment state of messages - in an existing subscription to the state captured by a snapshot. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require 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 pubsub_v1 - - def sample_list_snapshots(): - # Create a client - client = pubsub_v1.SubscriberClient() - - # Initialize request argument(s) - request = pubsub_v1.ListSnapshotsRequest( - project="project_value", - ) - - # Make the request - page_result = client.list_snapshots(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.pubsub_v1.types.ListSnapshotsRequest, dict]): - The request object. Request for the ``ListSnapshots`` method. - project (str): - Required. The name of the project in which to list - snapshots. Format is ``projects/{project-id}``. - - This corresponds to the ``project`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.pubsub_v1.services.subscriber.pagers.ListSnapshotsPager: - Response for the ListSnapshots method. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([project]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, pubsub.ListSnapshotsRequest): - request = pubsub.ListSnapshotsRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if project is not None: - request.project = project - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.list_snapshots] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("project", request.project), - )), - ) - - # 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.ListSnapshotsPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def create_snapshot(self, - request: Optional[Union[pubsub.CreateSnapshotRequest, dict]] = None, - *, - name: Optional[str] = None, - subscription: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pubsub.Snapshot: - r"""Creates a snapshot from the requested subscription. Snapshots - are used in - `Seek `__ - operations, which allow you to manage message acknowledgments in - bulk. That is, you can set the acknowledgment state of messages - in an existing subscription to the state captured by a snapshot. - If the snapshot already exists, returns ``ALREADY_EXISTS``. If - the requested subscription doesn't exist, returns ``NOT_FOUND``. - If the backlog in the subscription is too old -- and the - resulting snapshot would expire in less than 1 hour -- then - ``FAILED_PRECONDITION`` is returned. See also the - ``Snapshot.expire_time`` field. If the name is not provided in - the request, the server will assign a random name for this - snapshot on the same project as the subscription, conforming to - the [resource name format] - (https://cloud.google.com/pubsub/docs/pubsub-basics#resource_names). - The generated name is populated in the returned Snapshot object. - Note that for REST API requests, you must specify a name in the - request. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require 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 pubsub_v1 - - def sample_create_snapshot(): - # Create a client - client = pubsub_v1.SubscriberClient() - - # Initialize request argument(s) - request = pubsub_v1.CreateSnapshotRequest( - name="name_value", - subscription="subscription_value", - ) - - # Make the request - response = client.create_snapshot(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.pubsub_v1.types.CreateSnapshotRequest, dict]): - The request object. Request for the ``CreateSnapshot`` method. - name (str): - Required. User-provided name for this snapshot. If the - name is not provided in the request, the server will - assign a random name for this snapshot on the same - project as the subscription. Note that for REST API - requests, you must specify a name. See the `resource - name - rules `__. - Format is ``projects/{project}/snapshots/{snap}``. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - subscription (str): - Required. The subscription whose backlog the snapshot - retains. Specifically, the created snapshot is - guaranteed to retain: (a) The existing backlog on the - subscription. More precisely, this is defined as the - messages in the subscription's backlog that are - unacknowledged upon the successful completion of the - ``CreateSnapshot`` request; as well as: (b) Any messages - published to the subscription's topic following the - successful completion of the CreateSnapshot request. - Format is ``projects/{project}/subscriptions/{sub}``. - - This corresponds to the ``subscription`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.pubsub_v1.types.Snapshot: - A snapshot resource. Snapshots are used in - [Seek](https://cloud.google.com/pubsub/docs/replay-overview) - operations, which allow you to manage message - acknowledgments in bulk. That is, you can set the - acknowledgment state of messages in an existing - subscription to the state captured by a snapshot. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name, subscription]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, pubsub.CreateSnapshotRequest): - request = pubsub.CreateSnapshotRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - if subscription is not None: - request.subscription = subscription - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_snapshot] - - # Certain 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_snapshot(self, - request: Optional[Union[pubsub.UpdateSnapshotRequest, dict]] = None, - *, - snapshot: Optional[pubsub.Snapshot] = None, - update_mask: Optional[field_mask_pb2.FieldMask] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pubsub.Snapshot: - r"""Updates an existing snapshot by updating the fields specified in - the update mask. Snapshots are used in - `Seek `__ - operations, which allow you to manage message acknowledgments in - bulk. That is, you can set the acknowledgment state of messages - in an existing subscription to the state captured by a snapshot. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require 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 pubsub_v1 - - def sample_update_snapshot(): - # Create a client - client = pubsub_v1.SubscriberClient() - - # Initialize request argument(s) - request = pubsub_v1.UpdateSnapshotRequest( - ) - - # Make the request - response = client.update_snapshot(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.pubsub_v1.types.UpdateSnapshotRequest, dict]): - The request object. Request for the UpdateSnapshot - method. - snapshot (google.pubsub_v1.types.Snapshot): - Required. The updated snapshot - object. - - This corresponds to the ``snapshot`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Required. Indicates which fields in - the provided snapshot to update. Must be - specified and non-empty. - - This corresponds to the ``update_mask`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.pubsub_v1.types.Snapshot: - A snapshot resource. Snapshots are used in - [Seek](https://cloud.google.com/pubsub/docs/replay-overview) - operations, which allow you to manage message - acknowledgments in bulk. That is, you can set the - acknowledgment state of messages in an existing - subscription to the state captured by a snapshot. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([snapshot, update_mask]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, pubsub.UpdateSnapshotRequest): - request = pubsub.UpdateSnapshotRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if snapshot is not None: - request.snapshot = snapshot - if update_mask is not None: - request.update_mask = update_mask - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.update_snapshot] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("snapshot.name", request.snapshot.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_snapshot(self, - request: Optional[Union[pubsub.DeleteSnapshotRequest, dict]] = None, - *, - snapshot: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Removes an existing snapshot. Snapshots are used in [Seek] - (https://cloud.google.com/pubsub/docs/replay-overview) - operations, which allow you to manage message acknowledgments in - bulk. That is, you can set the acknowledgment state of messages - in an existing subscription to the state captured by a snapshot. - When the snapshot is deleted, all messages retained in the - snapshot are immediately dropped. After a snapshot is deleted, a - new one may be created with the same name, but the new one has - no association with the old snapshot or its subscription, unless - the same subscription is specified. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require 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 pubsub_v1 - - def sample_delete_snapshot(): - # Create a client - client = pubsub_v1.SubscriberClient() - - # Initialize request argument(s) - request = pubsub_v1.DeleteSnapshotRequest( - snapshot="snapshot_value", - ) - - # Make the request - client.delete_snapshot(request=request) - - Args: - request (Union[google.pubsub_v1.types.DeleteSnapshotRequest, dict]): - The request object. Request for the ``DeleteSnapshot`` method. - snapshot (str): - Required. The name of the snapshot to delete. Format is - ``projects/{project}/snapshots/{snap}``. - - This corresponds to the ``snapshot`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([snapshot]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, pubsub.DeleteSnapshotRequest): - request = pubsub.DeleteSnapshotRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if snapshot is not None: - request.snapshot = snapshot - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.delete_snapshot] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("snapshot", request.snapshot), - )), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - def seek(self, - request: Optional[Union[pubsub.SeekRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pubsub.SeekResponse: - r"""Seeks an existing subscription to a point in time or to a given - snapshot, whichever is provided in the request. Snapshots are - used in [Seek] - (https://cloud.google.com/pubsub/docs/replay-overview) - operations, which allow you to manage message acknowledgments in - bulk. That is, you can set the acknowledgment state of messages - in an existing subscription to the state captured by a snapshot. - Note that both the subscription and the snapshot must be on the - same topic. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require 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 pubsub_v1 - - def sample_seek(): - # Create a client - client = pubsub_v1.SubscriberClient() - - # Initialize request argument(s) - request = pubsub_v1.SeekRequest( - subscription="subscription_value", - ) - - # Make the request - response = client.seek(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.pubsub_v1.types.SeekRequest, dict]): - The request object. Request for the ``Seek`` method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.pubsub_v1.types.SeekResponse: - Response for the Seek method (this response is empty). - """ - # 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, pubsub.SeekRequest): - request = pubsub.SeekRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.seek] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("subscription", request.subscription), - )), - ) - - # 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) -> "SubscriberClient": - 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 set_iam_policy( - self, - request: Optional[iam_policy_pb2.SetIamPolicyRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> policy_pb2.Policy: - r"""Sets the IAM access control policy on the specified function. - - Replaces any existing policy. - - Args: - request (:class:`~.iam_policy_pb2.SetIamPolicyRequest`): - The request object. Request message for `SetIamPolicy` - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.policy_pb2.Policy: - Defines an Identity and Access Management (IAM) policy. - It is used to specify access control policies for Cloud - Platform resources. - A ``Policy`` is a collection of ``bindings``. A - ``binding`` binds one or more ``members`` to a single - ``role``. Members can be user accounts, service - accounts, Google groups, and domains (such as G Suite). - A ``role`` is a named list of permissions (defined by - IAM or configured by users). A ``binding`` can - optionally specify a ``condition``, which is a logic - expression that further constrains the role binding - based on attributes about the request and/or target - resource. - - **JSON Example** - - :: - - { - "bindings": [ - { - "role": "roles/resourcemanager.organizationAdmin", - "members": [ - "user:mike@example.com", - "group:admins@example.com", - "domain:google.com", - "serviceAccount:my-project-id@appspot.gserviceaccount.com" - ] - }, - { - "role": "roles/resourcemanager.organizationViewer", - "members": ["user:eve@example.com"], - "condition": { - "title": "expirable access", - "description": "Does not grant access after Sep 2020", - "expression": "request.time < - timestamp('2020-10-01T00:00:00.000Z')", - } - } - ] - } - - **YAML Example** - - :: - - bindings: - - members: - - user:mike@example.com - - group:admins@example.com - - domain:google.com - - serviceAccount:my-project-id@appspot.gserviceaccount.com - role: roles/resourcemanager.organizationAdmin - - members: - - user:eve@example.com - role: roles/resourcemanager.organizationViewer - condition: - title: expirable access - description: Does not grant access after Sep 2020 - expression: request.time < timestamp('2020-10-01T00:00:00.000Z') - - For a description of IAM and its features, see the `IAM - developer's - guide `__. - """ - # Create or coerce a protobuf request object. - - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = iam_policy_pb2.SetIamPolicyRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.set_iam_policy, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("resource", request.resource),)), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - def get_iam_policy( - self, - request: Optional[iam_policy_pb2.GetIamPolicyRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> policy_pb2.Policy: - r"""Gets the IAM access control policy for a function. - - Returns an empty policy if the function exists and does not have a - policy set. - - Args: - request (:class:`~.iam_policy_pb2.GetIamPolicyRequest`): - The request object. Request message for `GetIamPolicy` - method. - retry (google.api_core.retry.Retry): Designation of what errors, if - any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.policy_pb2.Policy: - Defines an Identity and Access Management (IAM) policy. - It is used to specify access control policies for Cloud - Platform resources. - A ``Policy`` is a collection of ``bindings``. A - ``binding`` binds one or more ``members`` to a single - ``role``. Members can be user accounts, service - accounts, Google groups, and domains (such as G Suite). - A ``role`` is a named list of permissions (defined by - IAM or configured by users). A ``binding`` can - optionally specify a ``condition``, which is a logic - expression that further constrains the role binding - based on attributes about the request and/or target - resource. - - **JSON Example** - - :: - - { - "bindings": [ - { - "role": "roles/resourcemanager.organizationAdmin", - "members": [ - "user:mike@example.com", - "group:admins@example.com", - "domain:google.com", - "serviceAccount:my-project-id@appspot.gserviceaccount.com" - ] - }, - { - "role": "roles/resourcemanager.organizationViewer", - "members": ["user:eve@example.com"], - "condition": { - "title": "expirable access", - "description": "Does not grant access after Sep 2020", - "expression": "request.time < - timestamp('2020-10-01T00:00:00.000Z')", - } - } - ] - } - - **YAML Example** - - :: - - bindings: - - members: - - user:mike@example.com - - group:admins@example.com - - domain:google.com - - serviceAccount:my-project-id@appspot.gserviceaccount.com - role: roles/resourcemanager.organizationAdmin - - members: - - user:eve@example.com - role: roles/resourcemanager.organizationViewer - condition: - title: expirable access - description: Does not grant access after Sep 2020 - expression: request.time < timestamp('2020-10-01T00:00:00.000Z') - - For a description of IAM and its features, see the `IAM - developer's - guide `__. - """ - # Create or coerce a protobuf request object. - - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = iam_policy_pb2.GetIamPolicyRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.get_iam_policy, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("resource", request.resource),)), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - def test_iam_permissions( - self, - request: Optional[iam_policy_pb2.TestIamPermissionsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> iam_policy_pb2.TestIamPermissionsResponse: - r"""Tests the specified IAM permissions against the IAM access control - policy for a function. - - If the function does not exist, this will return an empty set - of permissions, not a NOT_FOUND error. - - Args: - request (:class:`~.iam_policy_pb2.TestIamPermissionsRequest`): - The request object. Request message for - `TestIamPermissions` method. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.iam_policy_pb2.TestIamPermissionsResponse: - Response message for ``TestIamPermissions`` method. - """ - # Create or coerce a protobuf request object. - - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = iam_policy_pb2.TestIamPermissionsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.test_iam_permissions, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("resource", request.resource),)), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -__all__ = ( - "SubscriberClient", -) diff --git a/owl-bot-staging/v1/google/pubsub_v1/services/subscriber/pagers.py b/owl-bot-staging/v1/google/pubsub_v1/services/subscriber/pagers.py deleted file mode 100644 index f1fca5a4a..000000000 --- a/owl-bot-staging/v1/google/pubsub_v1/services/subscriber/pagers.py +++ /dev/null @@ -1,297 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.api_core import retry_async as retries_async -from typing import Any, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator, Union -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] - OptionalAsyncRetry = Union[retries_async.AsyncRetry, gapic_v1.method._MethodDefault, None] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object, None] # type: ignore - OptionalAsyncRetry = Union[retries_async.AsyncRetry, object, None] # type: ignore - -from google.pubsub_v1.types import pubsub - - -class ListSubscriptionsPager: - """A pager for iterating through ``list_subscriptions`` requests. - - This class thinly wraps an initial - :class:`google.pubsub_v1.types.ListSubscriptionsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``subscriptions`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListSubscriptions`` requests and continue to iterate - through the ``subscriptions`` field on the - corresponding responses. - - All the usual :class:`google.pubsub_v1.types.ListSubscriptionsResponse` - attributes are available on the pager. If multiple requests are made, only - the most recent response is retained, and thus used for attribute lookup. - """ - def __init__(self, - method: Callable[..., pubsub.ListSubscriptionsResponse], - request: pubsub.ListSubscriptionsRequest, - response: pubsub.ListSubscriptionsResponse, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiate the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.pubsub_v1.types.ListSubscriptionsRequest): - The initial request object. - response (google.pubsub_v1.types.ListSubscriptionsResponse): - The initial response object. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = pubsub.ListSubscriptionsRequest(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[pubsub.ListSubscriptionsResponse]: - 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[pubsub.Subscription]: - for page in self.pages: - yield from page.subscriptions - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListSubscriptionsAsyncPager: - """A pager for iterating through ``list_subscriptions`` requests. - - This class thinly wraps an initial - :class:`google.pubsub_v1.types.ListSubscriptionsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``subscriptions`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListSubscriptions`` requests and continue to iterate - through the ``subscriptions`` field on the - corresponding responses. - - All the usual :class:`google.pubsub_v1.types.ListSubscriptionsResponse` - attributes are available on the 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[pubsub.ListSubscriptionsResponse]], - request: pubsub.ListSubscriptionsRequest, - response: pubsub.ListSubscriptionsResponse, - *, - retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiates the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.pubsub_v1.types.ListSubscriptionsRequest): - The initial request object. - response (google.pubsub_v1.types.ListSubscriptionsResponse): - The initial response object. - retry (google.api_core.retry.AsyncRetry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = pubsub.ListSubscriptionsRequest(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[pubsub.ListSubscriptionsResponse]: - 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[pubsub.Subscription]: - async def async_generator(): - async for page in self.pages: - for response in page.subscriptions: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListSnapshotsPager: - """A pager for iterating through ``list_snapshots`` requests. - - This class thinly wraps an initial - :class:`google.pubsub_v1.types.ListSnapshotsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``snapshots`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListSnapshots`` requests and continue to iterate - through the ``snapshots`` field on the - corresponding responses. - - All the usual :class:`google.pubsub_v1.types.ListSnapshotsResponse` - attributes are available on the pager. If multiple requests are made, only - the most recent response is retained, and thus used for attribute lookup. - """ - def __init__(self, - method: Callable[..., pubsub.ListSnapshotsResponse], - request: pubsub.ListSnapshotsRequest, - response: pubsub.ListSnapshotsResponse, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiate the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.pubsub_v1.types.ListSnapshotsRequest): - The initial request object. - response (google.pubsub_v1.types.ListSnapshotsResponse): - The initial response object. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = pubsub.ListSnapshotsRequest(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[pubsub.ListSnapshotsResponse]: - 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[pubsub.Snapshot]: - for page in self.pages: - yield from page.snapshots - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListSnapshotsAsyncPager: - """A pager for iterating through ``list_snapshots`` requests. - - This class thinly wraps an initial - :class:`google.pubsub_v1.types.ListSnapshotsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``snapshots`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListSnapshots`` requests and continue to iterate - through the ``snapshots`` field on the - corresponding responses. - - All the usual :class:`google.pubsub_v1.types.ListSnapshotsResponse` - attributes are available on the 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[pubsub.ListSnapshotsResponse]], - request: pubsub.ListSnapshotsRequest, - response: pubsub.ListSnapshotsResponse, - *, - retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiates the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.pubsub_v1.types.ListSnapshotsRequest): - The initial request object. - response (google.pubsub_v1.types.ListSnapshotsResponse): - The initial response object. - retry (google.api_core.retry.AsyncRetry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = pubsub.ListSnapshotsRequest(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[pubsub.ListSnapshotsResponse]: - 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[pubsub.Snapshot]: - async def async_generator(): - async for page in self.pages: - for response in page.snapshots: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) diff --git a/owl-bot-staging/v1/google/pubsub_v1/services/subscriber/transports/__init__.py b/owl-bot-staging/v1/google/pubsub_v1/services/subscriber/transports/__init__.py deleted file mode 100644 index 1aee718bf..000000000 --- a/owl-bot-staging/v1/google/pubsub_v1/services/subscriber/transports/__init__.py +++ /dev/null @@ -1,38 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -from typing import Dict, Type - -from .base import SubscriberTransport -from .grpc import SubscriberGrpcTransport -from .grpc_asyncio import SubscriberGrpcAsyncIOTransport -from .rest import SubscriberRestTransport -from .rest import SubscriberRestInterceptor - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[SubscriberTransport]] -_transport_registry['grpc'] = SubscriberGrpcTransport -_transport_registry['grpc_asyncio'] = SubscriberGrpcAsyncIOTransport -_transport_registry['rest'] = SubscriberRestTransport - -__all__ = ( - 'SubscriberTransport', - 'SubscriberGrpcTransport', - 'SubscriberGrpcAsyncIOTransport', - 'SubscriberRestTransport', - 'SubscriberRestInterceptor', -) diff --git a/owl-bot-staging/v1/google/pubsub_v1/services/subscriber/transports/base.py b/owl-bot-staging/v1/google/pubsub_v1/services/subscriber/transports/base.py deleted file mode 100644 index 2139513c2..000000000 --- a/owl-bot-staging/v1/google/pubsub_v1/services/subscriber/transports/base.py +++ /dev/null @@ -1,561 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import abc -from typing import Awaitable, Callable, Dict, Optional, Sequence, Union - -from google.pubsub_v1 import gapic_version as package_version - -import google.auth # type: ignore -import google.api_core -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.iam.v1 import iam_policy_pb2 # type: ignore -from google.iam.v1 import policy_pb2 # type: ignore -from google.protobuf import empty_pb2 # type: ignore -from google.pubsub_v1.types import pubsub - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -class SubscriberTransport(abc.ABC): - """Abstract transport class for Subscriber.""" - - AUTH_SCOPES = ( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/pubsub', - ) - - DEFAULT_HOST: str = 'pubsub.googleapis.com' - def __init__( - self, *, - host: str = DEFAULT_HOST, - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - **kwargs, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to (default: 'pubsub.googleapis.com'). - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A list of scopes. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - """ - - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - - # Save the scopes. - self._scopes = scopes - if not hasattr(self, "_ignore_credentials"): - self._ignore_credentials: bool = False - - # If no credentials are provided, then determine the appropriate - # defaults. - if credentials and credentials_file: - raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") - - if credentials_file is not None: - credentials, _ = google.auth.load_credentials_from_file( - credentials_file, - **scopes_kwargs, - quota_project_id=quota_project_id - ) - elif credentials is None and not self._ignore_credentials: - credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) - # Don't apply audience if the credentials file passed from user. - if hasattr(credentials, "with_gdch_audience"): - credentials = credentials.with_gdch_audience(api_audience if api_audience else host) - - # If the credentials are service account credentials, then always try to use self signed JWT. - if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): - credentials = credentials.with_always_use_jwt_access(True) - - # Save the credentials. - self._credentials = credentials - - # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ':' not in host: - host += ':443' - self._host = host - - @property - def host(self): - return self._host - - def _prep_wrapped_messages(self, client_info): - # Precompute the wrapped methods. - self._wrapped_methods = { - self.create_subscription: gapic_v1.method.wrap_method( - self.create_subscription, - default_retry=retries.Retry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.Aborted, - core_exceptions.ServiceUnavailable, - core_exceptions.Unknown, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.get_subscription: gapic_v1.method.wrap_method( - self.get_subscription, - default_retry=retries.Retry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.Aborted, - core_exceptions.ServiceUnavailable, - core_exceptions.Unknown, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.update_subscription: gapic_v1.method.wrap_method( - self.update_subscription, - default_retry=retries.Retry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.list_subscriptions: gapic_v1.method.wrap_method( - self.list_subscriptions, - default_retry=retries.Retry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.Aborted, - core_exceptions.ServiceUnavailable, - core_exceptions.Unknown, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.delete_subscription: gapic_v1.method.wrap_method( - self.delete_subscription, - default_retry=retries.Retry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.modify_ack_deadline: gapic_v1.method.wrap_method( - self.modify_ack_deadline, - default_retry=retries.Retry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.acknowledge: gapic_v1.method.wrap_method( - self.acknowledge, - default_retry=retries.Retry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.pull: gapic_v1.method.wrap_method( - self.pull, - default_retry=retries.Retry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.Aborted, - core_exceptions.InternalServerError, - core_exceptions.ServiceUnavailable, - core_exceptions.Unknown, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.streaming_pull: gapic_v1.method.wrap_method( - self.streaming_pull, - default_retry=retries.Retry( - initial=0.1, - maximum=60.0, - multiplier=4, - predicate=retries.if_exception_type( - core_exceptions.Aborted, - core_exceptions.DeadlineExceeded, - core_exceptions.InternalServerError, - core_exceptions.ResourceExhausted, - core_exceptions.ServiceUnavailable, - ), - deadline=900.0, - ), - default_timeout=900.0, - client_info=client_info, - ), - self.modify_push_config: gapic_v1.method.wrap_method( - self.modify_push_config, - default_retry=retries.Retry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.get_snapshot: gapic_v1.method.wrap_method( - self.get_snapshot, - default_retry=retries.Retry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.Aborted, - core_exceptions.ServiceUnavailable, - core_exceptions.Unknown, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.list_snapshots: gapic_v1.method.wrap_method( - self.list_snapshots, - default_retry=retries.Retry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.Aborted, - core_exceptions.ServiceUnavailable, - core_exceptions.Unknown, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.create_snapshot: gapic_v1.method.wrap_method( - self.create_snapshot, - default_retry=retries.Retry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.update_snapshot: gapic_v1.method.wrap_method( - self.update_snapshot, - default_retry=retries.Retry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.delete_snapshot: gapic_v1.method.wrap_method( - self.delete_snapshot, - default_retry=retries.Retry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.seek: gapic_v1.method.wrap_method( - self.seek, - default_retry=retries.Retry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.Aborted, - core_exceptions.ServiceUnavailable, - core_exceptions.Unknown, - ), - deadline=60.0, - ), - default_timeout=60.0, - 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_subscription(self) -> Callable[ - [pubsub.Subscription], - Union[ - pubsub.Subscription, - Awaitable[pubsub.Subscription] - ]]: - raise NotImplementedError() - - @property - def get_subscription(self) -> Callable[ - [pubsub.GetSubscriptionRequest], - Union[ - pubsub.Subscription, - Awaitable[pubsub.Subscription] - ]]: - raise NotImplementedError() - - @property - def update_subscription(self) -> Callable[ - [pubsub.UpdateSubscriptionRequest], - Union[ - pubsub.Subscription, - Awaitable[pubsub.Subscription] - ]]: - raise NotImplementedError() - - @property - def list_subscriptions(self) -> Callable[ - [pubsub.ListSubscriptionsRequest], - Union[ - pubsub.ListSubscriptionsResponse, - Awaitable[pubsub.ListSubscriptionsResponse] - ]]: - raise NotImplementedError() - - @property - def delete_subscription(self) -> Callable[ - [pubsub.DeleteSubscriptionRequest], - Union[ - empty_pb2.Empty, - Awaitable[empty_pb2.Empty] - ]]: - raise NotImplementedError() - - @property - def modify_ack_deadline(self) -> Callable[ - [pubsub.ModifyAckDeadlineRequest], - Union[ - empty_pb2.Empty, - Awaitable[empty_pb2.Empty] - ]]: - raise NotImplementedError() - - @property - def acknowledge(self) -> Callable[ - [pubsub.AcknowledgeRequest], - Union[ - empty_pb2.Empty, - Awaitable[empty_pb2.Empty] - ]]: - raise NotImplementedError() - - @property - def pull(self) -> Callable[ - [pubsub.PullRequest], - Union[ - pubsub.PullResponse, - Awaitable[pubsub.PullResponse] - ]]: - raise NotImplementedError() - - @property - def streaming_pull(self) -> Callable[ - [pubsub.StreamingPullRequest], - Union[ - pubsub.StreamingPullResponse, - Awaitable[pubsub.StreamingPullResponse] - ]]: - raise NotImplementedError() - - @property - def modify_push_config(self) -> Callable[ - [pubsub.ModifyPushConfigRequest], - Union[ - empty_pb2.Empty, - Awaitable[empty_pb2.Empty] - ]]: - raise NotImplementedError() - - @property - def get_snapshot(self) -> Callable[ - [pubsub.GetSnapshotRequest], - Union[ - pubsub.Snapshot, - Awaitable[pubsub.Snapshot] - ]]: - raise NotImplementedError() - - @property - def list_snapshots(self) -> Callable[ - [pubsub.ListSnapshotsRequest], - Union[ - pubsub.ListSnapshotsResponse, - Awaitable[pubsub.ListSnapshotsResponse] - ]]: - raise NotImplementedError() - - @property - def create_snapshot(self) -> Callable[ - [pubsub.CreateSnapshotRequest], - Union[ - pubsub.Snapshot, - Awaitable[pubsub.Snapshot] - ]]: - raise NotImplementedError() - - @property - def update_snapshot(self) -> Callable[ - [pubsub.UpdateSnapshotRequest], - Union[ - pubsub.Snapshot, - Awaitable[pubsub.Snapshot] - ]]: - raise NotImplementedError() - - @property - def delete_snapshot(self) -> Callable[ - [pubsub.DeleteSnapshotRequest], - Union[ - empty_pb2.Empty, - Awaitable[empty_pb2.Empty] - ]]: - raise NotImplementedError() - - @property - def seek(self) -> Callable[ - [pubsub.SeekRequest], - Union[ - pubsub.SeekResponse, - Awaitable[pubsub.SeekResponse] - ]]: - 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 kind(self) -> str: - raise NotImplementedError() - - -__all__ = ( - 'SubscriberTransport', -) diff --git a/owl-bot-staging/v1/google/pubsub_v1/services/subscriber/transports/grpc.py b/owl-bot-staging/v1/google/pubsub_v1/services/subscriber/transports/grpc.py deleted file mode 100644 index 3ab35f87e..000000000 --- a/owl-bot-staging/v1/google/pubsub_v1/services/subscriber/transports/grpc.py +++ /dev/null @@ -1,839 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import grpc_helpers -from google.api_core import gapic_v1 -import google.auth # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore - -from google.iam.v1 import iam_policy_pb2 # type: ignore -from google.iam.v1 import policy_pb2 # type: ignore -from google.protobuf import empty_pb2 # type: ignore -from google.pubsub_v1.types import pubsub -from .base import SubscriberTransport, DEFAULT_CLIENT_INFO - - -class SubscriberGrpcTransport(SubscriberTransport): - """gRPC backend transport for Subscriber. - - The service that an application uses to manipulate subscriptions and - to consume messages from a subscription via the ``Pull`` method or - by establishing a bi-directional stream using the ``StreamingPull`` - method. - - This 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 = 'pubsub.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to (default: 'pubsub.googleapis.com'). - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if a ``channel`` instance is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if a ``channel`` instance is provided. - channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): - A ``Channel`` instance through which to make calls, or a Callable - that constructs and returns one. If set to None, ``self.create_channel`` - is used to create the channel. If a Callable is given, it will be called - with the same arguments as used in ``self.create_channel``. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if a ``channel`` instance is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if a ``channel`` instance or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if isinstance(channel, grpc.Channel): - # Ignore credentials if a channel was passed. - credentials = None - self._ignore_credentials = True - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - # initialize with the provided callable or the default channel - channel_init = channel or type(self).create_channel - self._grpc_channel = channel_init( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @classmethod - def create_channel(cls, - host: str = 'pubsub.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> grpc.Channel: - """Create and return a gRPC channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - grpc.Channel: A gRPC channel object. - - Raises: - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - - return grpc_helpers.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - @property - def grpc_channel(self) -> grpc.Channel: - """Return the channel designed to connect to this service. - """ - return self._grpc_channel - - @property - def create_subscription(self) -> Callable[ - [pubsub.Subscription], - pubsub.Subscription]: - r"""Return a callable for the create subscription method over gRPC. - - Creates a subscription to a given topic. See the [resource name - rules] - (https://cloud.google.com/pubsub/docs/pubsub-basics#resource_names). - If the subscription already exists, returns ``ALREADY_EXISTS``. - If the corresponding topic doesn't exist, returns ``NOT_FOUND``. - - If the name is not provided in the request, the server will - assign a random name for this subscription on the same project - as the topic, conforming to the [resource name format] - (https://cloud.google.com/pubsub/docs/pubsub-basics#resource_names). - The generated name is populated in the returned Subscription - object. Note that for REST API requests, you must specify a name - in the request. - - Returns: - Callable[[~.Subscription], - ~.Subscription]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_subscription' not in self._stubs: - self._stubs['create_subscription'] = self.grpc_channel.unary_unary( - '/google.pubsub.v1.Subscriber/CreateSubscription', - request_serializer=pubsub.Subscription.serialize, - response_deserializer=pubsub.Subscription.deserialize, - ) - return self._stubs['create_subscription'] - - @property - def get_subscription(self) -> Callable[ - [pubsub.GetSubscriptionRequest], - pubsub.Subscription]: - r"""Return a callable for the get subscription method over gRPC. - - Gets the configuration details of a subscription. - - Returns: - Callable[[~.GetSubscriptionRequest], - ~.Subscription]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'get_subscription' not in self._stubs: - self._stubs['get_subscription'] = self.grpc_channel.unary_unary( - '/google.pubsub.v1.Subscriber/GetSubscription', - request_serializer=pubsub.GetSubscriptionRequest.serialize, - response_deserializer=pubsub.Subscription.deserialize, - ) - return self._stubs['get_subscription'] - - @property - def update_subscription(self) -> Callable[ - [pubsub.UpdateSubscriptionRequest], - pubsub.Subscription]: - r"""Return a callable for the update subscription method over gRPC. - - Updates an existing subscription by updating the - fields specified in the update mask. Note that certain - properties of a subscription, such as its topic, are not - modifiable. - - Returns: - Callable[[~.UpdateSubscriptionRequest], - ~.Subscription]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_subscription' not in self._stubs: - self._stubs['update_subscription'] = self.grpc_channel.unary_unary( - '/google.pubsub.v1.Subscriber/UpdateSubscription', - request_serializer=pubsub.UpdateSubscriptionRequest.serialize, - response_deserializer=pubsub.Subscription.deserialize, - ) - return self._stubs['update_subscription'] - - @property - def list_subscriptions(self) -> Callable[ - [pubsub.ListSubscriptionsRequest], - pubsub.ListSubscriptionsResponse]: - r"""Return a callable for the list subscriptions method over gRPC. - - Lists matching subscriptions. - - Returns: - Callable[[~.ListSubscriptionsRequest], - ~.ListSubscriptionsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'list_subscriptions' not in self._stubs: - self._stubs['list_subscriptions'] = self.grpc_channel.unary_unary( - '/google.pubsub.v1.Subscriber/ListSubscriptions', - request_serializer=pubsub.ListSubscriptionsRequest.serialize, - response_deserializer=pubsub.ListSubscriptionsResponse.deserialize, - ) - return self._stubs['list_subscriptions'] - - @property - def delete_subscription(self) -> Callable[ - [pubsub.DeleteSubscriptionRequest], - empty_pb2.Empty]: - r"""Return a callable for the delete subscription method over gRPC. - - Deletes an existing subscription. All messages retained in the - subscription are immediately dropped. Calls to ``Pull`` after - deletion will return ``NOT_FOUND``. After a subscription is - deleted, a new one may be created with the same name, but the - new one has no association with the old subscription or its - topic unless the same topic is specified. - - Returns: - Callable[[~.DeleteSubscriptionRequest], - ~.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_subscription' not in self._stubs: - self._stubs['delete_subscription'] = self.grpc_channel.unary_unary( - '/google.pubsub.v1.Subscriber/DeleteSubscription', - request_serializer=pubsub.DeleteSubscriptionRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_subscription'] - - @property - def modify_ack_deadline(self) -> Callable[ - [pubsub.ModifyAckDeadlineRequest], - empty_pb2.Empty]: - r"""Return a callable for the modify ack deadline method over gRPC. - - Modifies the ack deadline for a specific message. This method is - useful to indicate that more time is needed to process a message - by the subscriber, or to make the message available for - redelivery if the processing was interrupted. Note that this - does not modify the subscription-level ``ackDeadlineSeconds`` - used for subsequent messages. - - Returns: - Callable[[~.ModifyAckDeadlineRequest], - ~.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 'modify_ack_deadline' not in self._stubs: - self._stubs['modify_ack_deadline'] = self.grpc_channel.unary_unary( - '/google.pubsub.v1.Subscriber/ModifyAckDeadline', - request_serializer=pubsub.ModifyAckDeadlineRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['modify_ack_deadline'] - - @property - def acknowledge(self) -> Callable[ - [pubsub.AcknowledgeRequest], - empty_pb2.Empty]: - r"""Return a callable for the acknowledge method over gRPC. - - Acknowledges the messages associated with the ``ack_ids`` in the - ``AcknowledgeRequest``. The Pub/Sub system can remove the - relevant messages from the subscription. - - Acknowledging a message whose ack deadline has expired may - succeed, but such a message may be redelivered later. - Acknowledging a message more than once will not result in an - error. - - Returns: - Callable[[~.AcknowledgeRequest], - ~.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 'acknowledge' not in self._stubs: - self._stubs['acknowledge'] = self.grpc_channel.unary_unary( - '/google.pubsub.v1.Subscriber/Acknowledge', - request_serializer=pubsub.AcknowledgeRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['acknowledge'] - - @property - def pull(self) -> Callable[ - [pubsub.PullRequest], - pubsub.PullResponse]: - r"""Return a callable for the pull method over gRPC. - - Pulls messages from the server. - - Returns: - Callable[[~.PullRequest], - ~.PullResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'pull' not in self._stubs: - self._stubs['pull'] = self.grpc_channel.unary_unary( - '/google.pubsub.v1.Subscriber/Pull', - request_serializer=pubsub.PullRequest.serialize, - response_deserializer=pubsub.PullResponse.deserialize, - ) - return self._stubs['pull'] - - @property - def streaming_pull(self) -> Callable[ - [pubsub.StreamingPullRequest], - pubsub.StreamingPullResponse]: - r"""Return a callable for the streaming pull method over gRPC. - - Establishes a stream with the server, which sends messages down - to the client. The client streams acknowledgements and ack - deadline modifications back to the server. The server will close - the stream and return the status on any error. The server may - close the stream with status ``UNAVAILABLE`` to reassign - server-side resources, in which case, the client should - re-establish the stream. Flow control can be achieved by - configuring the underlying RPC channel. - - Returns: - Callable[[~.StreamingPullRequest], - ~.StreamingPullResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'streaming_pull' not in self._stubs: - self._stubs['streaming_pull'] = self.grpc_channel.stream_stream( - '/google.pubsub.v1.Subscriber/StreamingPull', - request_serializer=pubsub.StreamingPullRequest.serialize, - response_deserializer=pubsub.StreamingPullResponse.deserialize, - ) - return self._stubs['streaming_pull'] - - @property - def modify_push_config(self) -> Callable[ - [pubsub.ModifyPushConfigRequest], - empty_pb2.Empty]: - r"""Return a callable for the modify push config method over gRPC. - - Modifies the ``PushConfig`` for a specified subscription. - - This may be used to change a push subscription to a pull one - (signified by an empty ``PushConfig``) or vice versa, or change - the endpoint URL and other attributes of a push subscription. - Messages will accumulate for delivery continuously through the - call regardless of changes to the ``PushConfig``. - - Returns: - Callable[[~.ModifyPushConfigRequest], - ~.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 'modify_push_config' not in self._stubs: - self._stubs['modify_push_config'] = self.grpc_channel.unary_unary( - '/google.pubsub.v1.Subscriber/ModifyPushConfig', - request_serializer=pubsub.ModifyPushConfigRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['modify_push_config'] - - @property - def get_snapshot(self) -> Callable[ - [pubsub.GetSnapshotRequest], - pubsub.Snapshot]: - r"""Return a callable for the get snapshot method over gRPC. - - Gets the configuration details of a snapshot. Snapshots are used - in - `Seek `__ - operations, which allow you to manage message acknowledgments in - bulk. That is, you can set the acknowledgment state of messages - in an existing subscription to the state captured by a snapshot. - - Returns: - Callable[[~.GetSnapshotRequest], - ~.Snapshot]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'get_snapshot' not in self._stubs: - self._stubs['get_snapshot'] = self.grpc_channel.unary_unary( - '/google.pubsub.v1.Subscriber/GetSnapshot', - request_serializer=pubsub.GetSnapshotRequest.serialize, - response_deserializer=pubsub.Snapshot.deserialize, - ) - return self._stubs['get_snapshot'] - - @property - def list_snapshots(self) -> Callable[ - [pubsub.ListSnapshotsRequest], - pubsub.ListSnapshotsResponse]: - r"""Return a callable for the list snapshots method over gRPC. - - Lists the existing snapshots. Snapshots are used in - `Seek `__ - operations, which allow you to manage message acknowledgments in - bulk. That is, you can set the acknowledgment state of messages - in an existing subscription to the state captured by a snapshot. - - Returns: - Callable[[~.ListSnapshotsRequest], - ~.ListSnapshotsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'list_snapshots' not in self._stubs: - self._stubs['list_snapshots'] = self.grpc_channel.unary_unary( - '/google.pubsub.v1.Subscriber/ListSnapshots', - request_serializer=pubsub.ListSnapshotsRequest.serialize, - response_deserializer=pubsub.ListSnapshotsResponse.deserialize, - ) - return self._stubs['list_snapshots'] - - @property - def create_snapshot(self) -> Callable[ - [pubsub.CreateSnapshotRequest], - pubsub.Snapshot]: - r"""Return a callable for the create snapshot method over gRPC. - - Creates a snapshot from the requested subscription. Snapshots - are used in - `Seek `__ - operations, which allow you to manage message acknowledgments in - bulk. That is, you can set the acknowledgment state of messages - in an existing subscription to the state captured by a snapshot. - If the snapshot already exists, returns ``ALREADY_EXISTS``. If - the requested subscription doesn't exist, returns ``NOT_FOUND``. - If the backlog in the subscription is too old -- and the - resulting snapshot would expire in less than 1 hour -- then - ``FAILED_PRECONDITION`` is returned. See also the - ``Snapshot.expire_time`` field. If the name is not provided in - the request, the server will assign a random name for this - snapshot on the same project as the subscription, conforming to - the [resource name format] - (https://cloud.google.com/pubsub/docs/pubsub-basics#resource_names). - The generated name is populated in the returned Snapshot object. - Note that for REST API requests, you must specify a name in the - request. - - Returns: - Callable[[~.CreateSnapshotRequest], - ~.Snapshot]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_snapshot' not in self._stubs: - self._stubs['create_snapshot'] = self.grpc_channel.unary_unary( - '/google.pubsub.v1.Subscriber/CreateSnapshot', - request_serializer=pubsub.CreateSnapshotRequest.serialize, - response_deserializer=pubsub.Snapshot.deserialize, - ) - return self._stubs['create_snapshot'] - - @property - def update_snapshot(self) -> Callable[ - [pubsub.UpdateSnapshotRequest], - pubsub.Snapshot]: - r"""Return a callable for the update snapshot method over gRPC. - - Updates an existing snapshot by updating the fields specified in - the update mask. Snapshots are used in - `Seek `__ - operations, which allow you to manage message acknowledgments in - bulk. That is, you can set the acknowledgment state of messages - in an existing subscription to the state captured by a snapshot. - - Returns: - Callable[[~.UpdateSnapshotRequest], - ~.Snapshot]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_snapshot' not in self._stubs: - self._stubs['update_snapshot'] = self.grpc_channel.unary_unary( - '/google.pubsub.v1.Subscriber/UpdateSnapshot', - request_serializer=pubsub.UpdateSnapshotRequest.serialize, - response_deserializer=pubsub.Snapshot.deserialize, - ) - return self._stubs['update_snapshot'] - - @property - def delete_snapshot(self) -> Callable[ - [pubsub.DeleteSnapshotRequest], - empty_pb2.Empty]: - r"""Return a callable for the delete snapshot method over gRPC. - - Removes an existing snapshot. Snapshots are used in [Seek] - (https://cloud.google.com/pubsub/docs/replay-overview) - operations, which allow you to manage message acknowledgments in - bulk. That is, you can set the acknowledgment state of messages - in an existing subscription to the state captured by a snapshot. - When the snapshot is deleted, all messages retained in the - snapshot are immediately dropped. After a snapshot is deleted, a - new one may be created with the same name, but the new one has - no association with the old snapshot or its subscription, unless - the same subscription is specified. - - Returns: - Callable[[~.DeleteSnapshotRequest], - ~.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_snapshot' not in self._stubs: - self._stubs['delete_snapshot'] = self.grpc_channel.unary_unary( - '/google.pubsub.v1.Subscriber/DeleteSnapshot', - request_serializer=pubsub.DeleteSnapshotRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_snapshot'] - - @property - def seek(self) -> Callable[ - [pubsub.SeekRequest], - pubsub.SeekResponse]: - r"""Return a callable for the seek method over gRPC. - - Seeks an existing subscription to a point in time or to a given - snapshot, whichever is provided in the request. Snapshots are - used in [Seek] - (https://cloud.google.com/pubsub/docs/replay-overview) - operations, which allow you to manage message acknowledgments in - bulk. That is, you can set the acknowledgment state of messages - in an existing subscription to the state captured by a snapshot. - Note that both the subscription and the snapshot must be on the - same topic. - - Returns: - Callable[[~.SeekRequest], - ~.SeekResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'seek' not in self._stubs: - self._stubs['seek'] = self.grpc_channel.unary_unary( - '/google.pubsub.v1.Subscriber/Seek', - request_serializer=pubsub.SeekRequest.serialize, - response_deserializer=pubsub.SeekResponse.deserialize, - ) - return self._stubs['seek'] - - @property - def set_iam_policy( - self, - ) -> Callable[[iam_policy_pb2.SetIamPolicyRequest], policy_pb2.Policy]: - r"""Return a callable for the set iam policy method over gRPC. - Sets the IAM access control policy on the specified - function. Replaces any existing policy. - Returns: - Callable[[~.SetIamPolicyRequest], - ~.Policy]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "set_iam_policy" not in self._stubs: - self._stubs["set_iam_policy"] = self.grpc_channel.unary_unary( - "/google.iam.v1.IAMPolicy/SetIamPolicy", - request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString, - response_deserializer=policy_pb2.Policy.FromString, - ) - return self._stubs["set_iam_policy"] - - @property - def get_iam_policy( - self, - ) -> Callable[[iam_policy_pb2.GetIamPolicyRequest], policy_pb2.Policy]: - r"""Return a callable for the get iam policy method over gRPC. - Gets the IAM access control policy for a function. - Returns an empty policy if the function exists and does - not have a policy set. - Returns: - Callable[[~.GetIamPolicyRequest], - ~.Policy]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "get_iam_policy" not in self._stubs: - self._stubs["get_iam_policy"] = self.grpc_channel.unary_unary( - "/google.iam.v1.IAMPolicy/GetIamPolicy", - request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, - response_deserializer=policy_pb2.Policy.FromString, - ) - return self._stubs["get_iam_policy"] - - @property - def test_iam_permissions( - self, - ) -> Callable[ - [iam_policy_pb2.TestIamPermissionsRequest], iam_policy_pb2.TestIamPermissionsResponse - ]: - r"""Return a callable for the test iam permissions method over gRPC. - Tests the specified permissions against the IAM access control - policy for a function. If the function does not exist, this will - return an empty set of permissions, not a NOT_FOUND error. - Returns: - Callable[[~.TestIamPermissionsRequest], - ~.TestIamPermissionsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "test_iam_permissions" not in self._stubs: - self._stubs["test_iam_permissions"] = self.grpc_channel.unary_unary( - "/google.iam.v1.IAMPolicy/TestIamPermissions", - request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString, - response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString, - ) - return self._stubs["test_iam_permissions"] - - def close(self): - self.grpc_channel.close() - - @property - def kind(self) -> str: - return "grpc" - - -__all__ = ( - 'SubscriberGrpcTransport', -) diff --git a/owl-bot-staging/v1/google/pubsub_v1/services/subscriber/transports/grpc_asyncio.py b/owl-bot-staging/v1/google/pubsub_v1/services/subscriber/transports/grpc_asyncio.py deleted file mode 100644 index 30078369d..000000000 --- a/owl-bot-staging/v1/google/pubsub_v1/services/subscriber/transports/grpc_asyncio.py +++ /dev/null @@ -1,1088 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import 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 - -import grpc # type: ignore -from grpc.experimental import aio # type: ignore - -from google.iam.v1 import iam_policy_pb2 # type: ignore -from google.iam.v1 import policy_pb2 # type: ignore -from google.protobuf import empty_pb2 # type: ignore -from google.pubsub_v1.types import pubsub -from .base import SubscriberTransport, DEFAULT_CLIENT_INFO -from .grpc import SubscriberGrpcTransport - - -class SubscriberGrpcAsyncIOTransport(SubscriberTransport): - """gRPC AsyncIO backend transport for Subscriber. - - The service that an application uses to manipulate subscriptions and - to consume messages from a subscription via the ``Pull`` method or - by establishing a bi-directional stream using the ``StreamingPull`` - method. - - This 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 = 'pubsub.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> aio.Channel: - """Create and return a gRPC AsyncIO channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - aio.Channel: A gRPC AsyncIO channel object. - """ - - return grpc_helpers_async.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - def __init__(self, *, - host: str = 'pubsub.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: Optional[Union[aio.Channel, Callable[..., aio.Channel]]] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to (default: 'pubsub.googleapis.com'). - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if a ``channel`` instance is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - channel (Optional[Union[aio.Channel, Callable[..., aio.Channel]]]): - A ``Channel`` instance through which to make calls, or a Callable - that constructs and returns one. If set to None, ``self.create_channel`` - is used to create the channel. If a Callable is given, it will be called - with the same arguments as used in ``self.create_channel``. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if a ``channel`` instance is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if a ``channel`` instance or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if isinstance(channel, aio.Channel): - # Ignore credentials if a channel was passed. - credentials = None - self._ignore_credentials = True - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - # initialize with the provided callable or the default channel - channel_init = channel or type(self).create_channel - self._grpc_channel = channel_init( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._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_subscription(self) -> Callable[ - [pubsub.Subscription], - Awaitable[pubsub.Subscription]]: - r"""Return a callable for the create subscription method over gRPC. - - Creates a subscription to a given topic. See the [resource name - rules] - (https://cloud.google.com/pubsub/docs/pubsub-basics#resource_names). - If the subscription already exists, returns ``ALREADY_EXISTS``. - If the corresponding topic doesn't exist, returns ``NOT_FOUND``. - - If the name is not provided in the request, the server will - assign a random name for this subscription on the same project - as the topic, conforming to the [resource name format] - (https://cloud.google.com/pubsub/docs/pubsub-basics#resource_names). - The generated name is populated in the returned Subscription - object. Note that for REST API requests, you must specify a name - in the request. - - Returns: - Callable[[~.Subscription], - Awaitable[~.Subscription]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_subscription' not in self._stubs: - self._stubs['create_subscription'] = self.grpc_channel.unary_unary( - '/google.pubsub.v1.Subscriber/CreateSubscription', - request_serializer=pubsub.Subscription.serialize, - response_deserializer=pubsub.Subscription.deserialize, - ) - return self._stubs['create_subscription'] - - @property - def get_subscription(self) -> Callable[ - [pubsub.GetSubscriptionRequest], - Awaitable[pubsub.Subscription]]: - r"""Return a callable for the get subscription method over gRPC. - - Gets the configuration details of a subscription. - - Returns: - Callable[[~.GetSubscriptionRequest], - Awaitable[~.Subscription]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'get_subscription' not in self._stubs: - self._stubs['get_subscription'] = self.grpc_channel.unary_unary( - '/google.pubsub.v1.Subscriber/GetSubscription', - request_serializer=pubsub.GetSubscriptionRequest.serialize, - response_deserializer=pubsub.Subscription.deserialize, - ) - return self._stubs['get_subscription'] - - @property - def update_subscription(self) -> Callable[ - [pubsub.UpdateSubscriptionRequest], - Awaitable[pubsub.Subscription]]: - r"""Return a callable for the update subscription method over gRPC. - - Updates an existing subscription by updating the - fields specified in the update mask. Note that certain - properties of a subscription, such as its topic, are not - modifiable. - - Returns: - Callable[[~.UpdateSubscriptionRequest], - Awaitable[~.Subscription]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_subscription' not in self._stubs: - self._stubs['update_subscription'] = self.grpc_channel.unary_unary( - '/google.pubsub.v1.Subscriber/UpdateSubscription', - request_serializer=pubsub.UpdateSubscriptionRequest.serialize, - response_deserializer=pubsub.Subscription.deserialize, - ) - return self._stubs['update_subscription'] - - @property - def list_subscriptions(self) -> Callable[ - [pubsub.ListSubscriptionsRequest], - Awaitable[pubsub.ListSubscriptionsResponse]]: - r"""Return a callable for the list subscriptions method over gRPC. - - Lists matching subscriptions. - - Returns: - Callable[[~.ListSubscriptionsRequest], - Awaitable[~.ListSubscriptionsResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'list_subscriptions' not in self._stubs: - self._stubs['list_subscriptions'] = self.grpc_channel.unary_unary( - '/google.pubsub.v1.Subscriber/ListSubscriptions', - request_serializer=pubsub.ListSubscriptionsRequest.serialize, - response_deserializer=pubsub.ListSubscriptionsResponse.deserialize, - ) - return self._stubs['list_subscriptions'] - - @property - def delete_subscription(self) -> Callable[ - [pubsub.DeleteSubscriptionRequest], - Awaitable[empty_pb2.Empty]]: - r"""Return a callable for the delete subscription method over gRPC. - - Deletes an existing subscription. All messages retained in the - subscription are immediately dropped. Calls to ``Pull`` after - deletion will return ``NOT_FOUND``. After a subscription is - deleted, a new one may be created with the same name, but the - new one has no association with the old subscription or its - topic unless the same topic is specified. - - Returns: - Callable[[~.DeleteSubscriptionRequest], - 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_subscription' not in self._stubs: - self._stubs['delete_subscription'] = self.grpc_channel.unary_unary( - '/google.pubsub.v1.Subscriber/DeleteSubscription', - request_serializer=pubsub.DeleteSubscriptionRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_subscription'] - - @property - def modify_ack_deadline(self) -> Callable[ - [pubsub.ModifyAckDeadlineRequest], - Awaitable[empty_pb2.Empty]]: - r"""Return a callable for the modify ack deadline method over gRPC. - - Modifies the ack deadline for a specific message. This method is - useful to indicate that more time is needed to process a message - by the subscriber, or to make the message available for - redelivery if the processing was interrupted. Note that this - does not modify the subscription-level ``ackDeadlineSeconds`` - used for subsequent messages. - - Returns: - Callable[[~.ModifyAckDeadlineRequest], - 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 'modify_ack_deadline' not in self._stubs: - self._stubs['modify_ack_deadline'] = self.grpc_channel.unary_unary( - '/google.pubsub.v1.Subscriber/ModifyAckDeadline', - request_serializer=pubsub.ModifyAckDeadlineRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['modify_ack_deadline'] - - @property - def acknowledge(self) -> Callable[ - [pubsub.AcknowledgeRequest], - Awaitable[empty_pb2.Empty]]: - r"""Return a callable for the acknowledge method over gRPC. - - Acknowledges the messages associated with the ``ack_ids`` in the - ``AcknowledgeRequest``. The Pub/Sub system can remove the - relevant messages from the subscription. - - Acknowledging a message whose ack deadline has expired may - succeed, but such a message may be redelivered later. - Acknowledging a message more than once will not result in an - error. - - Returns: - Callable[[~.AcknowledgeRequest], - 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 'acknowledge' not in self._stubs: - self._stubs['acknowledge'] = self.grpc_channel.unary_unary( - '/google.pubsub.v1.Subscriber/Acknowledge', - request_serializer=pubsub.AcknowledgeRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['acknowledge'] - - @property - def pull(self) -> Callable[ - [pubsub.PullRequest], - Awaitable[pubsub.PullResponse]]: - r"""Return a callable for the pull method over gRPC. - - Pulls messages from the server. - - Returns: - Callable[[~.PullRequest], - Awaitable[~.PullResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'pull' not in self._stubs: - self._stubs['pull'] = self.grpc_channel.unary_unary( - '/google.pubsub.v1.Subscriber/Pull', - request_serializer=pubsub.PullRequest.serialize, - response_deserializer=pubsub.PullResponse.deserialize, - ) - return self._stubs['pull'] - - @property - def streaming_pull(self) -> Callable[ - [pubsub.StreamingPullRequest], - Awaitable[pubsub.StreamingPullResponse]]: - r"""Return a callable for the streaming pull method over gRPC. - - Establishes a stream with the server, which sends messages down - to the client. The client streams acknowledgements and ack - deadline modifications back to the server. The server will close - the stream and return the status on any error. The server may - close the stream with status ``UNAVAILABLE`` to reassign - server-side resources, in which case, the client should - re-establish the stream. Flow control can be achieved by - configuring the underlying RPC channel. - - Returns: - Callable[[~.StreamingPullRequest], - Awaitable[~.StreamingPullResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'streaming_pull' not in self._stubs: - self._stubs['streaming_pull'] = self.grpc_channel.stream_stream( - '/google.pubsub.v1.Subscriber/StreamingPull', - request_serializer=pubsub.StreamingPullRequest.serialize, - response_deserializer=pubsub.StreamingPullResponse.deserialize, - ) - return self._stubs['streaming_pull'] - - @property - def modify_push_config(self) -> Callable[ - [pubsub.ModifyPushConfigRequest], - Awaitable[empty_pb2.Empty]]: - r"""Return a callable for the modify push config method over gRPC. - - Modifies the ``PushConfig`` for a specified subscription. - - This may be used to change a push subscription to a pull one - (signified by an empty ``PushConfig``) or vice versa, or change - the endpoint URL and other attributes of a push subscription. - Messages will accumulate for delivery continuously through the - call regardless of changes to the ``PushConfig``. - - Returns: - Callable[[~.ModifyPushConfigRequest], - 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 'modify_push_config' not in self._stubs: - self._stubs['modify_push_config'] = self.grpc_channel.unary_unary( - '/google.pubsub.v1.Subscriber/ModifyPushConfig', - request_serializer=pubsub.ModifyPushConfigRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['modify_push_config'] - - @property - def get_snapshot(self) -> Callable[ - [pubsub.GetSnapshotRequest], - Awaitable[pubsub.Snapshot]]: - r"""Return a callable for the get snapshot method over gRPC. - - Gets the configuration details of a snapshot. Snapshots are used - in - `Seek `__ - operations, which allow you to manage message acknowledgments in - bulk. That is, you can set the acknowledgment state of messages - in an existing subscription to the state captured by a snapshot. - - Returns: - Callable[[~.GetSnapshotRequest], - Awaitable[~.Snapshot]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'get_snapshot' not in self._stubs: - self._stubs['get_snapshot'] = self.grpc_channel.unary_unary( - '/google.pubsub.v1.Subscriber/GetSnapshot', - request_serializer=pubsub.GetSnapshotRequest.serialize, - response_deserializer=pubsub.Snapshot.deserialize, - ) - return self._stubs['get_snapshot'] - - @property - def list_snapshots(self) -> Callable[ - [pubsub.ListSnapshotsRequest], - Awaitable[pubsub.ListSnapshotsResponse]]: - r"""Return a callable for the list snapshots method over gRPC. - - Lists the existing snapshots. Snapshots are used in - `Seek `__ - operations, which allow you to manage message acknowledgments in - bulk. That is, you can set the acknowledgment state of messages - in an existing subscription to the state captured by a snapshot. - - Returns: - Callable[[~.ListSnapshotsRequest], - Awaitable[~.ListSnapshotsResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'list_snapshots' not in self._stubs: - self._stubs['list_snapshots'] = self.grpc_channel.unary_unary( - '/google.pubsub.v1.Subscriber/ListSnapshots', - request_serializer=pubsub.ListSnapshotsRequest.serialize, - response_deserializer=pubsub.ListSnapshotsResponse.deserialize, - ) - return self._stubs['list_snapshots'] - - @property - def create_snapshot(self) -> Callable[ - [pubsub.CreateSnapshotRequest], - Awaitable[pubsub.Snapshot]]: - r"""Return a callable for the create snapshot method over gRPC. - - Creates a snapshot from the requested subscription. Snapshots - are used in - `Seek `__ - operations, which allow you to manage message acknowledgments in - bulk. That is, you can set the acknowledgment state of messages - in an existing subscription to the state captured by a snapshot. - If the snapshot already exists, returns ``ALREADY_EXISTS``. If - the requested subscription doesn't exist, returns ``NOT_FOUND``. - If the backlog in the subscription is too old -- and the - resulting snapshot would expire in less than 1 hour -- then - ``FAILED_PRECONDITION`` is returned. See also the - ``Snapshot.expire_time`` field. If the name is not provided in - the request, the server will assign a random name for this - snapshot on the same project as the subscription, conforming to - the [resource name format] - (https://cloud.google.com/pubsub/docs/pubsub-basics#resource_names). - The generated name is populated in the returned Snapshot object. - Note that for REST API requests, you must specify a name in the - request. - - Returns: - Callable[[~.CreateSnapshotRequest], - Awaitable[~.Snapshot]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_snapshot' not in self._stubs: - self._stubs['create_snapshot'] = self.grpc_channel.unary_unary( - '/google.pubsub.v1.Subscriber/CreateSnapshot', - request_serializer=pubsub.CreateSnapshotRequest.serialize, - response_deserializer=pubsub.Snapshot.deserialize, - ) - return self._stubs['create_snapshot'] - - @property - def update_snapshot(self) -> Callable[ - [pubsub.UpdateSnapshotRequest], - Awaitable[pubsub.Snapshot]]: - r"""Return a callable for the update snapshot method over gRPC. - - Updates an existing snapshot by updating the fields specified in - the update mask. Snapshots are used in - `Seek `__ - operations, which allow you to manage message acknowledgments in - bulk. That is, you can set the acknowledgment state of messages - in an existing subscription to the state captured by a snapshot. - - Returns: - Callable[[~.UpdateSnapshotRequest], - Awaitable[~.Snapshot]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_snapshot' not in self._stubs: - self._stubs['update_snapshot'] = self.grpc_channel.unary_unary( - '/google.pubsub.v1.Subscriber/UpdateSnapshot', - request_serializer=pubsub.UpdateSnapshotRequest.serialize, - response_deserializer=pubsub.Snapshot.deserialize, - ) - return self._stubs['update_snapshot'] - - @property - def delete_snapshot(self) -> Callable[ - [pubsub.DeleteSnapshotRequest], - Awaitable[empty_pb2.Empty]]: - r"""Return a callable for the delete snapshot method over gRPC. - - Removes an existing snapshot. Snapshots are used in [Seek] - (https://cloud.google.com/pubsub/docs/replay-overview) - operations, which allow you to manage message acknowledgments in - bulk. That is, you can set the acknowledgment state of messages - in an existing subscription to the state captured by a snapshot. - When the snapshot is deleted, all messages retained in the - snapshot are immediately dropped. After a snapshot is deleted, a - new one may be created with the same name, but the new one has - no association with the old snapshot or its subscription, unless - the same subscription is specified. - - Returns: - Callable[[~.DeleteSnapshotRequest], - 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_snapshot' not in self._stubs: - self._stubs['delete_snapshot'] = self.grpc_channel.unary_unary( - '/google.pubsub.v1.Subscriber/DeleteSnapshot', - request_serializer=pubsub.DeleteSnapshotRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_snapshot'] - - @property - def seek(self) -> Callable[ - [pubsub.SeekRequest], - Awaitable[pubsub.SeekResponse]]: - r"""Return a callable for the seek method over gRPC. - - Seeks an existing subscription to a point in time or to a given - snapshot, whichever is provided in the request. Snapshots are - used in [Seek] - (https://cloud.google.com/pubsub/docs/replay-overview) - operations, which allow you to manage message acknowledgments in - bulk. That is, you can set the acknowledgment state of messages - in an existing subscription to the state captured by a snapshot. - Note that both the subscription and the snapshot must be on the - same topic. - - Returns: - Callable[[~.SeekRequest], - Awaitable[~.SeekResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'seek' not in self._stubs: - self._stubs['seek'] = self.grpc_channel.unary_unary( - '/google.pubsub.v1.Subscriber/Seek', - request_serializer=pubsub.SeekRequest.serialize, - response_deserializer=pubsub.SeekResponse.deserialize, - ) - return self._stubs['seek'] - - @property - def set_iam_policy( - self, - ) -> Callable[[iam_policy_pb2.SetIamPolicyRequest], Awaitable[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], - Awaitable[~.Policy]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "set_iam_policy" not in self._stubs: - self._stubs["set_iam_policy"] = self.grpc_channel.unary_unary( - "/google.iam.v1.IAMPolicy/SetIamPolicy", - request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString, - response_deserializer=policy_pb2.Policy.FromString, - ) - return self._stubs["set_iam_policy"] - - @property - def get_iam_policy( - self, - ) -> Callable[[iam_policy_pb2.GetIamPolicyRequest], Awaitable[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], - Awaitable[~.Policy]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "get_iam_policy" not in self._stubs: - self._stubs["get_iam_policy"] = self.grpc_channel.unary_unary( - "/google.iam.v1.IAMPolicy/GetIamPolicy", - request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, - response_deserializer=policy_pb2.Policy.FromString, - ) - return self._stubs["get_iam_policy"] - - @property - def test_iam_permissions( - self, - ) -> Callable[ - [iam_policy_pb2.TestIamPermissionsRequest], - Awaitable[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], - Awaitable[~.TestIamPermissionsResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "test_iam_permissions" not in self._stubs: - self._stubs["test_iam_permissions"] = self.grpc_channel.unary_unary( - "/google.iam.v1.IAMPolicy/TestIamPermissions", - request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString, - response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString, - ) - return self._stubs["test_iam_permissions"] - - 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_subscription: gapic_v1.method_async.wrap_method( - self.create_subscription, - default_retry=retries.AsyncRetry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.Aborted, - core_exceptions.ServiceUnavailable, - core_exceptions.Unknown, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.get_subscription: gapic_v1.method_async.wrap_method( - self.get_subscription, - default_retry=retries.AsyncRetry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.Aborted, - core_exceptions.ServiceUnavailable, - core_exceptions.Unknown, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.update_subscription: gapic_v1.method_async.wrap_method( - self.update_subscription, - default_retry=retries.AsyncRetry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.list_subscriptions: gapic_v1.method_async.wrap_method( - self.list_subscriptions, - default_retry=retries.AsyncRetry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.Aborted, - core_exceptions.ServiceUnavailable, - core_exceptions.Unknown, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.delete_subscription: gapic_v1.method_async.wrap_method( - self.delete_subscription, - default_retry=retries.AsyncRetry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.modify_ack_deadline: gapic_v1.method_async.wrap_method( - self.modify_ack_deadline, - default_retry=retries.AsyncRetry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.acknowledge: gapic_v1.method_async.wrap_method( - self.acknowledge, - default_retry=retries.AsyncRetry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.pull: gapic_v1.method_async.wrap_method( - self.pull, - default_retry=retries.AsyncRetry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.Aborted, - core_exceptions.InternalServerError, - core_exceptions.ServiceUnavailable, - core_exceptions.Unknown, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.streaming_pull: gapic_v1.method_async.wrap_method( - self.streaming_pull, - default_retry=retries.AsyncRetry( - initial=0.1, - maximum=60.0, - multiplier=4, - predicate=retries.if_exception_type( - core_exceptions.Aborted, - core_exceptions.DeadlineExceeded, - core_exceptions.InternalServerError, - core_exceptions.ResourceExhausted, - core_exceptions.ServiceUnavailable, - ), - deadline=900.0, - ), - default_timeout=900.0, - client_info=client_info, - ), - self.modify_push_config: gapic_v1.method_async.wrap_method( - self.modify_push_config, - default_retry=retries.AsyncRetry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.get_snapshot: gapic_v1.method_async.wrap_method( - self.get_snapshot, - default_retry=retries.AsyncRetry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.Aborted, - core_exceptions.ServiceUnavailable, - core_exceptions.Unknown, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.list_snapshots: gapic_v1.method_async.wrap_method( - self.list_snapshots, - default_retry=retries.AsyncRetry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.Aborted, - core_exceptions.ServiceUnavailable, - core_exceptions.Unknown, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.create_snapshot: gapic_v1.method_async.wrap_method( - self.create_snapshot, - default_retry=retries.AsyncRetry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.update_snapshot: gapic_v1.method_async.wrap_method( - self.update_snapshot, - default_retry=retries.AsyncRetry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.delete_snapshot: gapic_v1.method_async.wrap_method( - self.delete_snapshot, - default_retry=retries.AsyncRetry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.seek: gapic_v1.method_async.wrap_method( - self.seek, - default_retry=retries.AsyncRetry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.Aborted, - core_exceptions.ServiceUnavailable, - core_exceptions.Unknown, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - } - - def close(self): - return self.grpc_channel.close() - - -__all__ = ( - 'SubscriberGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v1/google/pubsub_v1/services/subscriber/transports/rest.py b/owl-bot-staging/v1/google/pubsub_v1/services/subscriber/transports/rest.py deleted file mode 100644 index 48f12c2e4..000000000 --- a/owl-bot-staging/v1/google/pubsub_v1/services/subscriber/transports/rest.py +++ /dev/null @@ -1,2139 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -from google.auth.transport.requests import AuthorizedSession # type: ignore -import json # type: ignore -import grpc # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.api_core import exceptions as core_exceptions -from google.api_core import retry as retries -from google.api_core import rest_helpers -from google.api_core import rest_streaming -from google.api_core import 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 requests import __version__ as requests_version -import dataclasses -import re -from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union -import warnings - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object, None] # type: ignore - - -from google.iam.v1 import iam_policy_pb2 # type: ignore -from google.iam.v1 import policy_pb2 # type: ignore -from google.protobuf import empty_pb2 # type: ignore -from google.pubsub_v1.types import pubsub - -from .base import SubscriberTransport, DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO - - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, - grpc_version=None, - rest_version=requests_version, -) - - -class SubscriberRestInterceptor: - """Interceptor for Subscriber. - - 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 SubscriberRestTransport. - - .. code-block:: python - class MyCustomSubscriberInterceptor(SubscriberRestInterceptor): - def pre_acknowledge(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def pre_create_snapshot(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_create_snapshot(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_create_subscription(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_create_subscription(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_delete_snapshot(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def pre_delete_subscription(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def pre_get_snapshot(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_snapshot(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_get_subscription(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_subscription(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_list_snapshots(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_list_snapshots(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_list_subscriptions(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_list_subscriptions(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_modify_ack_deadline(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def pre_modify_push_config(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def pre_pull(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_pull(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_seek(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_seek(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_update_snapshot(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_update_snapshot(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_update_subscription(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_update_subscription(self, response): - logging.log(f"Received response: {response}") - return response - - transport = SubscriberRestTransport(interceptor=MyCustomSubscriberInterceptor()) - client = SubscriberClient(transport=transport) - - - """ - def pre_acknowledge(self, request: pubsub.AcknowledgeRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[pubsub.AcknowledgeRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for acknowledge - - Override in a subclass to manipulate the request or metadata - before they are sent to the Subscriber server. - """ - return request, metadata - - def pre_create_snapshot(self, request: pubsub.CreateSnapshotRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[pubsub.CreateSnapshotRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for create_snapshot - - Override in a subclass to manipulate the request or metadata - before they are sent to the Subscriber server. - """ - return request, metadata - - def post_create_snapshot(self, response: pubsub.Snapshot) -> pubsub.Snapshot: - """Post-rpc interceptor for create_snapshot - - Override in a subclass to manipulate the response - after it is returned by the Subscriber server but before - it is returned to user code. - """ - return response - def pre_create_subscription(self, request: pubsub.Subscription, metadata: Sequence[Tuple[str, str]]) -> Tuple[pubsub.Subscription, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for create_subscription - - Override in a subclass to manipulate the request or metadata - before they are sent to the Subscriber server. - """ - return request, metadata - - def post_create_subscription(self, response: pubsub.Subscription) -> pubsub.Subscription: - """Post-rpc interceptor for create_subscription - - Override in a subclass to manipulate the response - after it is returned by the Subscriber server but before - it is returned to user code. - """ - return response - def pre_delete_snapshot(self, request: pubsub.DeleteSnapshotRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[pubsub.DeleteSnapshotRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for delete_snapshot - - Override in a subclass to manipulate the request or metadata - before they are sent to the Subscriber server. - """ - return request, metadata - - def pre_delete_subscription(self, request: pubsub.DeleteSubscriptionRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[pubsub.DeleteSubscriptionRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for delete_subscription - - Override in a subclass to manipulate the request or metadata - before they are sent to the Subscriber server. - """ - return request, metadata - - def pre_get_snapshot(self, request: pubsub.GetSnapshotRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[pubsub.GetSnapshotRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_snapshot - - Override in a subclass to manipulate the request or metadata - before they are sent to the Subscriber server. - """ - return request, metadata - - def post_get_snapshot(self, response: pubsub.Snapshot) -> pubsub.Snapshot: - """Post-rpc interceptor for get_snapshot - - Override in a subclass to manipulate the response - after it is returned by the Subscriber server but before - it is returned to user code. - """ - return response - def pre_get_subscription(self, request: pubsub.GetSubscriptionRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[pubsub.GetSubscriptionRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_subscription - - Override in a subclass to manipulate the request or metadata - before they are sent to the Subscriber server. - """ - return request, metadata - - def post_get_subscription(self, response: pubsub.Subscription) -> pubsub.Subscription: - """Post-rpc interceptor for get_subscription - - Override in a subclass to manipulate the response - after it is returned by the Subscriber server but before - it is returned to user code. - """ - return response - def pre_list_snapshots(self, request: pubsub.ListSnapshotsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[pubsub.ListSnapshotsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_snapshots - - Override in a subclass to manipulate the request or metadata - before they are sent to the Subscriber server. - """ - return request, metadata - - def post_list_snapshots(self, response: pubsub.ListSnapshotsResponse) -> pubsub.ListSnapshotsResponse: - """Post-rpc interceptor for list_snapshots - - Override in a subclass to manipulate the response - after it is returned by the Subscriber server but before - it is returned to user code. - """ - return response - def pre_list_subscriptions(self, request: pubsub.ListSubscriptionsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[pubsub.ListSubscriptionsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_subscriptions - - Override in a subclass to manipulate the request or metadata - before they are sent to the Subscriber server. - """ - return request, metadata - - def post_list_subscriptions(self, response: pubsub.ListSubscriptionsResponse) -> pubsub.ListSubscriptionsResponse: - """Post-rpc interceptor for list_subscriptions - - Override in a subclass to manipulate the response - after it is returned by the Subscriber server but before - it is returned to user code. - """ - return response - def pre_modify_ack_deadline(self, request: pubsub.ModifyAckDeadlineRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[pubsub.ModifyAckDeadlineRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for modify_ack_deadline - - Override in a subclass to manipulate the request or metadata - before they are sent to the Subscriber server. - """ - return request, metadata - - def pre_modify_push_config(self, request: pubsub.ModifyPushConfigRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[pubsub.ModifyPushConfigRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for modify_push_config - - Override in a subclass to manipulate the request or metadata - before they are sent to the Subscriber server. - """ - return request, metadata - - def pre_pull(self, request: pubsub.PullRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[pubsub.PullRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for pull - - Override in a subclass to manipulate the request or metadata - before they are sent to the Subscriber server. - """ - return request, metadata - - def post_pull(self, response: pubsub.PullResponse) -> pubsub.PullResponse: - """Post-rpc interceptor for pull - - Override in a subclass to manipulate the response - after it is returned by the Subscriber server but before - it is returned to user code. - """ - return response - def pre_seek(self, request: pubsub.SeekRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[pubsub.SeekRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for seek - - Override in a subclass to manipulate the request or metadata - before they are sent to the Subscriber server. - """ - return request, metadata - - def post_seek(self, response: pubsub.SeekResponse) -> pubsub.SeekResponse: - """Post-rpc interceptor for seek - - Override in a subclass to manipulate the response - after it is returned by the Subscriber server but before - it is returned to user code. - """ - return response - def pre_update_snapshot(self, request: pubsub.UpdateSnapshotRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[pubsub.UpdateSnapshotRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for update_snapshot - - Override in a subclass to manipulate the request or metadata - before they are sent to the Subscriber server. - """ - return request, metadata - - def post_update_snapshot(self, response: pubsub.Snapshot) -> pubsub.Snapshot: - """Post-rpc interceptor for update_snapshot - - Override in a subclass to manipulate the response - after it is returned by the Subscriber server but before - it is returned to user code. - """ - return response - def pre_update_subscription(self, request: pubsub.UpdateSubscriptionRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[pubsub.UpdateSubscriptionRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for update_subscription - - Override in a subclass to manipulate the request or metadata - before they are sent to the Subscriber server. - """ - return request, metadata - - def post_update_subscription(self, response: pubsub.Subscription) -> pubsub.Subscription: - """Post-rpc interceptor for update_subscription - - Override in a subclass to manipulate the response - after it is returned by the Subscriber server but before - it is returned to user code. - """ - return response - - def pre_get_iam_policy( - self, request: iam_policy_pb2.GetIamPolicyRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[iam_policy_pb2.GetIamPolicyRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_iam_policy - - Override in a subclass to manipulate the request or metadata - before they are sent to the Subscriber 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 Subscriber server but before - it is returned to user code. - """ - return response - def pre_set_iam_policy( - self, request: iam_policy_pb2.SetIamPolicyRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[iam_policy_pb2.SetIamPolicyRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for set_iam_policy - - Override in a subclass to manipulate the request or metadata - before they are sent to the Subscriber 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 Subscriber server but before - it is returned to user code. - """ - return response - def pre_test_iam_permissions( - self, request: iam_policy_pb2.TestIamPermissionsRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[iam_policy_pb2.TestIamPermissionsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for test_iam_permissions - - Override in a subclass to manipulate the request or metadata - before they are sent to the Subscriber 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 Subscriber server but before - it is returned to user code. - """ - return response - - -@dataclasses.dataclass -class SubscriberRestStub: - _session: AuthorizedSession - _host: str - _interceptor: SubscriberRestInterceptor - - -class SubscriberRestTransport(SubscriberTransport): - """REST backend transport for Subscriber. - - The service that an application uses to manipulate subscriptions and - to consume messages from a subscription via the ``Pull`` method or - by establishing a bi-directional stream using the ``StreamingPull`` - method. - - This 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 = 'pubsub.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - client_cert_source_for_mtls: Optional[Callable[[ - ], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - url_scheme: str = 'https', - interceptor: Optional[SubscriberRestInterceptor] = None, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to (default: 'pubsub.googleapis.com'). - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client - certificate to configure mutual TLS HTTP channel. It is ignored - if ``channel`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you are developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - url_scheme: the protocol scheme for the API endpoint. Normally - "https", but for testing or local servers, - "http" can be specified. - """ - # Run the base constructor - # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. - # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the - # credentials object - 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 - ) - 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 SubscriberRestInterceptor() - self._prep_wrapped_messages(client_info) - - class _Acknowledge(SubscriberRestStub): - def __hash__(self): - return hash("Acknowledge") - - __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} - - def __call__(self, - request: pubsub.AcknowledgeRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ): - r"""Call the acknowledge method over HTTP. - - Args: - request (~.pubsub.AcknowledgeRequest): - The request object. Request for the Acknowledge method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/{subscription=projects/*/subscriptions/*}:acknowledge', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_acknowledge(request, metadata) - pb_request = pubsub.AcknowledgeRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=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) - - class _CreateSnapshot(SubscriberRestStub): - def __hash__(self): - return hash("CreateSnapshot") - - __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} - - def __call__(self, - request: pubsub.CreateSnapshotRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> pubsub.Snapshot: - r"""Call the create snapshot method over HTTP. - - Args: - request (~.pubsub.CreateSnapshotRequest): - The request object. Request for the ``CreateSnapshot`` method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.pubsub.Snapshot: - A snapshot resource. Snapshots are used in - `Seek `__ - operations, which allow you to manage message - acknowledgments in bulk. That is, you can set the - acknowledgment state of messages in an existing - subscription to the state captured by a snapshot. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'put', - 'uri': '/v1/{name=projects/*/snapshots/*}', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_create_snapshot(request, metadata) - pb_request = pubsub.CreateSnapshotRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=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 = pubsub.Snapshot() - pb_resp = pubsub.Snapshot.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_create_snapshot(resp) - return resp - - class _CreateSubscription(SubscriberRestStub): - def __hash__(self): - return hash("CreateSubscription") - - __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} - - def __call__(self, - request: pubsub.Subscription, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> pubsub.Subscription: - r"""Call the create subscription method over HTTP. - - Args: - request (~.pubsub.Subscription): - The request object. A subscription resource. If none of ``push_config``, - ``bigquery_config``, or ``cloud_storage_config`` is set, - then the subscriber will pull and ack messages using API - methods. At most one of these fields may be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.pubsub.Subscription: - A subscription resource. If none of ``push_config``, - ``bigquery_config``, or ``cloud_storage_config`` is set, - then the subscriber will pull and ack messages using API - methods. At most one of these fields may be set. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'put', - 'uri': '/v1/{name=projects/*/subscriptions/*}', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_create_subscription(request, metadata) - pb_request = pubsub.Subscription.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=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 = pubsub.Subscription() - pb_resp = pubsub.Subscription.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_create_subscription(resp) - return resp - - class _DeleteSnapshot(SubscriberRestStub): - def __hash__(self): - return hash("DeleteSnapshot") - - __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} - - def __call__(self, - request: pubsub.DeleteSnapshotRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ): - r"""Call the delete snapshot method over HTTP. - - Args: - request (~.pubsub.DeleteSnapshotRequest): - The request object. Request for the ``DeleteSnapshot`` method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'delete', - 'uri': '/v1/{snapshot=projects/*/snapshots/*}', - }, - ] - request, metadata = self._interceptor.pre_delete_snapshot(request, metadata) - pb_request = pubsub.DeleteSnapshotRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # 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 _DeleteSubscription(SubscriberRestStub): - def __hash__(self): - return hash("DeleteSubscription") - - __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} - - def __call__(self, - request: pubsub.DeleteSubscriptionRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ): - r"""Call the delete subscription method over HTTP. - - Args: - request (~.pubsub.DeleteSubscriptionRequest): - The request object. Request for the DeleteSubscription - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'delete', - 'uri': '/v1/{subscription=projects/*/subscriptions/*}', - }, - ] - request, metadata = self._interceptor.pre_delete_subscription(request, metadata) - pb_request = pubsub.DeleteSubscriptionRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # 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 _GetSnapshot(SubscriberRestStub): - def __hash__(self): - return hash("GetSnapshot") - - __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} - - def __call__(self, - request: pubsub.GetSnapshotRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> pubsub.Snapshot: - r"""Call the get snapshot method over HTTP. - - Args: - request (~.pubsub.GetSnapshotRequest): - The request object. Request for the GetSnapshot method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.pubsub.Snapshot: - A snapshot resource. Snapshots are used in - `Seek `__ - operations, which allow you to manage message - acknowledgments in bulk. That is, you can set the - acknowledgment state of messages in an existing - subscription to the state captured by a snapshot. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{snapshot=projects/*/snapshots/*}', - }, - ] - request, metadata = self._interceptor.pre_get_snapshot(request, metadata) - pb_request = pubsub.GetSnapshotRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # 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 = pubsub.Snapshot() - pb_resp = pubsub.Snapshot.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_get_snapshot(resp) - return resp - - class _GetSubscription(SubscriberRestStub): - def __hash__(self): - return hash("GetSubscription") - - __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} - - def __call__(self, - request: pubsub.GetSubscriptionRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> pubsub.Subscription: - r"""Call the get subscription method over HTTP. - - Args: - request (~.pubsub.GetSubscriptionRequest): - The request object. Request for the GetSubscription - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.pubsub.Subscription: - A subscription resource. If none of ``push_config``, - ``bigquery_config``, or ``cloud_storage_config`` is set, - then the subscriber will pull and ack messages using API - methods. At most one of these fields may be set. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{subscription=projects/*/subscriptions/*}', - }, - ] - request, metadata = self._interceptor.pre_get_subscription(request, metadata) - pb_request = pubsub.GetSubscriptionRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # 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 = pubsub.Subscription() - pb_resp = pubsub.Subscription.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_get_subscription(resp) - return resp - - class _ListSnapshots(SubscriberRestStub): - def __hash__(self): - return hash("ListSnapshots") - - __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} - - def __call__(self, - request: pubsub.ListSnapshotsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> pubsub.ListSnapshotsResponse: - r"""Call the list snapshots method over HTTP. - - Args: - request (~.pubsub.ListSnapshotsRequest): - The request object. Request for the ``ListSnapshots`` method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.pubsub.ListSnapshotsResponse: - Response for the ``ListSnapshots`` method. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{project=projects/*}/snapshots', - }, - ] - request, metadata = self._interceptor.pre_list_snapshots(request, metadata) - pb_request = pubsub.ListSnapshotsRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # 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 = pubsub.ListSnapshotsResponse() - pb_resp = pubsub.ListSnapshotsResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_list_snapshots(resp) - return resp - - class _ListSubscriptions(SubscriberRestStub): - def __hash__(self): - return hash("ListSubscriptions") - - __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} - - def __call__(self, - request: pubsub.ListSubscriptionsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> pubsub.ListSubscriptionsResponse: - r"""Call the list subscriptions method over HTTP. - - Args: - request (~.pubsub.ListSubscriptionsRequest): - The request object. Request for the ``ListSubscriptions`` method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.pubsub.ListSubscriptionsResponse: - Response for the ``ListSubscriptions`` method. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{project=projects/*}/subscriptions', - }, - ] - request, metadata = self._interceptor.pre_list_subscriptions(request, metadata) - pb_request = pubsub.ListSubscriptionsRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # 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 = pubsub.ListSubscriptionsResponse() - pb_resp = pubsub.ListSubscriptionsResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_list_subscriptions(resp) - return resp - - class _ModifyAckDeadline(SubscriberRestStub): - def __hash__(self): - return hash("ModifyAckDeadline") - - __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} - - def __call__(self, - request: pubsub.ModifyAckDeadlineRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ): - r"""Call the modify ack deadline method over HTTP. - - Args: - request (~.pubsub.ModifyAckDeadlineRequest): - The request object. Request for the ModifyAckDeadline - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/{subscription=projects/*/subscriptions/*}:modifyAckDeadline', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_modify_ack_deadline(request, metadata) - pb_request = pubsub.ModifyAckDeadlineRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=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) - - class _ModifyPushConfig(SubscriberRestStub): - def __hash__(self): - return hash("ModifyPushConfig") - - __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} - - def __call__(self, - request: pubsub.ModifyPushConfigRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ): - r"""Call the modify push config method over HTTP. - - Args: - request (~.pubsub.ModifyPushConfigRequest): - The request object. Request for the ModifyPushConfig - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/{subscription=projects/*/subscriptions/*}:modifyPushConfig', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_modify_push_config(request, metadata) - pb_request = pubsub.ModifyPushConfigRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=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) - - class _Pull(SubscriberRestStub): - def __hash__(self): - return hash("Pull") - - __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} - - def __call__(self, - request: pubsub.PullRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> pubsub.PullResponse: - r"""Call the pull method over HTTP. - - Args: - request (~.pubsub.PullRequest): - The request object. Request for the ``Pull`` method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.pubsub.PullResponse: - Response for the ``Pull`` method. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/{subscription=projects/*/subscriptions/*}:pull', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_pull(request, metadata) - pb_request = pubsub.PullRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=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 = pubsub.PullResponse() - pb_resp = pubsub.PullResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_pull(resp) - return resp - - class _Seek(SubscriberRestStub): - def __hash__(self): - return hash("Seek") - - __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} - - def __call__(self, - request: pubsub.SeekRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> pubsub.SeekResponse: - r"""Call the seek method over HTTP. - - Args: - request (~.pubsub.SeekRequest): - The request object. Request for the ``Seek`` method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.pubsub.SeekResponse: - Response for the ``Seek`` method (this response is - empty). - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/{subscription=projects/*/subscriptions/*}:seek', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_seek(request, metadata) - pb_request = pubsub.SeekRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=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 = pubsub.SeekResponse() - pb_resp = pubsub.SeekResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_seek(resp) - return resp - - class _StreamingPull(SubscriberRestStub): - def __hash__(self): - return hash("StreamingPull") - - def __call__(self, - request: pubsub.StreamingPullRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> rest_streaming.ResponseIterator: - raise NotImplementedError( - "Method StreamingPull is not available over REST transport" - ) - class _UpdateSnapshot(SubscriberRestStub): - def __hash__(self): - return hash("UpdateSnapshot") - - __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} - - def __call__(self, - request: pubsub.UpdateSnapshotRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> pubsub.Snapshot: - r"""Call the update snapshot method over HTTP. - - Args: - request (~.pubsub.UpdateSnapshotRequest): - The request object. Request for the UpdateSnapshot - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.pubsub.Snapshot: - A snapshot resource. Snapshots are used in - `Seek `__ - operations, which allow you to manage message - acknowledgments in bulk. That is, you can set the - acknowledgment state of messages in an existing - subscription to the state captured by a snapshot. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'patch', - 'uri': '/v1/{snapshot.name=projects/*/snapshots/*}', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_update_snapshot(request, metadata) - pb_request = pubsub.UpdateSnapshotRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=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 = pubsub.Snapshot() - pb_resp = pubsub.Snapshot.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_update_snapshot(resp) - return resp - - class _UpdateSubscription(SubscriberRestStub): - def __hash__(self): - return hash("UpdateSubscription") - - __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} - - def __call__(self, - request: pubsub.UpdateSubscriptionRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> pubsub.Subscription: - r"""Call the update subscription method over HTTP. - - Args: - request (~.pubsub.UpdateSubscriptionRequest): - The request object. Request for the UpdateSubscription - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.pubsub.Subscription: - A subscription resource. If none of ``push_config``, - ``bigquery_config``, or ``cloud_storage_config`` is set, - then the subscriber will pull and ack messages using API - methods. At most one of these fields may be set. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'patch', - 'uri': '/v1/{subscription.name=projects/*/subscriptions/*}', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_update_subscription(request, metadata) - pb_request = pubsub.UpdateSubscriptionRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=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 = pubsub.Subscription() - pb_resp = pubsub.Subscription.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_update_subscription(resp) - return resp - - @property - def acknowledge(self) -> Callable[ - [pubsub.AcknowledgeRequest], - 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._Acknowledge(self._session, self._host, self._interceptor) # type: ignore - - @property - def create_snapshot(self) -> Callable[ - [pubsub.CreateSnapshotRequest], - pubsub.Snapshot]: - # 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._CreateSnapshot(self._session, self._host, self._interceptor) # type: ignore - - @property - def create_subscription(self) -> Callable[ - [pubsub.Subscription], - pubsub.Subscription]: - # 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._CreateSubscription(self._session, self._host, self._interceptor) # type: ignore - - @property - def delete_snapshot(self) -> Callable[ - [pubsub.DeleteSnapshotRequest], - 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._DeleteSnapshot(self._session, self._host, self._interceptor) # type: ignore - - @property - def delete_subscription(self) -> Callable[ - [pubsub.DeleteSubscriptionRequest], - 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._DeleteSubscription(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_snapshot(self) -> Callable[ - [pubsub.GetSnapshotRequest], - pubsub.Snapshot]: - # 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._GetSnapshot(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_subscription(self) -> Callable[ - [pubsub.GetSubscriptionRequest], - pubsub.Subscription]: - # 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._GetSubscription(self._session, self._host, self._interceptor) # type: ignore - - @property - def list_snapshots(self) -> Callable[ - [pubsub.ListSnapshotsRequest], - pubsub.ListSnapshotsResponse]: - # 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._ListSnapshots(self._session, self._host, self._interceptor) # type: ignore - - @property - def list_subscriptions(self) -> Callable[ - [pubsub.ListSubscriptionsRequest], - pubsub.ListSubscriptionsResponse]: - # 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._ListSubscriptions(self._session, self._host, self._interceptor) # type: ignore - - @property - def modify_ack_deadline(self) -> Callable[ - [pubsub.ModifyAckDeadlineRequest], - 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._ModifyAckDeadline(self._session, self._host, self._interceptor) # type: ignore - - @property - def modify_push_config(self) -> Callable[ - [pubsub.ModifyPushConfigRequest], - 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._ModifyPushConfig(self._session, self._host, self._interceptor) # type: ignore - - @property - def pull(self) -> Callable[ - [pubsub.PullRequest], - pubsub.PullResponse]: - # 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._Pull(self._session, self._host, self._interceptor) # type: ignore - - @property - def seek(self) -> Callable[ - [pubsub.SeekRequest], - pubsub.SeekResponse]: - # 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._Seek(self._session, self._host, self._interceptor) # type: ignore - - @property - def streaming_pull(self) -> Callable[ - [pubsub.StreamingPullRequest], - pubsub.StreamingPullResponse]: - # 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._StreamingPull(self._session, self._host, self._interceptor) # type: ignore - - @property - def update_snapshot(self) -> Callable[ - [pubsub.UpdateSnapshotRequest], - pubsub.Snapshot]: - # 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._UpdateSnapshot(self._session, self._host, self._interceptor) # type: ignore - - @property - def update_subscription(self) -> Callable[ - [pubsub.UpdateSubscriptionRequest], - pubsub.Subscription]: - # 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._UpdateSubscription(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_iam_policy(self): - return self._GetIamPolicy(self._session, self._host, self._interceptor) # type: ignore - - class _GetIamPolicy(SubscriberRestStub): - def __call__(self, - request: iam_policy_pb2.GetIamPolicyRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> policy_pb2.Policy: - - r"""Call the get iam policy method over HTTP. - - Args: - request (iam_policy_pb2.GetIamPolicyRequest): - The request object for GetIamPolicy method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - policy_pb2.Policy: Response from GetIamPolicy method. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{resource=projects/*/topics/*}:getIamPolicy', - }, -{ - 'method': 'get', - 'uri': '/v1/{resource=projects/*/subscriptions/*}:getIamPolicy', - }, -{ - 'method': 'get', - 'uri': '/v1/{resource=projects/*/snapshots/*}:getIamPolicy', - }, -{ - 'method': 'get', - 'uri': '/v1/{resource=projects/*/schemas/*}:getIamPolicy', - }, - ] - - request, metadata = self._interceptor.pre_get_iam_policy(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - resp = policy_pb2.Policy() - resp = json_format.Parse(response.content.decode("utf-8"), resp) - resp = self._interceptor.post_get_iam_policy(resp) - return resp - - @property - def set_iam_policy(self): - return self._SetIamPolicy(self._session, self._host, self._interceptor) # type: ignore - - class _SetIamPolicy(SubscriberRestStub): - def __call__(self, - request: iam_policy_pb2.SetIamPolicyRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> policy_pb2.Policy: - - r"""Call the set iam policy method over HTTP. - - Args: - request (iam_policy_pb2.SetIamPolicyRequest): - The request object for SetIamPolicy method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - policy_pb2.Policy: Response from SetIamPolicy method. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/{resource=projects/*/topics/*}:setIamPolicy', - 'body': '*', - }, -{ - 'method': 'post', - 'uri': '/v1/{resource=projects/*/subscriptions/*}:setIamPolicy', - 'body': '*', - }, -{ - 'method': 'post', - 'uri': '/v1/{resource=projects/*/snapshots/*}:setIamPolicy', - 'body': '*', - }, -{ - 'method': 'post', - 'uri': '/v1/{resource=projects/*/schemas/*}:setIamPolicy', - 'body': '*', - }, - ] - - request, metadata = self._interceptor.pre_set_iam_policy(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - body = json.dumps(transcoded_request['body']) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - data=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) - - resp = policy_pb2.Policy() - resp = json_format.Parse(response.content.decode("utf-8"), resp) - resp = self._interceptor.post_set_iam_policy(resp) - return resp - - @property - def test_iam_permissions(self): - return self._TestIamPermissions(self._session, self._host, self._interceptor) # type: ignore - - class _TestIamPermissions(SubscriberRestStub): - def __call__(self, - request: iam_policy_pb2.TestIamPermissionsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> iam_policy_pb2.TestIamPermissionsResponse: - - r"""Call the test iam permissions method over HTTP. - - Args: - request (iam_policy_pb2.TestIamPermissionsRequest): - The request object for TestIamPermissions method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - iam_policy_pb2.TestIamPermissionsResponse: Response from TestIamPermissions method. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/{resource=projects/*/subscriptions/*}:testIamPermissions', - 'body': '*', - }, -{ - 'method': 'post', - 'uri': '/v1/{resource=projects/*/topics/*}:testIamPermissions', - 'body': '*', - }, -{ - 'method': 'post', - 'uri': '/v1/{resource=projects/*/snapshots/*}:testIamPermissions', - 'body': '*', - }, -{ - 'method': 'post', - 'uri': '/v1/{resource=projects/*/schemas/*}:testIamPermissions', - 'body': '*', - }, - ] - - request, metadata = self._interceptor.pre_test_iam_permissions(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - body = json.dumps(transcoded_request['body']) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - data=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) - - resp = iam_policy_pb2.TestIamPermissionsResponse() - resp = json_format.Parse(response.content.decode("utf-8"), resp) - resp = self._interceptor.post_test_iam_permissions(resp) - return resp - - @property - def kind(self) -> str: - return "rest" - - def close(self): - self._session.close() - - -__all__=( - 'SubscriberRestTransport', -) diff --git a/owl-bot-staging/v1/google/pubsub_v1/types/__init__.py b/owl-bot-staging/v1/google/pubsub_v1/types/__init__.py deleted file mode 100644 index fe285419a..000000000 --- a/owl-bot-staging/v1/google/pubsub_v1/types/__init__.py +++ /dev/null @@ -1,150 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from .pubsub import ( - AcknowledgeRequest, - BigQueryConfig, - CloudStorageConfig, - CreateSnapshotRequest, - DeadLetterPolicy, - DeleteSnapshotRequest, - DeleteSubscriptionRequest, - DeleteTopicRequest, - DetachSubscriptionRequest, - DetachSubscriptionResponse, - ExpirationPolicy, - GetSnapshotRequest, - GetSubscriptionRequest, - GetTopicRequest, - IngestionDataSourceSettings, - ListSnapshotsRequest, - ListSnapshotsResponse, - ListSubscriptionsRequest, - ListSubscriptionsResponse, - ListTopicSnapshotsRequest, - ListTopicSnapshotsResponse, - ListTopicsRequest, - ListTopicsResponse, - ListTopicSubscriptionsRequest, - ListTopicSubscriptionsResponse, - MessageStoragePolicy, - ModifyAckDeadlineRequest, - ModifyPushConfigRequest, - PublishRequest, - PublishResponse, - PubsubMessage, - PullRequest, - PullResponse, - PushConfig, - ReceivedMessage, - RetryPolicy, - SchemaSettings, - SeekRequest, - SeekResponse, - Snapshot, - StreamingPullRequest, - StreamingPullResponse, - Subscription, - Topic, - UpdateSnapshotRequest, - UpdateSubscriptionRequest, - UpdateTopicRequest, -) -from .schema import ( - CommitSchemaRequest, - CreateSchemaRequest, - DeleteSchemaRequest, - DeleteSchemaRevisionRequest, - GetSchemaRequest, - ListSchemaRevisionsRequest, - ListSchemaRevisionsResponse, - ListSchemasRequest, - ListSchemasResponse, - RollbackSchemaRequest, - Schema, - ValidateMessageRequest, - ValidateMessageResponse, - ValidateSchemaRequest, - ValidateSchemaResponse, - Encoding, - SchemaView, -) - -__all__ = ( - 'AcknowledgeRequest', - 'BigQueryConfig', - 'CloudStorageConfig', - 'CreateSnapshotRequest', - 'DeadLetterPolicy', - 'DeleteSnapshotRequest', - 'DeleteSubscriptionRequest', - 'DeleteTopicRequest', - 'DetachSubscriptionRequest', - 'DetachSubscriptionResponse', - 'ExpirationPolicy', - 'GetSnapshotRequest', - 'GetSubscriptionRequest', - 'GetTopicRequest', - 'IngestionDataSourceSettings', - 'ListSnapshotsRequest', - 'ListSnapshotsResponse', - 'ListSubscriptionsRequest', - 'ListSubscriptionsResponse', - 'ListTopicSnapshotsRequest', - 'ListTopicSnapshotsResponse', - 'ListTopicsRequest', - 'ListTopicsResponse', - 'ListTopicSubscriptionsRequest', - 'ListTopicSubscriptionsResponse', - 'MessageStoragePolicy', - 'ModifyAckDeadlineRequest', - 'ModifyPushConfigRequest', - 'PublishRequest', - 'PublishResponse', - 'PubsubMessage', - 'PullRequest', - 'PullResponse', - 'PushConfig', - 'ReceivedMessage', - 'RetryPolicy', - 'SchemaSettings', - 'SeekRequest', - 'SeekResponse', - 'Snapshot', - 'StreamingPullRequest', - 'StreamingPullResponse', - 'Subscription', - 'Topic', - 'UpdateSnapshotRequest', - 'UpdateSubscriptionRequest', - 'UpdateTopicRequest', - 'CommitSchemaRequest', - 'CreateSchemaRequest', - 'DeleteSchemaRequest', - 'DeleteSchemaRevisionRequest', - 'GetSchemaRequest', - 'ListSchemaRevisionsRequest', - 'ListSchemaRevisionsResponse', - 'ListSchemasRequest', - 'ListSchemasResponse', - 'RollbackSchemaRequest', - 'Schema', - 'ValidateMessageRequest', - 'ValidateMessageResponse', - 'ValidateSchemaRequest', - 'ValidateSchemaResponse', - 'Encoding', - 'SchemaView', -) diff --git a/owl-bot-staging/v1/google/pubsub_v1/types/pubsub.py b/owl-bot-staging/v1/google/pubsub_v1/types/pubsub.py deleted file mode 100644 index 4795fb6e5..000000000 --- a/owl-bot-staging/v1/google/pubsub_v1/types/pubsub.py +++ /dev/null @@ -1,2387 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - -from google.protobuf import duration_pb2 # type: ignore -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from google.pubsub_v1.types import schema as gp_schema - - -__protobuf__ = proto.module( - package='google.pubsub.v1', - manifest={ - 'MessageStoragePolicy', - 'SchemaSettings', - 'IngestionDataSourceSettings', - 'Topic', - 'PubsubMessage', - 'GetTopicRequest', - 'UpdateTopicRequest', - 'PublishRequest', - 'PublishResponse', - 'ListTopicsRequest', - 'ListTopicsResponse', - 'ListTopicSubscriptionsRequest', - 'ListTopicSubscriptionsResponse', - 'ListTopicSnapshotsRequest', - 'ListTopicSnapshotsResponse', - 'DeleteTopicRequest', - 'DetachSubscriptionRequest', - 'DetachSubscriptionResponse', - 'Subscription', - 'RetryPolicy', - 'DeadLetterPolicy', - 'ExpirationPolicy', - 'PushConfig', - 'BigQueryConfig', - 'CloudStorageConfig', - 'ReceivedMessage', - 'GetSubscriptionRequest', - 'UpdateSubscriptionRequest', - 'ListSubscriptionsRequest', - 'ListSubscriptionsResponse', - 'DeleteSubscriptionRequest', - 'ModifyPushConfigRequest', - 'PullRequest', - 'PullResponse', - 'ModifyAckDeadlineRequest', - 'AcknowledgeRequest', - 'StreamingPullRequest', - 'StreamingPullResponse', - 'CreateSnapshotRequest', - 'UpdateSnapshotRequest', - 'Snapshot', - 'GetSnapshotRequest', - 'ListSnapshotsRequest', - 'ListSnapshotsResponse', - 'DeleteSnapshotRequest', - 'SeekRequest', - 'SeekResponse', - }, -) - - -class MessageStoragePolicy(proto.Message): - r"""A policy constraining the storage of messages published to - the topic. - - Attributes: - allowed_persistence_regions (MutableSequence[str]): - Optional. A list of IDs of Google Cloud - regions where messages that are published to the - topic may be persisted in storage. Messages - published by publishers running in non-allowed - Google Cloud regions (or running outside of - Google Cloud altogether) are routed for storage - in one of the allowed regions. An empty list - means that no regions are allowed, and is not a - valid configuration. - enforce_in_transit (bool): - Optional. If true, ``allowed_persistence_regions`` is also - used to enforce in-transit guarantees for messages. That is, - Pub/Sub will fail Publish operations on this topic and - subscribe operations on any subscription attached to this - topic in any region that is not in - ``allowed_persistence_regions``. - """ - - allowed_persistence_regions: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=1, - ) - enforce_in_transit: bool = proto.Field( - proto.BOOL, - number=2, - ) - - -class SchemaSettings(proto.Message): - r"""Settings for validating messages published against a schema. - - Attributes: - schema (str): - Required. The name of the schema that messages published - should be validated against. Format is - ``projects/{project}/schemas/{schema}``. The value of this - field will be ``_deleted-schema_`` if the schema has been - deleted. - encoding (google.pubsub_v1.types.Encoding): - Optional. The encoding of messages validated against - ``schema``. - first_revision_id (str): - Optional. The minimum (inclusive) revision allowed for - validating messages. If empty or not present, allow any - revision to be validated against last_revision or any - revision created before. - last_revision_id (str): - Optional. The maximum (inclusive) revision allowed for - validating messages. If empty or not present, allow any - revision to be validated against first_revision or any - revision created after. - """ - - schema: str = proto.Field( - proto.STRING, - number=1, - ) - encoding: gp_schema.Encoding = proto.Field( - proto.ENUM, - number=2, - enum=gp_schema.Encoding, - ) - first_revision_id: str = proto.Field( - proto.STRING, - number=3, - ) - last_revision_id: str = proto.Field( - proto.STRING, - number=4, - ) - - -class IngestionDataSourceSettings(proto.Message): - r"""Settings for an ingestion data source on a topic. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - aws_kinesis (google.pubsub_v1.types.IngestionDataSourceSettings.AwsKinesis): - Optional. Amazon Kinesis Data Streams. - - This field is a member of `oneof`_ ``source``. - """ - - class AwsKinesis(proto.Message): - r"""Ingestion settings for Amazon Kinesis Data Streams. - - Attributes: - state (google.pubsub_v1.types.IngestionDataSourceSettings.AwsKinesis.State): - Output only. An output-only field that - indicates the state of the Kinesis ingestion - source. - stream_arn (str): - Required. The Kinesis stream ARN to ingest - data from. - consumer_arn (str): - Required. The Kinesis consumer ARN to used - for ingestion in Enhanced Fan-Out mode. The - consumer must be already created and ready to be - used. - aws_role_arn (str): - Required. AWS role ARN to be used for - Federated Identity authentication with Kinesis. - Check the Pub/Sub docs for how to set up this - role and the required permissions that need to - be attached to it. - gcp_service_account (str): - Required. The GCP service account to be used for Federated - Identity authentication with Kinesis (via a - ``AssumeRoleWithWebIdentity`` call for the provided role). - The ``aws_role_arn`` must be set up with - ``accounts.google.com:sub`` equals to this service account - number. - """ - class State(proto.Enum): - r"""Possible states for ingestion from Amazon Kinesis Data - Streams. - - Values: - STATE_UNSPECIFIED (0): - Default value. This value is unused. - ACTIVE (1): - Ingestion is active. - KINESIS_PERMISSION_DENIED (2): - Permission denied encountered while consuming data from - Kinesis. This can happen if: - - - The provided ``aws_role_arn`` does not exist or does not - have the appropriate permissions attached. - - The provided ``aws_role_arn`` is not set up properly for - Identity Federation using ``gcp_service_account``. - - The Pub/Sub SA is not granted the - ``iam.serviceAccounts.getOpenIdToken`` permission on - ``gcp_service_account``. - PUBLISH_PERMISSION_DENIED (3): - Permission denied encountered while publishing to the topic. - This can happen if the Pub/Sub SA has not been granted the - `appropriate publish - permissions `__ - STREAM_NOT_FOUND (4): - The Kinesis stream does not exist. - CONSUMER_NOT_FOUND (5): - The Kinesis consumer does not exist. - """ - STATE_UNSPECIFIED = 0 - ACTIVE = 1 - KINESIS_PERMISSION_DENIED = 2 - PUBLISH_PERMISSION_DENIED = 3 - STREAM_NOT_FOUND = 4 - CONSUMER_NOT_FOUND = 5 - - state: 'IngestionDataSourceSettings.AwsKinesis.State' = proto.Field( - proto.ENUM, - number=1, - enum='IngestionDataSourceSettings.AwsKinesis.State', - ) - stream_arn: str = proto.Field( - proto.STRING, - number=2, - ) - consumer_arn: str = proto.Field( - proto.STRING, - number=3, - ) - aws_role_arn: str = proto.Field( - proto.STRING, - number=4, - ) - gcp_service_account: str = proto.Field( - proto.STRING, - number=5, - ) - - aws_kinesis: AwsKinesis = proto.Field( - proto.MESSAGE, - number=1, - oneof='source', - message=AwsKinesis, - ) - - -class Topic(proto.Message): - r"""A topic resource. - - Attributes: - name (str): - Required. The name of the topic. It must have the format - ``"projects/{project}/topics/{topic}"``. ``{topic}`` must - start with a letter, and contain only letters - (``[A-Za-z]``), numbers (``[0-9]``), dashes (``-``), - underscores (``_``), periods (``.``), tildes (``~``), plus - (``+``) or percent signs (``%``). It must be between 3 and - 255 characters in length, and it must not start with - ``"goog"``. - labels (MutableMapping[str, str]): - Optional. See [Creating and managing labels] - (https://cloud.google.com/pubsub/docs/labels). - message_storage_policy (google.pubsub_v1.types.MessageStoragePolicy): - Optional. Policy constraining the set of - Google Cloud Platform regions where messages - published to the topic may be stored. If not - present, then no constraints are in effect. - kms_key_name (str): - Optional. The resource name of the Cloud KMS CryptoKey to be - used to protect access to messages published on this topic. - - The expected format is - ``projects/*/locations/*/keyRings/*/cryptoKeys/*``. - schema_settings (google.pubsub_v1.types.SchemaSettings): - Optional. Settings for validating messages - published against a schema. - satisfies_pzs (bool): - Optional. Reserved for future use. This field - is set only in responses from the server; it is - ignored if it is set in any requests. - message_retention_duration (google.protobuf.duration_pb2.Duration): - Optional. Indicates the minimum duration to retain a message - after it is published to the topic. If this field is set, - messages published to the topic in the last - ``message_retention_duration`` are always available to - subscribers. For instance, it allows any attached - subscription to `seek to a - timestamp `__ - that is up to ``message_retention_duration`` in the past. If - this field is not set, message retention is controlled by - settings on individual subscriptions. Cannot be more than 31 - days or less than 10 minutes. - state (google.pubsub_v1.types.Topic.State): - Output only. An output-only field indicating - the state of the topic. - ingestion_data_source_settings (google.pubsub_v1.types.IngestionDataSourceSettings): - Optional. Settings for ingestion from a data - source into this topic. - """ - class State(proto.Enum): - r"""The state of the topic. - - Values: - STATE_UNSPECIFIED (0): - Default value. This value is unused. - ACTIVE (1): - The topic does not have any persistent - errors. - INGESTION_RESOURCE_ERROR (2): - Ingestion from the data source has - encountered a permanent error. See the more - detailed error state in the corresponding - ingestion source configuration. - """ - STATE_UNSPECIFIED = 0 - ACTIVE = 1 - INGESTION_RESOURCE_ERROR = 2 - - name: str = proto.Field( - proto.STRING, - number=1, - ) - labels: MutableMapping[str, str] = proto.MapField( - proto.STRING, - proto.STRING, - number=2, - ) - message_storage_policy: 'MessageStoragePolicy' = proto.Field( - proto.MESSAGE, - number=3, - message='MessageStoragePolicy', - ) - kms_key_name: str = proto.Field( - proto.STRING, - number=5, - ) - schema_settings: 'SchemaSettings' = proto.Field( - proto.MESSAGE, - number=6, - message='SchemaSettings', - ) - satisfies_pzs: bool = proto.Field( - proto.BOOL, - number=7, - ) - message_retention_duration: duration_pb2.Duration = proto.Field( - proto.MESSAGE, - number=8, - message=duration_pb2.Duration, - ) - state: State = proto.Field( - proto.ENUM, - number=9, - enum=State, - ) - ingestion_data_source_settings: 'IngestionDataSourceSettings' = proto.Field( - proto.MESSAGE, - number=10, - message='IngestionDataSourceSettings', - ) - - -class PubsubMessage(proto.Message): - r"""A message that is published by publishers and consumed by - subscribers. The message must contain either a non-empty data field - or at least one attribute. Note that client libraries represent this - object differently depending on the language. See the corresponding - `client library - documentation `__ - for more information. See [quotas and limits] - (https://cloud.google.com/pubsub/quotas) for more information about - message limits. - - Attributes: - data (bytes): - Optional. The message data field. If this - field is empty, the message must contain at - least one attribute. - attributes (MutableMapping[str, str]): - Optional. Attributes for this message. If - this field is empty, the message must contain - non-empty data. This can be used to filter - messages on the subscription. - message_id (str): - ID of this message, assigned by the server when the message - is published. Guaranteed to be unique within the topic. This - value may be read by a subscriber that receives a - ``PubsubMessage`` via a ``Pull`` call or a push delivery. It - must not be populated by the publisher in a ``Publish`` - call. - publish_time (google.protobuf.timestamp_pb2.Timestamp): - The time at which the message was published, populated by - the server when it receives the ``Publish`` call. It must - not be populated by the publisher in a ``Publish`` call. - ordering_key (str): - Optional. If non-empty, identifies related messages for - which publish order should be respected. If a - ``Subscription`` has ``enable_message_ordering`` set to - ``true``, messages published with the same non-empty - ``ordering_key`` value will be delivered to subscribers in - the order in which they are received by the Pub/Sub system. - All ``PubsubMessage``\ s published in a given - ``PublishRequest`` must specify the same ``ordering_key`` - value. For more information, see `ordering - messages `__. - """ - - data: bytes = proto.Field( - proto.BYTES, - number=1, - ) - attributes: MutableMapping[str, str] = proto.MapField( - proto.STRING, - proto.STRING, - number=2, - ) - message_id: str = proto.Field( - proto.STRING, - number=3, - ) - publish_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=4, - message=timestamp_pb2.Timestamp, - ) - ordering_key: str = proto.Field( - proto.STRING, - number=5, - ) - - -class GetTopicRequest(proto.Message): - r"""Request for the GetTopic method. - - Attributes: - topic (str): - Required. The name of the topic to get. Format is - ``projects/{project}/topics/{topic}``. - """ - - topic: str = proto.Field( - proto.STRING, - number=1, - ) - - -class UpdateTopicRequest(proto.Message): - r"""Request for the UpdateTopic method. - - Attributes: - topic (google.pubsub_v1.types.Topic): - Required. The updated topic object. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Required. Indicates which fields in the provided topic to - update. Must be specified and non-empty. Note that if - ``update_mask`` contains "message_storage_policy" but the - ``message_storage_policy`` is not set in the ``topic`` - provided above, then the updated value is determined by the - policy configured at the project or organization level. - """ - - topic: 'Topic' = proto.Field( - proto.MESSAGE, - number=1, - message='Topic', - ) - update_mask: field_mask_pb2.FieldMask = proto.Field( - proto.MESSAGE, - number=2, - message=field_mask_pb2.FieldMask, - ) - - -class PublishRequest(proto.Message): - r"""Request for the Publish method. - - Attributes: - topic (str): - Required. The messages in the request will be published on - this topic. Format is ``projects/{project}/topics/{topic}``. - messages (MutableSequence[google.pubsub_v1.types.PubsubMessage]): - Required. The messages to publish. - """ - - topic: str = proto.Field( - proto.STRING, - number=1, - ) - messages: MutableSequence['PubsubMessage'] = proto.RepeatedField( - proto.MESSAGE, - number=2, - message='PubsubMessage', - ) - - -class PublishResponse(proto.Message): - r"""Response for the ``Publish`` method. - - Attributes: - message_ids (MutableSequence[str]): - Optional. The server-assigned ID of each - published message, in the same order as the - messages in the request. IDs are guaranteed to - be unique within the topic. - """ - - message_ids: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=1, - ) - - -class ListTopicsRequest(proto.Message): - r"""Request for the ``ListTopics`` method. - - Attributes: - project (str): - Required. The name of the project in which to list topics. - Format is ``projects/{project-id}``. - page_size (int): - Optional. Maximum number of topics to return. - page_token (str): - Optional. The value returned by the last - ``ListTopicsResponse``; indicates that this is a - continuation of a prior ``ListTopics`` call, and that the - system should return the next page of data. - """ - - project: 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 ListTopicsResponse(proto.Message): - r"""Response for the ``ListTopics`` method. - - Attributes: - topics (MutableSequence[google.pubsub_v1.types.Topic]): - Optional. The resulting topics. - next_page_token (str): - Optional. If not empty, indicates that there may be more - topics that match the request; this value should be passed - in a new ``ListTopicsRequest``. - """ - - @property - def raw_page(self): - return self - - topics: MutableSequence['Topic'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='Topic', - ) - next_page_token: str = proto.Field( - proto.STRING, - number=2, - ) - - -class ListTopicSubscriptionsRequest(proto.Message): - r"""Request for the ``ListTopicSubscriptions`` method. - - Attributes: - topic (str): - Required. The name of the topic that subscriptions are - attached to. Format is - ``projects/{project}/topics/{topic}``. - page_size (int): - Optional. Maximum number of subscription - names to return. - page_token (str): - Optional. The value returned by the last - ``ListTopicSubscriptionsResponse``; indicates that this is a - continuation of a prior ``ListTopicSubscriptions`` call, and - that the system should return the next page of data. - """ - - topic: 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 ListTopicSubscriptionsResponse(proto.Message): - r"""Response for the ``ListTopicSubscriptions`` method. - - Attributes: - subscriptions (MutableSequence[str]): - Optional. The names of subscriptions attached - to the topic specified in the request. - next_page_token (str): - Optional. If not empty, indicates that there may be more - subscriptions that match the request; this value should be - passed in a new ``ListTopicSubscriptionsRequest`` to get - more subscriptions. - """ - - @property - def raw_page(self): - return self - - subscriptions: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=1, - ) - next_page_token: str = proto.Field( - proto.STRING, - number=2, - ) - - -class ListTopicSnapshotsRequest(proto.Message): - r"""Request for the ``ListTopicSnapshots`` method. - - Attributes: - topic (str): - Required. The name of the topic that snapshots are attached - to. Format is ``projects/{project}/topics/{topic}``. - page_size (int): - Optional. Maximum number of snapshot names to - return. - page_token (str): - Optional. The value returned by the last - ``ListTopicSnapshotsResponse``; indicates that this is a - continuation of a prior ``ListTopicSnapshots`` call, and - that the system should return the next page of data. - """ - - topic: 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 ListTopicSnapshotsResponse(proto.Message): - r"""Response for the ``ListTopicSnapshots`` method. - - Attributes: - snapshots (MutableSequence[str]): - Optional. The names of the snapshots that - match the request. - next_page_token (str): - Optional. If not empty, indicates that there may be more - snapshots that match the request; this value should be - passed in a new ``ListTopicSnapshotsRequest`` to get more - snapshots. - """ - - @property - def raw_page(self): - return self - - snapshots: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=1, - ) - next_page_token: str = proto.Field( - proto.STRING, - number=2, - ) - - -class DeleteTopicRequest(proto.Message): - r"""Request for the ``DeleteTopic`` method. - - Attributes: - topic (str): - Required. Name of the topic to delete. Format is - ``projects/{project}/topics/{topic}``. - """ - - topic: str = proto.Field( - proto.STRING, - number=1, - ) - - -class DetachSubscriptionRequest(proto.Message): - r"""Request for the DetachSubscription method. - - Attributes: - subscription (str): - Required. The subscription to detach. Format is - ``projects/{project}/subscriptions/{subscription}``. - """ - - subscription: str = proto.Field( - proto.STRING, - number=1, - ) - - -class DetachSubscriptionResponse(proto.Message): - r"""Response for the DetachSubscription method. - Reserved for future use. - - """ - - -class Subscription(proto.Message): - r"""A subscription resource. If none of ``push_config``, - ``bigquery_config``, or ``cloud_storage_config`` is set, then the - subscriber will pull and ack messages using API methods. At most one - of these fields may be set. - - Attributes: - name (str): - Required. The name of the subscription. It must have the - format - ``"projects/{project}/subscriptions/{subscription}"``. - ``{subscription}`` must start with a letter, and contain - only letters (``[A-Za-z]``), numbers (``[0-9]``), dashes - (``-``), underscores (``_``), periods (``.``), tildes - (``~``), plus (``+``) or percent signs (``%``). It must be - between 3 and 255 characters in length, and it must not - start with ``"goog"``. - topic (str): - Required. The name of the topic from which this subscription - is receiving messages. Format is - ``projects/{project}/topics/{topic}``. The value of this - field will be ``_deleted-topic_`` if the topic has been - deleted. - push_config (google.pubsub_v1.types.PushConfig): - Optional. If push delivery is used with this - subscription, this field is used to configure - it. - bigquery_config (google.pubsub_v1.types.BigQueryConfig): - Optional. If delivery to BigQuery is used - with this subscription, this field is used to - configure it. - cloud_storage_config (google.pubsub_v1.types.CloudStorageConfig): - Optional. If delivery to Google Cloud Storage - is used with this subscription, this field is - used to configure it. - ack_deadline_seconds (int): - Optional. The approximate amount of time (on a best-effort - basis) Pub/Sub waits for the subscriber to acknowledge - receipt before resending the message. In the interval after - the message is delivered and before it is acknowledged, it - is considered to be *outstanding*. During that time period, - the message will not be redelivered (on a best-effort - basis). - - For pull subscriptions, this value is used as the initial - value for the ack deadline. To override this value for a - given message, call ``ModifyAckDeadline`` with the - corresponding ``ack_id`` if using non-streaming pull or send - the ``ack_id`` in a ``StreamingModifyAckDeadlineRequest`` if - using streaming pull. The minimum custom deadline you can - specify is 10 seconds. The maximum custom deadline you can - specify is 600 seconds (10 minutes). If this parameter is 0, - a default value of 10 seconds is used. - - For push delivery, this value is also used to set the - request timeout for the call to the push endpoint. - - If the subscriber never acknowledges the message, the - Pub/Sub system will eventually redeliver the message. - retain_acked_messages (bool): - Optional. Indicates whether to retain acknowledged messages. - If true, then messages are not expunged from the - subscription's backlog, even if they are acknowledged, until - they fall out of the ``message_retention_duration`` window. - This must be true if you would like to [``Seek`` to a - timestamp] - (https://cloud.google.com/pubsub/docs/replay-overview#seek_to_a_time) - in the past to replay previously-acknowledged messages. - message_retention_duration (google.protobuf.duration_pb2.Duration): - Optional. How long to retain unacknowledged messages in the - subscription's backlog, from the moment a message is - published. If ``retain_acked_messages`` is true, then this - also configures the retention of acknowledged messages, and - thus configures how far back in time a ``Seek`` can be done. - Defaults to 7 days. Cannot be more than 31 days or less than - 10 minutes. - labels (MutableMapping[str, str]): - Optional. See `Creating and managing - labels `__. - enable_message_ordering (bool): - Optional. If true, messages published with the same - ``ordering_key`` in ``PubsubMessage`` will be delivered to - the subscribers in the order in which they are received by - the Pub/Sub system. Otherwise, they may be delivered in any - order. - expiration_policy (google.pubsub_v1.types.ExpirationPolicy): - Optional. A policy that specifies the conditions for this - subscription's expiration. A subscription is considered - active as long as any connected subscriber is successfully - consuming messages from the subscription or is issuing - operations on the subscription. If ``expiration_policy`` is - not set, a *default policy* with ``ttl`` of 31 days will be - used. The minimum allowed value for - ``expiration_policy.ttl`` is 1 day. If ``expiration_policy`` - is set, but ``expiration_policy.ttl`` is not set, the - subscription never expires. - filter (str): - Optional. An expression written in the Pub/Sub `filter - language `__. - If non-empty, then only ``PubsubMessage``\ s whose - ``attributes`` field matches the filter are delivered on - this subscription. If empty, then no messages are filtered - out. - dead_letter_policy (google.pubsub_v1.types.DeadLetterPolicy): - Optional. A policy that specifies the conditions for dead - lettering messages in this subscription. If - dead_letter_policy is not set, dead lettering is disabled. - - The Pub/Sub service account associated with this - subscriptions's parent project (i.e., - service-{project_number}@gcp-sa-pubsub.iam.gserviceaccount.com) - must have permission to Acknowledge() messages on this - subscription. - retry_policy (google.pubsub_v1.types.RetryPolicy): - Optional. A policy that specifies how Pub/Sub - retries message delivery for this subscription. - - If not set, the default retry policy is applied. - This generally implies that messages will be - retried as soon as possible for healthy - subscribers. RetryPolicy will be triggered on - NACKs or acknowledgement deadline exceeded - events for a given message. - detached (bool): - Optional. Indicates whether the subscription is detached - from its topic. Detached subscriptions don't receive - messages from their topic and don't retain any backlog. - ``Pull`` and ``StreamingPull`` requests will return - FAILED_PRECONDITION. If the subscription is a push - subscription, pushes to the endpoint will not be made. - enable_exactly_once_delivery (bool): - Optional. If true, Pub/Sub provides the following guarantees - for the delivery of a message with a given value of - ``message_id`` on this subscription: - - - The message sent to a subscriber is guaranteed not to be - resent before the message's acknowledgement deadline - expires. - - An acknowledged message will not be resent to a - subscriber. - - Note that subscribers may still receive multiple copies of a - message when ``enable_exactly_once_delivery`` is true if the - message was published multiple times by a publisher client. - These copies are considered distinct by Pub/Sub and have - distinct ``message_id`` values. - topic_message_retention_duration (google.protobuf.duration_pb2.Duration): - Output only. Indicates the minimum duration for which a - message is retained after it is published to the - subscription's topic. If this field is set, messages - published to the subscription's topic in the last - ``topic_message_retention_duration`` are always available to - subscribers. See the ``message_retention_duration`` field in - ``Topic``. This field is set only in responses from the - server; it is ignored if it is set in any requests. - state (google.pubsub_v1.types.Subscription.State): - Output only. An output-only field indicating - whether or not the subscription can receive - messages. - """ - class State(proto.Enum): - r"""Possible states for a subscription. - - Values: - STATE_UNSPECIFIED (0): - Default value. This value is unused. - ACTIVE (1): - The subscription can actively receive - messages - RESOURCE_ERROR (2): - The subscription cannot receive messages - because of an error with the resource to which - it pushes messages. See the more detailed error - state in the corresponding configuration. - """ - STATE_UNSPECIFIED = 0 - ACTIVE = 1 - RESOURCE_ERROR = 2 - - name: str = proto.Field( - proto.STRING, - number=1, - ) - topic: str = proto.Field( - proto.STRING, - number=2, - ) - push_config: 'PushConfig' = proto.Field( - proto.MESSAGE, - number=4, - message='PushConfig', - ) - bigquery_config: 'BigQueryConfig' = proto.Field( - proto.MESSAGE, - number=18, - message='BigQueryConfig', - ) - cloud_storage_config: 'CloudStorageConfig' = proto.Field( - proto.MESSAGE, - number=22, - message='CloudStorageConfig', - ) - ack_deadline_seconds: int = proto.Field( - proto.INT32, - number=5, - ) - retain_acked_messages: bool = proto.Field( - proto.BOOL, - number=7, - ) - message_retention_duration: duration_pb2.Duration = proto.Field( - proto.MESSAGE, - number=8, - message=duration_pb2.Duration, - ) - labels: MutableMapping[str, str] = proto.MapField( - proto.STRING, - proto.STRING, - number=9, - ) - enable_message_ordering: bool = proto.Field( - proto.BOOL, - number=10, - ) - expiration_policy: 'ExpirationPolicy' = proto.Field( - proto.MESSAGE, - number=11, - message='ExpirationPolicy', - ) - filter: str = proto.Field( - proto.STRING, - number=12, - ) - dead_letter_policy: 'DeadLetterPolicy' = proto.Field( - proto.MESSAGE, - number=13, - message='DeadLetterPolicy', - ) - retry_policy: 'RetryPolicy' = proto.Field( - proto.MESSAGE, - number=14, - message='RetryPolicy', - ) - detached: bool = proto.Field( - proto.BOOL, - number=15, - ) - enable_exactly_once_delivery: bool = proto.Field( - proto.BOOL, - number=16, - ) - topic_message_retention_duration: duration_pb2.Duration = proto.Field( - proto.MESSAGE, - number=17, - message=duration_pb2.Duration, - ) - state: State = proto.Field( - proto.ENUM, - number=19, - enum=State, - ) - - -class RetryPolicy(proto.Message): - r"""A policy that specifies how Pub/Sub retries message delivery. - - Retry delay will be exponential based on provided minimum and - maximum backoffs. https://en.wikipedia.org/wiki/Exponential_backoff. - - RetryPolicy will be triggered on NACKs or acknowledgement deadline - exceeded events for a given message. - - Retry Policy is implemented on a best effort basis. At times, the - delay between consecutive deliveries may not match the - configuration. That is, delay can be more or less than configured - backoff. - - Attributes: - minimum_backoff (google.protobuf.duration_pb2.Duration): - Optional. The minimum delay between - consecutive deliveries of a given message. Value - should be between 0 and 600 seconds. Defaults to - 10 seconds. - maximum_backoff (google.protobuf.duration_pb2.Duration): - Optional. The maximum delay between - consecutive deliveries of a given message. Value - should be between 0 and 600 seconds. Defaults to - 600 seconds. - """ - - minimum_backoff: duration_pb2.Duration = proto.Field( - proto.MESSAGE, - number=1, - message=duration_pb2.Duration, - ) - maximum_backoff: duration_pb2.Duration = proto.Field( - proto.MESSAGE, - number=2, - message=duration_pb2.Duration, - ) - - -class DeadLetterPolicy(proto.Message): - r"""Dead lettering is done on a best effort basis. The same - message might be dead lettered multiple times. - - If validation on any of the fields fails at subscription - creation/updation, the create/update subscription request will - fail. - - Attributes: - dead_letter_topic (str): - Optional. The name of the topic to which dead letter - messages should be published. Format is - ``projects/{project}/topics/{topic}``.The Pub/Sub service - account associated with the enclosing subscription's parent - project (i.e., - service-{project_number}@gcp-sa-pubsub.iam.gserviceaccount.com) - must have permission to Publish() to this topic. - - The operation will fail if the topic does not exist. Users - should ensure that there is a subscription attached to this - topic since messages published to a topic with no - subscriptions are lost. - max_delivery_attempts (int): - Optional. The maximum number of delivery attempts for any - message. The value must be between 5 and 100. - - The number of delivery attempts is defined as 1 + (the sum - of number of NACKs and number of times the acknowledgement - deadline has been exceeded for the message). - - A NACK is any call to ModifyAckDeadline with a 0 deadline. - Note that client libraries may automatically extend - ack_deadlines. - - This field will be honored on a best effort basis. - - If this parameter is 0, a default value of 5 is used. - """ - - dead_letter_topic: str = proto.Field( - proto.STRING, - number=1, - ) - max_delivery_attempts: int = proto.Field( - proto.INT32, - number=2, - ) - - -class ExpirationPolicy(proto.Message): - r"""A policy that specifies the conditions for resource - expiration (i.e., automatic resource deletion). - - Attributes: - ttl (google.protobuf.duration_pb2.Duration): - Optional. Specifies the "time-to-live" duration for an - associated resource. The resource expires if it is not - active for a period of ``ttl``. The definition of "activity" - depends on the type of the associated resource. The minimum - and maximum allowed values for ``ttl`` depend on the type of - the associated resource, as well. If ``ttl`` is not set, the - associated resource never expires. - """ - - ttl: duration_pb2.Duration = proto.Field( - proto.MESSAGE, - number=1, - message=duration_pb2.Duration, - ) - - -class PushConfig(proto.Message): - r"""Configuration for a push delivery endpoint. - - 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: - push_endpoint (str): - Optional. A URL locating the endpoint to which messages - should be pushed. For example, a Webhook endpoint might use - ``https://example.com/push``. - attributes (MutableMapping[str, str]): - Optional. Endpoint configuration attributes that can be used - to control different aspects of the message delivery. - - The only currently supported attribute is - ``x-goog-version``, which you can use to change the format - of the pushed message. This attribute indicates the version - of the data expected by the endpoint. This controls the - shape of the pushed message (i.e., its fields and metadata). - - If not present during the ``CreateSubscription`` call, it - will default to the version of the Pub/Sub API used to make - such call. If not present in a ``ModifyPushConfig`` call, - its value will not be changed. ``GetSubscription`` calls - will always return a valid version, even if the subscription - was created without this attribute. - - The only supported values for the ``x-goog-version`` - attribute are: - - - ``v1beta1``: uses the push format defined in the v1beta1 - Pub/Sub API. - - ``v1`` or ``v1beta2``: uses the push format defined in - the v1 Pub/Sub API. - - For example: ``attributes { "x-goog-version": "v1" }`` - oidc_token (google.pubsub_v1.types.PushConfig.OidcToken): - Optional. If specified, Pub/Sub will generate and attach an - OIDC JWT token as an ``Authorization`` header in the HTTP - request for every pushed message. - - This field is a member of `oneof`_ ``authentication_method``. - pubsub_wrapper (google.pubsub_v1.types.PushConfig.PubsubWrapper): - Optional. When set, the payload to the push - endpoint is in the form of the JSON - representation of a PubsubMessage - (https://cloud.google.com/pubsub/docs/reference/rpc/google.pubsub.v1#pubsubmessage). - - This field is a member of `oneof`_ ``wrapper``. - no_wrapper (google.pubsub_v1.types.PushConfig.NoWrapper): - Optional. When set, the payload to the push - endpoint is not wrapped. - - This field is a member of `oneof`_ ``wrapper``. - """ - - class OidcToken(proto.Message): - r"""Contains information needed for generating an `OpenID Connect - token `__. - - Attributes: - service_account_email (str): - Optional. `Service account - email `__ - used for generating the OIDC token. For more information on - setting up authentication, see `Push - subscriptions `__. - audience (str): - Optional. Audience to be used when generating - OIDC token. The audience claim identifies the - recipients that the JWT is intended for. The - audience value is a single case-sensitive - string. Having multiple values (array) for the - audience field is not supported. More info about - the OIDC JWT token audience here: - - https://tools.ietf.org/html/rfc7519#section-4.1.3 - Note: if not specified, the Push endpoint URL - will be used. - """ - - service_account_email: str = proto.Field( - proto.STRING, - number=1, - ) - audience: str = proto.Field( - proto.STRING, - number=2, - ) - - class PubsubWrapper(proto.Message): - r"""The payload to the push endpoint is in the form of the JSON - representation of a PubsubMessage - (https://cloud.google.com/pubsub/docs/reference/rpc/google.pubsub.v1#pubsubmessage). - - """ - - class NoWrapper(proto.Message): - r"""Sets the ``data`` field as the HTTP body for delivery. - - Attributes: - write_metadata (bool): - Optional. When true, writes the Pub/Sub message metadata to - ``x-goog-pubsub-:`` headers of the HTTP request. - Writes the Pub/Sub message attributes to ``:`` - headers of the HTTP request. - """ - - write_metadata: bool = proto.Field( - proto.BOOL, - number=1, - ) - - push_endpoint: str = proto.Field( - proto.STRING, - number=1, - ) - attributes: MutableMapping[str, str] = proto.MapField( - proto.STRING, - proto.STRING, - number=2, - ) - oidc_token: OidcToken = proto.Field( - proto.MESSAGE, - number=3, - oneof='authentication_method', - message=OidcToken, - ) - pubsub_wrapper: PubsubWrapper = proto.Field( - proto.MESSAGE, - number=4, - oneof='wrapper', - message=PubsubWrapper, - ) - no_wrapper: NoWrapper = proto.Field( - proto.MESSAGE, - number=5, - oneof='wrapper', - message=NoWrapper, - ) - - -class BigQueryConfig(proto.Message): - r"""Configuration for a BigQuery subscription. - - Attributes: - table (str): - Optional. The name of the table to which to - write data, of the form - {projectId}.{datasetId}.{tableId} - use_topic_schema (bool): - Optional. When true, use the topic's schema as the columns - to write to in BigQuery, if it exists. ``use_topic_schema`` - and ``use_table_schema`` cannot be enabled at the same time. - write_metadata (bool): - Optional. When true, write the subscription name, - message_id, publish_time, attributes, and ordering_key to - additional columns in the table. The subscription name, - message_id, and publish_time fields are put in their own - columns while all other message properties (other than data) - are written to a JSON object in the attributes column. - drop_unknown_fields (bool): - Optional. When true and use_topic_schema is true, any fields - that are a part of the topic schema that are not part of the - BigQuery table schema are dropped when writing to BigQuery. - Otherwise, the schemas must be kept in sync and any messages - with extra fields are not written and remain in the - subscription's backlog. - state (google.pubsub_v1.types.BigQueryConfig.State): - Output only. An output-only field that - indicates whether or not the subscription can - receive messages. - use_table_schema (bool): - Optional. When true, use the BigQuery table's schema as the - columns to write to in BigQuery. ``use_table_schema`` and - ``use_topic_schema`` cannot be enabled at the same time. - service_account_email (str): - Optional. The service account to use to write to BigQuery. - The subscription creator or updater that specifies this - field must have ``iam.serviceAccounts.actAs`` permission on - the service account. If not specified, the Pub/Sub `service - agent `__, - service-{project_number}@gcp-sa-pubsub.iam.gserviceaccount.com, - is used. - """ - class State(proto.Enum): - r"""Possible states for a BigQuery subscription. - - Values: - STATE_UNSPECIFIED (0): - Default value. This value is unused. - ACTIVE (1): - The subscription can actively send messages - to BigQuery - PERMISSION_DENIED (2): - Cannot write to the BigQuery table because of permission - denied errors. This can happen if - - - Pub/Sub SA has not been granted the `appropriate BigQuery - IAM - permissions `__ - - bigquery.googleapis.com API is not enabled for the - project - (`instructions `__) - NOT_FOUND (3): - Cannot write to the BigQuery table because it - does not exist. - SCHEMA_MISMATCH (4): - Cannot write to the BigQuery table due to a - schema mismatch. - IN_TRANSIT_LOCATION_RESTRICTION (5): - Cannot write to the destination because enforce_in_transit - is set to true and the destination locations are not in the - allowed regions. - """ - STATE_UNSPECIFIED = 0 - ACTIVE = 1 - PERMISSION_DENIED = 2 - NOT_FOUND = 3 - SCHEMA_MISMATCH = 4 - IN_TRANSIT_LOCATION_RESTRICTION = 5 - - table: str = proto.Field( - proto.STRING, - number=1, - ) - use_topic_schema: bool = proto.Field( - proto.BOOL, - number=2, - ) - write_metadata: bool = proto.Field( - proto.BOOL, - number=3, - ) - drop_unknown_fields: bool = proto.Field( - proto.BOOL, - number=4, - ) - state: State = proto.Field( - proto.ENUM, - number=5, - enum=State, - ) - use_table_schema: bool = proto.Field( - proto.BOOL, - number=6, - ) - service_account_email: str = proto.Field( - proto.STRING, - number=7, - ) - - -class CloudStorageConfig(proto.Message): - r"""Configuration for a Cloud Storage subscription. - - 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: - bucket (str): - Required. User-provided name for the Cloud Storage bucket. - The bucket must be created by the user. The bucket name must - be without any prefix like "gs://". See the [bucket naming - requirements] - (https://cloud.google.com/storage/docs/buckets#naming). - filename_prefix (str): - Optional. User-provided prefix for Cloud Storage filename. - See the `object naming - requirements `__. - filename_suffix (str): - Optional. User-provided suffix for Cloud Storage filename. - See the `object naming - requirements `__. - Must not end in "/". - filename_datetime_format (str): - Optional. User-provided format string specifying how to - represent datetimes in Cloud Storage filenames. See the - `datetime format - guidance `__. - text_config (google.pubsub_v1.types.CloudStorageConfig.TextConfig): - Optional. If set, message data will be - written to Cloud Storage in text format. - - This field is a member of `oneof`_ ``output_format``. - avro_config (google.pubsub_v1.types.CloudStorageConfig.AvroConfig): - Optional. If set, message data will be - written to Cloud Storage in Avro format. - - This field is a member of `oneof`_ ``output_format``. - max_duration (google.protobuf.duration_pb2.Duration): - Optional. The maximum duration that can - elapse before a new Cloud Storage file is - created. Min 1 minute, max 10 minutes, default 5 - minutes. May not exceed the subscription's - acknowledgement deadline. - max_bytes (int): - Optional. The maximum bytes that can be written to a Cloud - Storage file before a new file is created. Min 1 KB, max 10 - GiB. The max_bytes limit may be exceeded in cases where - messages are larger than the limit. - max_messages (int): - Optional. The maximum number of messages that - can be written to a Cloud Storage file before a - new file is created. Min 1000 messages. - state (google.pubsub_v1.types.CloudStorageConfig.State): - Output only. An output-only field that - indicates whether or not the subscription can - receive messages. - service_account_email (str): - Optional. The service account to use to write to Cloud - Storage. The subscription creator or updater that specifies - this field must have ``iam.serviceAccounts.actAs`` - permission on the service account. If not specified, the - Pub/Sub `service - agent `__, - service-{project_number}@gcp-sa-pubsub.iam.gserviceaccount.com, - is used. - """ - class State(proto.Enum): - r"""Possible states for a Cloud Storage subscription. - - Values: - STATE_UNSPECIFIED (0): - Default value. This value is unused. - ACTIVE (1): - The subscription can actively send messages - to Cloud Storage. - PERMISSION_DENIED (2): - Cannot write to the Cloud Storage bucket - because of permission denied errors. - NOT_FOUND (3): - Cannot write to the Cloud Storage bucket - because it does not exist. - IN_TRANSIT_LOCATION_RESTRICTION (4): - Cannot write to the destination because enforce_in_transit - is set to true and the destination locations are not in the - allowed regions. - SCHEMA_MISMATCH (5): - Cannot write to the Cloud Storage bucket due - to an incompatibility between the topic schema - and subscription settings. - """ - STATE_UNSPECIFIED = 0 - ACTIVE = 1 - PERMISSION_DENIED = 2 - NOT_FOUND = 3 - IN_TRANSIT_LOCATION_RESTRICTION = 4 - SCHEMA_MISMATCH = 5 - - class TextConfig(proto.Message): - r"""Configuration for writing message data in text format. - Message payloads will be written to files as raw text, separated - by a newline. - - """ - - class AvroConfig(proto.Message): - r"""Configuration for writing message data in Avro format. - Message payloads and metadata will be written to files as an - Avro binary. - - Attributes: - write_metadata (bool): - Optional. When true, write the subscription name, - message_id, publish_time, attributes, and ordering_key as - additional fields in the output. The subscription name, - message_id, and publish_time fields are put in their own - fields while all other message properties other than data - (for example, an ordering_key, if present) are added as - entries in the attributes map. - use_topic_schema (bool): - Optional. When true, the output Cloud Storage - file will be serialized using the topic schema, - if it exists. - """ - - write_metadata: bool = proto.Field( - proto.BOOL, - number=1, - ) - use_topic_schema: bool = proto.Field( - proto.BOOL, - number=2, - ) - - bucket: str = proto.Field( - proto.STRING, - number=1, - ) - filename_prefix: str = proto.Field( - proto.STRING, - number=2, - ) - filename_suffix: str = proto.Field( - proto.STRING, - number=3, - ) - filename_datetime_format: str = proto.Field( - proto.STRING, - number=10, - ) - text_config: TextConfig = proto.Field( - proto.MESSAGE, - number=4, - oneof='output_format', - message=TextConfig, - ) - avro_config: AvroConfig = proto.Field( - proto.MESSAGE, - number=5, - oneof='output_format', - message=AvroConfig, - ) - max_duration: duration_pb2.Duration = proto.Field( - proto.MESSAGE, - number=6, - message=duration_pb2.Duration, - ) - max_bytes: int = proto.Field( - proto.INT64, - number=7, - ) - max_messages: int = proto.Field( - proto.INT64, - number=8, - ) - state: State = proto.Field( - proto.ENUM, - number=9, - enum=State, - ) - service_account_email: str = proto.Field( - proto.STRING, - number=11, - ) - - -class ReceivedMessage(proto.Message): - r"""A message and its corresponding acknowledgment ID. - - Attributes: - ack_id (str): - Optional. This ID can be used to acknowledge - the received message. - message (google.pubsub_v1.types.PubsubMessage): - Optional. The message. - delivery_attempt (int): - Optional. The approximate number of times that Pub/Sub has - attempted to deliver the associated message to a subscriber. - - More precisely, this is 1 + (number of NACKs) + (number of - ack_deadline exceeds) for this message. - - A NACK is any call to ModifyAckDeadline with a 0 deadline. - An ack_deadline exceeds event is whenever a message is not - acknowledged within ack_deadline. Note that ack_deadline is - initially Subscription.ackDeadlineSeconds, but may get - extended automatically by the client library. - - Upon the first delivery of a given message, - ``delivery_attempt`` will have a value of 1. The value is - calculated at best effort and is approximate. - - If a DeadLetterPolicy is not set on the subscription, this - will be 0. - """ - - ack_id: str = proto.Field( - proto.STRING, - number=1, - ) - message: 'PubsubMessage' = proto.Field( - proto.MESSAGE, - number=2, - message='PubsubMessage', - ) - delivery_attempt: int = proto.Field( - proto.INT32, - number=3, - ) - - -class GetSubscriptionRequest(proto.Message): - r"""Request for the GetSubscription method. - - Attributes: - subscription (str): - Required. The name of the subscription to get. Format is - ``projects/{project}/subscriptions/{sub}``. - """ - - subscription: str = proto.Field( - proto.STRING, - number=1, - ) - - -class UpdateSubscriptionRequest(proto.Message): - r"""Request for the UpdateSubscription method. - - Attributes: - subscription (google.pubsub_v1.types.Subscription): - Required. The updated subscription object. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Required. Indicates which fields in the - provided subscription to update. Must be - specified and non-empty. - """ - - subscription: 'Subscription' = proto.Field( - proto.MESSAGE, - number=1, - message='Subscription', - ) - update_mask: field_mask_pb2.FieldMask = proto.Field( - proto.MESSAGE, - number=2, - message=field_mask_pb2.FieldMask, - ) - - -class ListSubscriptionsRequest(proto.Message): - r"""Request for the ``ListSubscriptions`` method. - - Attributes: - project (str): - Required. The name of the project in which to list - subscriptions. Format is ``projects/{project-id}``. - page_size (int): - Optional. Maximum number of subscriptions to - return. - page_token (str): - Optional. The value returned by the last - ``ListSubscriptionsResponse``; indicates that this is a - continuation of a prior ``ListSubscriptions`` call, and that - the system should return the next page of data. - """ - - project: 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 ListSubscriptionsResponse(proto.Message): - r"""Response for the ``ListSubscriptions`` method. - - Attributes: - subscriptions (MutableSequence[google.pubsub_v1.types.Subscription]): - Optional. The subscriptions that match the - request. - next_page_token (str): - Optional. If not empty, indicates that there may be more - subscriptions that match the request; this value should be - passed in a new ``ListSubscriptionsRequest`` to get more - subscriptions. - """ - - @property - def raw_page(self): - return self - - subscriptions: MutableSequence['Subscription'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='Subscription', - ) - next_page_token: str = proto.Field( - proto.STRING, - number=2, - ) - - -class DeleteSubscriptionRequest(proto.Message): - r"""Request for the DeleteSubscription method. - - Attributes: - subscription (str): - Required. The subscription to delete. Format is - ``projects/{project}/subscriptions/{sub}``. - """ - - subscription: str = proto.Field( - proto.STRING, - number=1, - ) - - -class ModifyPushConfigRequest(proto.Message): - r"""Request for the ModifyPushConfig method. - - Attributes: - subscription (str): - Required. The name of the subscription. Format is - ``projects/{project}/subscriptions/{sub}``. - push_config (google.pubsub_v1.types.PushConfig): - Required. The push configuration for future deliveries. - - An empty ``pushConfig`` indicates that the Pub/Sub system - should stop pushing messages from the given subscription and - allow messages to be pulled and acknowledged - effectively - pausing the subscription if ``Pull`` or ``StreamingPull`` is - not called. - """ - - subscription: str = proto.Field( - proto.STRING, - number=1, - ) - push_config: 'PushConfig' = proto.Field( - proto.MESSAGE, - number=2, - message='PushConfig', - ) - - -class PullRequest(proto.Message): - r"""Request for the ``Pull`` method. - - Attributes: - subscription (str): - Required. The subscription from which messages should be - pulled. Format is - ``projects/{project}/subscriptions/{sub}``. - return_immediately (bool): - Optional. If this field set to true, the system will respond - immediately even if it there are no messages available to - return in the ``Pull`` response. Otherwise, the system may - wait (for a bounded amount of time) until at least one - message is available, rather than returning no messages. - Warning: setting this field to ``true`` is discouraged - because it adversely impacts the performance of ``Pull`` - operations. We recommend that users do not set this field. - max_messages (int): - Required. The maximum number of messages to - return for this request. Must be a positive - integer. The Pub/Sub system may return fewer - than the number specified. - """ - - subscription: str = proto.Field( - proto.STRING, - number=1, - ) - return_immediately: bool = proto.Field( - proto.BOOL, - number=2, - ) - max_messages: int = proto.Field( - proto.INT32, - number=3, - ) - - -class PullResponse(proto.Message): - r"""Response for the ``Pull`` method. - - Attributes: - received_messages (MutableSequence[google.pubsub_v1.types.ReceivedMessage]): - Optional. Received Pub/Sub messages. The list will be empty - if there are no more messages available in the backlog, or - if no messages could be returned before the request timeout. - For JSON, the response can be entirely empty. The Pub/Sub - system may return fewer than the ``maxMessages`` requested - even if there are more messages available in the backlog. - """ - - received_messages: MutableSequence['ReceivedMessage'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='ReceivedMessage', - ) - - -class ModifyAckDeadlineRequest(proto.Message): - r"""Request for the ModifyAckDeadline method. - - Attributes: - subscription (str): - Required. The name of the subscription. Format is - ``projects/{project}/subscriptions/{sub}``. - ack_ids (MutableSequence[str]): - Required. List of acknowledgment IDs. - ack_deadline_seconds (int): - Required. The new ack deadline with respect to the time this - request was sent to the Pub/Sub system. For example, if the - value is 10, the new ack deadline will expire 10 seconds - after the ``ModifyAckDeadline`` call was made. Specifying - zero might immediately make the message available for - delivery to another subscriber client. This typically - results in an increase in the rate of message redeliveries - (that is, duplicates). The minimum deadline you can specify - is 0 seconds. The maximum deadline you can specify in a - single request is 600 seconds (10 minutes). - """ - - subscription: str = proto.Field( - proto.STRING, - number=1, - ) - ack_ids: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=4, - ) - ack_deadline_seconds: int = proto.Field( - proto.INT32, - number=3, - ) - - -class AcknowledgeRequest(proto.Message): - r"""Request for the Acknowledge method. - - Attributes: - subscription (str): - Required. The subscription whose message is being - acknowledged. Format is - ``projects/{project}/subscriptions/{sub}``. - ack_ids (MutableSequence[str]): - Required. The acknowledgment ID for the messages being - acknowledged that was returned by the Pub/Sub system in the - ``Pull`` response. Must not be empty. - """ - - subscription: str = proto.Field( - proto.STRING, - number=1, - ) - ack_ids: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=2, - ) - - -class StreamingPullRequest(proto.Message): - r"""Request for the ``StreamingPull`` streaming RPC method. This request - is used to establish the initial stream as well as to stream - acknowledgements and ack deadline modifications from the client to - the server. - - Attributes: - subscription (str): - Required. The subscription for which to initialize the new - stream. This must be provided in the first request on the - stream, and must not be set in subsequent requests from - client to server. Format is - ``projects/{project}/subscriptions/{sub}``. - ack_ids (MutableSequence[str]): - Optional. List of acknowledgement IDs for acknowledging - previously received messages (received on this stream or a - different stream). If an ack ID has expired, the - corresponding message may be redelivered later. - Acknowledging a message more than once will not result in an - error. If the acknowledgement ID is malformed, the stream - will be aborted with status ``INVALID_ARGUMENT``. - modify_deadline_seconds (MutableSequence[int]): - Optional. The list of new ack deadlines for the IDs listed - in ``modify_deadline_ack_ids``. The size of this list must - be the same as the size of ``modify_deadline_ack_ids``. If - it differs the stream will be aborted with - ``INVALID_ARGUMENT``. Each element in this list is applied - to the element in the same position in - ``modify_deadline_ack_ids``. The new ack deadline is with - respect to the time this request was sent to the Pub/Sub - system. Must be >= 0. For example, if the value is 10, the - new ack deadline will expire 10 seconds after this request - is received. If the value is 0, the message is immediately - made available for another streaming or non-streaming pull - request. If the value is < 0 (an error), the stream will be - aborted with status ``INVALID_ARGUMENT``. - modify_deadline_ack_ids (MutableSequence[str]): - Optional. List of acknowledgement IDs whose deadline will be - modified based on the corresponding element in - ``modify_deadline_seconds``. This field can be used to - indicate that more time is needed to process a message by - the subscriber, or to make the message available for - redelivery if the processing was interrupted. - stream_ack_deadline_seconds (int): - Required. The ack deadline to use for the - stream. This must be provided in the first - request on the stream, but it can also be - updated on subsequent requests from client to - server. The minimum deadline you can specify is - 10 seconds. The maximum deadline you can specify - is 600 seconds (10 minutes). - client_id (str): - Optional. A unique identifier that is used to distinguish - client instances from each other. Only needs to be provided - on the initial request. When a stream disconnects and - reconnects for the same stream, the client_id should be set - to the same value so that state associated with the old - stream can be transferred to the new stream. The same - client_id should not be used for different client instances. - max_outstanding_messages (int): - Optional. Flow control settings for the maximum number of - outstanding messages. When there are - ``max_outstanding_messages`` currently sent to the streaming - pull client that have not yet been acked or nacked, the - server stops sending more messages. The sending of messages - resumes once the number of outstanding messages is less than - this value. If the value is <= 0, there is no limit to the - number of outstanding messages. This property can only be - set on the initial StreamingPullRequest. If it is set on a - subsequent request, the stream will be aborted with status - ``INVALID_ARGUMENT``. - max_outstanding_bytes (int): - Optional. Flow control settings for the maximum number of - outstanding bytes. When there are ``max_outstanding_bytes`` - or more worth of messages currently sent to the streaming - pull client that have not yet been acked or nacked, the - server will stop sending more messages. The sending of - messages resumes once the number of outstanding bytes is - less than this value. If the value is <= 0, there is no - limit to the number of outstanding bytes. This property can - only be set on the initial StreamingPullRequest. If it is - set on a subsequent request, the stream will be aborted with - status ``INVALID_ARGUMENT``. - """ - - subscription: str = proto.Field( - proto.STRING, - number=1, - ) - ack_ids: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=2, - ) - modify_deadline_seconds: MutableSequence[int] = proto.RepeatedField( - proto.INT32, - number=3, - ) - modify_deadline_ack_ids: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=4, - ) - stream_ack_deadline_seconds: int = proto.Field( - proto.INT32, - number=5, - ) - client_id: str = proto.Field( - proto.STRING, - number=6, - ) - max_outstanding_messages: int = proto.Field( - proto.INT64, - number=7, - ) - max_outstanding_bytes: int = proto.Field( - proto.INT64, - number=8, - ) - - -class StreamingPullResponse(proto.Message): - r"""Response for the ``StreamingPull`` method. This response is used to - stream messages from the server to the client. - - Attributes: - received_messages (MutableSequence[google.pubsub_v1.types.ReceivedMessage]): - Optional. Received Pub/Sub messages. This - will not be empty. - acknowledge_confirmation (google.pubsub_v1.types.StreamingPullResponse.AcknowledgeConfirmation): - Optional. This field will only be set if - ``enable_exactly_once_delivery`` is set to ``true``. - modify_ack_deadline_confirmation (google.pubsub_v1.types.StreamingPullResponse.ModifyAckDeadlineConfirmation): - Optional. This field will only be set if - ``enable_exactly_once_delivery`` is set to ``true``. - subscription_properties (google.pubsub_v1.types.StreamingPullResponse.SubscriptionProperties): - Optional. Properties associated with this - subscription. - """ - - class AcknowledgeConfirmation(proto.Message): - r"""Acknowledgement IDs sent in one or more previous requests to - acknowledge a previously received message. - - Attributes: - ack_ids (MutableSequence[str]): - Optional. Successfully processed - acknowledgement IDs. - invalid_ack_ids (MutableSequence[str]): - Optional. List of acknowledgement IDs that - were malformed or whose acknowledgement deadline - has expired. - unordered_ack_ids (MutableSequence[str]): - Optional. List of acknowledgement IDs that - were out of order. - temporary_failed_ack_ids (MutableSequence[str]): - Optional. List of acknowledgement IDs that - failed processing with temporary issues. - """ - - ack_ids: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=1, - ) - invalid_ack_ids: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=2, - ) - unordered_ack_ids: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=3, - ) - temporary_failed_ack_ids: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=4, - ) - - class ModifyAckDeadlineConfirmation(proto.Message): - r"""Acknowledgement IDs sent in one or more previous requests to - modify the deadline for a specific message. - - Attributes: - ack_ids (MutableSequence[str]): - Optional. Successfully processed - acknowledgement IDs. - invalid_ack_ids (MutableSequence[str]): - Optional. List of acknowledgement IDs that - were malformed or whose acknowledgement deadline - has expired. - temporary_failed_ack_ids (MutableSequence[str]): - Optional. List of acknowledgement IDs that - failed processing with temporary issues. - """ - - ack_ids: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=1, - ) - invalid_ack_ids: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=2, - ) - temporary_failed_ack_ids: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=3, - ) - - class SubscriptionProperties(proto.Message): - r"""Subscription properties sent as part of the response. - - Attributes: - exactly_once_delivery_enabled (bool): - Optional. True iff exactly once delivery is - enabled for this subscription. - message_ordering_enabled (bool): - Optional. True iff message ordering is - enabled for this subscription. - """ - - exactly_once_delivery_enabled: bool = proto.Field( - proto.BOOL, - number=1, - ) - message_ordering_enabled: bool = proto.Field( - proto.BOOL, - number=2, - ) - - received_messages: MutableSequence['ReceivedMessage'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='ReceivedMessage', - ) - acknowledge_confirmation: AcknowledgeConfirmation = proto.Field( - proto.MESSAGE, - number=5, - message=AcknowledgeConfirmation, - ) - modify_ack_deadline_confirmation: ModifyAckDeadlineConfirmation = proto.Field( - proto.MESSAGE, - number=3, - message=ModifyAckDeadlineConfirmation, - ) - subscription_properties: SubscriptionProperties = proto.Field( - proto.MESSAGE, - number=4, - message=SubscriptionProperties, - ) - - -class CreateSnapshotRequest(proto.Message): - r"""Request for the ``CreateSnapshot`` method. - - Attributes: - name (str): - Required. User-provided name for this snapshot. If the name - is not provided in the request, the server will assign a - random name for this snapshot on the same project as the - subscription. Note that for REST API requests, you must - specify a name. See the `resource name - rules `__. - Format is ``projects/{project}/snapshots/{snap}``. - subscription (str): - Required. The subscription whose backlog the snapshot - retains. Specifically, the created snapshot is guaranteed to - retain: (a) The existing backlog on the subscription. More - precisely, this is defined as the messages in the - subscription's backlog that are unacknowledged upon the - successful completion of the ``CreateSnapshot`` request; as - well as: (b) Any messages published to the subscription's - topic following the successful completion of the - CreateSnapshot request. Format is - ``projects/{project}/subscriptions/{sub}``. - labels (MutableMapping[str, str]): - Optional. See `Creating and managing - labels `__. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - subscription: str = proto.Field( - proto.STRING, - number=2, - ) - labels: MutableMapping[str, str] = proto.MapField( - proto.STRING, - proto.STRING, - number=3, - ) - - -class UpdateSnapshotRequest(proto.Message): - r"""Request for the UpdateSnapshot method. - - Attributes: - snapshot (google.pubsub_v1.types.Snapshot): - Required. The updated snapshot object. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Required. Indicates which fields in the - provided snapshot to update. Must be specified - and non-empty. - """ - - snapshot: 'Snapshot' = proto.Field( - proto.MESSAGE, - number=1, - message='Snapshot', - ) - update_mask: field_mask_pb2.FieldMask = proto.Field( - proto.MESSAGE, - number=2, - message=field_mask_pb2.FieldMask, - ) - - -class Snapshot(proto.Message): - r"""A snapshot resource. Snapshots are used in - `Seek `__ - operations, which allow you to manage message acknowledgments in - bulk. That is, you can set the acknowledgment state of messages in - an existing subscription to the state captured by a snapshot. - - Attributes: - name (str): - Optional. The name of the snapshot. - topic (str): - Optional. The name of the topic from which - this snapshot is retaining messages. - expire_time (google.protobuf.timestamp_pb2.Timestamp): - Optional. The snapshot is guaranteed to exist up until this - time. A newly-created snapshot expires no later than 7 days - from the time of its creation. Its exact lifetime is - determined at creation by the existing backlog in the source - subscription. Specifically, the lifetime of the snapshot is - ``7 days - (age of oldest unacked message in the subscription)``. - For example, consider a subscription whose oldest unacked - message is 3 days old. If a snapshot is created from this - subscription, the snapshot -- which will always capture this - 3-day-old backlog as long as the snapshot exists -- will - expire in 4 days. The service will refuse to create a - snapshot that would expire in less than 1 hour after - creation. - labels (MutableMapping[str, str]): - Optional. See [Creating and managing labels] - (https://cloud.google.com/pubsub/docs/labels). - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - topic: str = proto.Field( - proto.STRING, - number=2, - ) - expire_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=3, - message=timestamp_pb2.Timestamp, - ) - labels: MutableMapping[str, str] = proto.MapField( - proto.STRING, - proto.STRING, - number=4, - ) - - -class GetSnapshotRequest(proto.Message): - r"""Request for the GetSnapshot method. - - Attributes: - snapshot (str): - Required. The name of the snapshot to get. Format is - ``projects/{project}/snapshots/{snap}``. - """ - - snapshot: str = proto.Field( - proto.STRING, - number=1, - ) - - -class ListSnapshotsRequest(proto.Message): - r"""Request for the ``ListSnapshots`` method. - - Attributes: - project (str): - Required. The name of the project in which to list - snapshots. Format is ``projects/{project-id}``. - page_size (int): - Optional. Maximum number of snapshots to - return. - page_token (str): - Optional. The value returned by the last - ``ListSnapshotsResponse``; indicates that this is a - continuation of a prior ``ListSnapshots`` call, and that the - system should return the next page of data. - """ - - project: 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 ListSnapshotsResponse(proto.Message): - r"""Response for the ``ListSnapshots`` method. - - Attributes: - snapshots (MutableSequence[google.pubsub_v1.types.Snapshot]): - Optional. The resulting snapshots. - next_page_token (str): - Optional. If not empty, indicates that there may be more - snapshot that match the request; this value should be passed - in a new ``ListSnapshotsRequest``. - """ - - @property - def raw_page(self): - return self - - snapshots: MutableSequence['Snapshot'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='Snapshot', - ) - next_page_token: str = proto.Field( - proto.STRING, - number=2, - ) - - -class DeleteSnapshotRequest(proto.Message): - r"""Request for the ``DeleteSnapshot`` method. - - Attributes: - snapshot (str): - Required. The name of the snapshot to delete. Format is - ``projects/{project}/snapshots/{snap}``. - """ - - snapshot: str = proto.Field( - proto.STRING, - number=1, - ) - - -class SeekRequest(proto.Message): - r"""Request for the ``Seek`` 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: - subscription (str): - Required. The subscription to affect. - time (google.protobuf.timestamp_pb2.Timestamp): - Optional. The time to seek to. Messages retained in the - subscription that were published before this time are marked - as acknowledged, and messages retained in the subscription - that were published after this time are marked as - unacknowledged. Note that this operation affects only those - messages retained in the subscription (configured by the - combination of ``message_retention_duration`` and - ``retain_acked_messages``). For example, if ``time`` - corresponds to a point before the message retention window - (or to a point before the system's notion of the - subscription creation time), only retained messages will be - marked as unacknowledged, and already-expunged messages will - not be restored. - - This field is a member of `oneof`_ ``target``. - snapshot (str): - Optional. The snapshot to seek to. The snapshot's topic must - be the same as that of the provided subscription. Format is - ``projects/{project}/snapshots/{snap}``. - - This field is a member of `oneof`_ ``target``. - """ - - subscription: str = proto.Field( - proto.STRING, - number=1, - ) - time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=2, - oneof='target', - message=timestamp_pb2.Timestamp, - ) - snapshot: str = proto.Field( - proto.STRING, - number=3, - oneof='target', - ) - - -class SeekResponse(proto.Message): - r"""Response for the ``Seek`` method (this response is empty). - """ - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1/google/pubsub_v1/types/schema.py b/owl-bot-staging/v1/google/pubsub_v1/types/schema.py deleted file mode 100644 index 60279aced..000000000 --- a/owl-bot-staging/v1/google/pubsub_v1/types/schema.py +++ /dev/null @@ -1,512 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - -from google.protobuf import timestamp_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.pubsub.v1', - manifest={ - 'SchemaView', - 'Encoding', - 'Schema', - 'CreateSchemaRequest', - 'GetSchemaRequest', - 'ListSchemasRequest', - 'ListSchemasResponse', - 'ListSchemaRevisionsRequest', - 'ListSchemaRevisionsResponse', - 'CommitSchemaRequest', - 'RollbackSchemaRequest', - 'DeleteSchemaRevisionRequest', - 'DeleteSchemaRequest', - 'ValidateSchemaRequest', - 'ValidateSchemaResponse', - 'ValidateMessageRequest', - 'ValidateMessageResponse', - }, -) - - -class SchemaView(proto.Enum): - r"""View of Schema object fields to be returned by GetSchema and - ListSchemas. - - Values: - SCHEMA_VIEW_UNSPECIFIED (0): - The default / unset value. - The API will default to the BASIC view. - BASIC (1): - Include the name and type of the schema, but - not the definition. - FULL (2): - Include all Schema object fields. - """ - SCHEMA_VIEW_UNSPECIFIED = 0 - BASIC = 1 - FULL = 2 - - -class Encoding(proto.Enum): - r"""Possible encoding types for messages. - - Values: - ENCODING_UNSPECIFIED (0): - Unspecified - JSON (1): - JSON encoding - BINARY (2): - Binary encoding, as defined by the schema - type. For some schema types, binary encoding may - not be available. - """ - ENCODING_UNSPECIFIED = 0 - JSON = 1 - BINARY = 2 - - -class Schema(proto.Message): - r"""A schema resource. - - Attributes: - name (str): - Required. Name of the schema. Format is - ``projects/{project}/schemas/{schema}``. - type_ (google.pubsub_v1.types.Schema.Type): - The type of the schema definition. - definition (str): - The definition of the schema. This should contain a string - representing the full definition of the schema that is a - valid schema definition of the type specified in ``type``. - revision_id (str): - Output only. Immutable. The revision ID of - the schema. - revision_create_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. The timestamp that the revision - was created. - """ - class Type(proto.Enum): - r"""Possible schema definition types. - - Values: - TYPE_UNSPECIFIED (0): - Default value. This value is unused. - PROTOCOL_BUFFER (1): - A Protocol Buffer schema definition. - AVRO (2): - An Avro schema definition. - """ - TYPE_UNSPECIFIED = 0 - PROTOCOL_BUFFER = 1 - AVRO = 2 - - name: str = proto.Field( - proto.STRING, - number=1, - ) - type_: Type = proto.Field( - proto.ENUM, - number=2, - enum=Type, - ) - definition: str = proto.Field( - proto.STRING, - number=3, - ) - revision_id: str = proto.Field( - proto.STRING, - number=4, - ) - revision_create_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=6, - message=timestamp_pb2.Timestamp, - ) - - -class CreateSchemaRequest(proto.Message): - r"""Request for the CreateSchema method. - - Attributes: - parent (str): - Required. The name of the project in which to create the - schema. Format is ``projects/{project-id}``. - schema (google.pubsub_v1.types.Schema): - Required. The schema object to create. - - This schema's ``name`` parameter is ignored. The schema - object returned by CreateSchema will have a ``name`` made - using the given ``parent`` and ``schema_id``. - schema_id (str): - The ID to use for the schema, which will become the final - component of the schema's resource name. - - See - https://cloud.google.com/pubsub/docs/pubsub-basics#resource_names - for resource name constraints. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - schema: 'Schema' = proto.Field( - proto.MESSAGE, - number=2, - message='Schema', - ) - schema_id: str = proto.Field( - proto.STRING, - number=3, - ) - - -class GetSchemaRequest(proto.Message): - r"""Request for the GetSchema method. - - Attributes: - name (str): - Required. The name of the schema to get. Format is - ``projects/{project}/schemas/{schema}``. - view (google.pubsub_v1.types.SchemaView): - The set of fields to return in the response. If not set, - returns a Schema with all fields filled out. Set to - ``BASIC`` to omit the ``definition``. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - view: 'SchemaView' = proto.Field( - proto.ENUM, - number=2, - enum='SchemaView', - ) - - -class ListSchemasRequest(proto.Message): - r"""Request for the ``ListSchemas`` method. - - Attributes: - parent (str): - Required. The name of the project in which to list schemas. - Format is ``projects/{project-id}``. - view (google.pubsub_v1.types.SchemaView): - The set of Schema fields to return in the response. If not - set, returns Schemas with ``name`` and ``type``, but not - ``definition``. Set to ``FULL`` to retrieve all fields. - page_size (int): - Maximum number of schemas to return. - page_token (str): - The value returned by the last ``ListSchemasResponse``; - indicates that this is a continuation of a prior - ``ListSchemas`` call, and that the system should return the - next page of data. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - view: 'SchemaView' = proto.Field( - proto.ENUM, - number=2, - enum='SchemaView', - ) - page_size: int = proto.Field( - proto.INT32, - number=3, - ) - page_token: str = proto.Field( - proto.STRING, - number=4, - ) - - -class ListSchemasResponse(proto.Message): - r"""Response for the ``ListSchemas`` method. - - Attributes: - schemas (MutableSequence[google.pubsub_v1.types.Schema]): - The resulting schemas. - next_page_token (str): - If not empty, indicates that there may be more schemas that - match the request; this value should be passed in a new - ``ListSchemasRequest``. - """ - - @property - def raw_page(self): - return self - - schemas: MutableSequence['Schema'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='Schema', - ) - next_page_token: str = proto.Field( - proto.STRING, - number=2, - ) - - -class ListSchemaRevisionsRequest(proto.Message): - r"""Request for the ``ListSchemaRevisions`` method. - - Attributes: - name (str): - Required. The name of the schema to list - revisions for. - view (google.pubsub_v1.types.SchemaView): - The set of Schema fields to return in the response. If not - set, returns Schemas with ``name`` and ``type``, but not - ``definition``. Set to ``FULL`` to retrieve all fields. - page_size (int): - The maximum number of revisions to return per - page. - page_token (str): - The page token, received from a previous - ListSchemaRevisions call. Provide this to - retrieve the subsequent page. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - view: 'SchemaView' = proto.Field( - proto.ENUM, - number=2, - enum='SchemaView', - ) - page_size: int = proto.Field( - proto.INT32, - number=3, - ) - page_token: str = proto.Field( - proto.STRING, - number=4, - ) - - -class ListSchemaRevisionsResponse(proto.Message): - r"""Response for the ``ListSchemaRevisions`` method. - - Attributes: - schemas (MutableSequence[google.pubsub_v1.types.Schema]): - The revisions of the schema. - next_page_token (str): - A token that can be sent as ``page_token`` to retrieve the - next page. If this field is empty, there are no subsequent - pages. - """ - - @property - def raw_page(self): - return self - - schemas: MutableSequence['Schema'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='Schema', - ) - next_page_token: str = proto.Field( - proto.STRING, - number=2, - ) - - -class CommitSchemaRequest(proto.Message): - r"""Request for CommitSchema method. - - Attributes: - name (str): - Required. The name of the schema we are revising. Format is - ``projects/{project}/schemas/{schema}``. - schema (google.pubsub_v1.types.Schema): - Required. The schema revision to commit. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - schema: 'Schema' = proto.Field( - proto.MESSAGE, - number=2, - message='Schema', - ) - - -class RollbackSchemaRequest(proto.Message): - r"""Request for the ``RollbackSchema`` method. - - Attributes: - name (str): - Required. The schema being rolled back with - revision id. - revision_id (str): - Required. The revision ID to roll back to. - It must be a revision of the same schema. - - Example: c7cfa2a8 - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - revision_id: str = proto.Field( - proto.STRING, - number=2, - ) - - -class DeleteSchemaRevisionRequest(proto.Message): - r"""Request for the ``DeleteSchemaRevision`` method. - - Attributes: - name (str): - Required. The name of the schema revision to be deleted, - with a revision ID explicitly included. - - Example: ``projects/123/schemas/my-schema@c7cfa2a8`` - revision_id (str): - Optional. This field is deprecated and should not be used - for specifying the revision ID. The revision ID should be - specified via the ``name`` parameter. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - revision_id: str = proto.Field( - proto.STRING, - number=2, - ) - - -class DeleteSchemaRequest(proto.Message): - r"""Request for the ``DeleteSchema`` method. - - Attributes: - name (str): - Required. Name of the schema to delete. Format is - ``projects/{project}/schemas/{schema}``. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class ValidateSchemaRequest(proto.Message): - r"""Request for the ``ValidateSchema`` method. - - Attributes: - parent (str): - Required. The name of the project in which to validate - schemas. Format is ``projects/{project-id}``. - schema (google.pubsub_v1.types.Schema): - Required. The schema object to validate. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - schema: 'Schema' = proto.Field( - proto.MESSAGE, - number=2, - message='Schema', - ) - - -class ValidateSchemaResponse(proto.Message): - r"""Response for the ``ValidateSchema`` method. Empty for now. - """ - - -class ValidateMessageRequest(proto.Message): - r"""Request for the ``ValidateMessage`` 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: - parent (str): - Required. The name of the project in which to validate - schemas. Format is ``projects/{project-id}``. - name (str): - Name of the schema against which to validate. - - Format is ``projects/{project}/schemas/{schema}``. - - This field is a member of `oneof`_ ``schema_spec``. - schema (google.pubsub_v1.types.Schema): - Ad-hoc schema against which to validate - - This field is a member of `oneof`_ ``schema_spec``. - message (bytes): - Message to validate against the provided ``schema_spec``. - encoding (google.pubsub_v1.types.Encoding): - The encoding expected for messages - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - name: str = proto.Field( - proto.STRING, - number=2, - oneof='schema_spec', - ) - schema: 'Schema' = proto.Field( - proto.MESSAGE, - number=3, - oneof='schema_spec', - message='Schema', - ) - message: bytes = proto.Field( - proto.BYTES, - number=4, - ) - encoding: 'Encoding' = proto.Field( - proto.ENUM, - number=5, - enum='Encoding', - ) - - -class ValidateMessageResponse(proto.Message): - r"""Response for the ``ValidateMessage`` method. Empty for now. - """ - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1/mypy.ini b/owl-bot-staging/v1/mypy.ini deleted file mode 100644 index 574c5aed3..000000000 --- a/owl-bot-staging/v1/mypy.ini +++ /dev/null @@ -1,3 +0,0 @@ -[mypy] -python_version = 3.7 -namespace_packages = True diff --git a/owl-bot-staging/v1/noxfile.py b/owl-bot-staging/v1/noxfile.py deleted file mode 100644 index d4fb4ff10..000000000 --- a/owl-bot-staging/v1/noxfile.py +++ /dev/null @@ -1,278 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import os -import pathlib -import re -import shutil -import subprocess -import sys - - -import nox # type: ignore - -ALL_PYTHON = [ - "3.7", - "3.8", - "3.9", - "3.10", - "3.11", - "3.12" -] - -CURRENT_DIRECTORY = pathlib.Path(__file__).parent.absolute() - -LOWER_BOUND_CONSTRAINTS_FILE = CURRENT_DIRECTORY / "constraints.txt" -PACKAGE_NAME = 'google-cloud-pubsub' - -BLACK_VERSION = "black==22.3.0" -BLACK_PATHS = ["docs", "google", "tests", "samples", "noxfile.py", "setup.py"] -DEFAULT_PYTHON_VERSION = "3.12" - -nox.sessions = [ - "unit", - "cover", - "mypy", - "check_lower_bounds" - # exclude update_lower_bounds from default - "docs", - "blacken", - "lint", - "prerelease_deps", -] - -@nox.session(python=ALL_PYTHON) -@nox.parametrize( - "protobuf_implementation", - [ "python", "upb", "cpp" ], -) -def unit(session, protobuf_implementation): - """Run the unit test suite.""" - - if protobuf_implementation == "cpp" and session.python in ("3.11", "3.12"): - session.skip("cpp implementation is not supported in python 3.11+") - - session.install('coverage', 'pytest', 'pytest-cov', 'pytest-asyncio', 'asyncmock; python_version < "3.8"') - session.install('-e', '.', "-c", f"testing/constraints-{session.python}.txt") - - # Remove the 'cpp' implementation once support for Protobuf 3.x is dropped. - # The 'cpp' implementation requires Protobuf<4. - if protobuf_implementation == "cpp": - session.install("protobuf<4") - - session.run( - 'py.test', - '--quiet', - '--cov=google/pubsub_v1/', - '--cov=tests/', - '--cov-config=.coveragerc', - '--cov-report=term', - '--cov-report=html', - os.path.join('tests', 'unit', ''.join(session.posargs)), - env={ - "PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION": protobuf_implementation, - }, - ) - -@nox.session(python=ALL_PYTHON[-1]) -@nox.parametrize( - "protobuf_implementation", - [ "python", "upb", "cpp" ], -) -def prerelease_deps(session, protobuf_implementation): - """Run the unit test suite against pre-release versions of dependencies.""" - - if protobuf_implementation == "cpp" and session.python in ("3.11", "3.12"): - session.skip("cpp implementation is not supported in python 3.11+") - - # Install test environment dependencies - session.install('coverage', 'pytest', 'pytest-cov', 'pytest-asyncio', 'asyncmock; python_version < "3.8"') - - # Install the package without dependencies - session.install('-e', '.', '--no-deps') - - # We test the minimum dependency versions using the minimum Python - # version so the lowest python runtime that we test has a corresponding constraints - # file, located at `testing/constraints--.txt`, which contains all of the - # dependencies and extras. - with open( - CURRENT_DIRECTORY - / "testing" - / f"constraints-{ALL_PYTHON[0]}.txt", - encoding="utf-8", - ) as constraints_file: - constraints_text = constraints_file.read() - - # Ignore leading whitespace and comment lines. - constraints_deps = [ - match.group(1) - for match in re.finditer( - r"^\s*(\S+)(?===\S+)", constraints_text, flags=re.MULTILINE - ) - ] - - session.install(*constraints_deps) - - prerel_deps = [ - "googleapis-common-protos", - "google-api-core", - "google-auth", - "grpcio", - "grpcio-status", - "protobuf", - "proto-plus", - ] - - for dep in prerel_deps: - session.install("--pre", "--no-deps", "--upgrade", dep) - - # Remaining dependencies - other_deps = [ - "requests", - ] - session.install(*other_deps) - - # Print out prerelease package versions - - session.run("python", "-c", "import google.api_core; print(google.api_core.__version__)") - session.run("python", "-c", "import google.auth; print(google.auth.__version__)") - session.run("python", "-c", "import grpc; print(grpc.__version__)") - session.run( - "python", "-c", "import google.protobuf; print(google.protobuf.__version__)" - ) - session.run( - "python", "-c", "import proto; print(proto.__version__)" - ) - - session.run( - 'py.test', - '--quiet', - '--cov=google/pubsub_v1/', - '--cov=tests/', - '--cov-config=.coveragerc', - '--cov-report=term', - '--cov-report=html', - os.path.join('tests', 'unit', ''.join(session.posargs)), - env={ - "PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION": protobuf_implementation, - }, - ) - - -@nox.session(python=DEFAULT_PYTHON_VERSION) -def cover(session): - """Run the final coverage report. - This outputs the coverage report aggregating coverage from the unit - test runs (not system test runs), and then erases coverage data. - """ - session.install("coverage", "pytest-cov") - session.run("coverage", "report", "--show-missing", "--fail-under=100") - - session.run("coverage", "erase") - - -@nox.session(python=ALL_PYTHON) -def mypy(session): - """Run the type checker.""" - session.install( - 'mypy', - 'types-requests', - 'types-protobuf' - ) - session.install('.') - session.run( - 'mypy', - '-p', - 'google', - ) - - -@nox.session -def update_lower_bounds(session): - """Update lower bounds in constraints.txt to match setup.py""" - session.install('google-cloud-testutils') - session.install('.') - - session.run( - 'lower-bound-checker', - 'update', - '--package-name', - PACKAGE_NAME, - '--constraints-file', - str(LOWER_BOUND_CONSTRAINTS_FILE), - ) - - -@nox.session -def check_lower_bounds(session): - """Check lower bounds in setup.py are reflected in constraints file""" - session.install('google-cloud-testutils') - session.install('.') - - session.run( - 'lower-bound-checker', - 'check', - '--package-name', - PACKAGE_NAME, - '--constraints-file', - str(LOWER_BOUND_CONSTRAINTS_FILE), - ) - -@nox.session(python=DEFAULT_PYTHON_VERSION) -def docs(session): - """Build the docs for this library.""" - - session.install("-e", ".") - session.install("sphinx==7.0.1", "alabaster", "recommonmark") - - shutil.rmtree(os.path.join("docs", "_build"), ignore_errors=True) - session.run( - "sphinx-build", - "-W", # warnings as errors - "-T", # show full traceback on exception - "-N", # no colors - "-b", - "html", - "-d", - os.path.join("docs", "_build", "doctrees", ""), - os.path.join("docs", ""), - os.path.join("docs", "_build", "html", ""), - ) - - -@nox.session(python=DEFAULT_PYTHON_VERSION) -def lint(session): - """Run linters. - - Returns a failure if the linters find linting errors or sufficiently - serious code quality issues. - """ - session.install("flake8", BLACK_VERSION) - session.run( - "black", - "--check", - *BLACK_PATHS, - ) - session.run("flake8", "google", "tests", "samples") - - -@nox.session(python=DEFAULT_PYTHON_VERSION) -def blacken(session): - """Run black. Format code to uniform standard.""" - session.install(BLACK_VERSION) - session.run( - "black", - *BLACK_PATHS, - ) diff --git a/owl-bot-staging/v1/samples/generated_samples/pubsub_v1_generated_publisher_create_topic_async.py b/owl-bot-staging/v1/samples/generated_samples/pubsub_v1_generated_publisher_create_topic_async.py deleted file mode 100644 index 5694b24ef..000000000 --- a/owl-bot-staging/v1/samples/generated_samples/pubsub_v1_generated_publisher_create_topic_async.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CreateTopic -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-pubsub - - -# [START pubsub_v1_generated_Publisher_CreateTopic_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 pubsub_v1 - - -async def sample_create_topic(): - # Create a client - client = pubsub_v1.PublisherAsyncClient() - - # Initialize request argument(s) - request = pubsub_v1.Topic( - name="name_value", - ) - - # Make the request - response = await client.create_topic(request=request) - - # Handle the response - print(response) - -# [END pubsub_v1_generated_Publisher_CreateTopic_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/pubsub_v1_generated_publisher_create_topic_sync.py b/owl-bot-staging/v1/samples/generated_samples/pubsub_v1_generated_publisher_create_topic_sync.py deleted file mode 100644 index 7de319c67..000000000 --- a/owl-bot-staging/v1/samples/generated_samples/pubsub_v1_generated_publisher_create_topic_sync.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CreateTopic -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-pubsub - - -# [START pubsub_v1_generated_Publisher_CreateTopic_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 pubsub_v1 - - -def sample_create_topic(): - # Create a client - client = pubsub_v1.PublisherClient() - - # Initialize request argument(s) - request = pubsub_v1.Topic( - name="name_value", - ) - - # Make the request - response = client.create_topic(request=request) - - # Handle the response - print(response) - -# [END pubsub_v1_generated_Publisher_CreateTopic_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/pubsub_v1_generated_publisher_delete_topic_async.py b/owl-bot-staging/v1/samples/generated_samples/pubsub_v1_generated_publisher_delete_topic_async.py deleted file mode 100644 index 3d2b74803..000000000 --- a/owl-bot-staging/v1/samples/generated_samples/pubsub_v1_generated_publisher_delete_topic_async.py +++ /dev/null @@ -1,50 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for DeleteTopic -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-pubsub - - -# [START pubsub_v1_generated_Publisher_DeleteTopic_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 pubsub_v1 - - -async def sample_delete_topic(): - # Create a client - client = pubsub_v1.PublisherAsyncClient() - - # Initialize request argument(s) - request = pubsub_v1.DeleteTopicRequest( - topic="topic_value", - ) - - # Make the request - await client.delete_topic(request=request) - - -# [END pubsub_v1_generated_Publisher_DeleteTopic_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/pubsub_v1_generated_publisher_delete_topic_sync.py b/owl-bot-staging/v1/samples/generated_samples/pubsub_v1_generated_publisher_delete_topic_sync.py deleted file mode 100644 index e760eddbd..000000000 --- a/owl-bot-staging/v1/samples/generated_samples/pubsub_v1_generated_publisher_delete_topic_sync.py +++ /dev/null @@ -1,50 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for DeleteTopic -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-pubsub - - -# [START pubsub_v1_generated_Publisher_DeleteTopic_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 pubsub_v1 - - -def sample_delete_topic(): - # Create a client - client = pubsub_v1.PublisherClient() - - # Initialize request argument(s) - request = pubsub_v1.DeleteTopicRequest( - topic="topic_value", - ) - - # Make the request - client.delete_topic(request=request) - - -# [END pubsub_v1_generated_Publisher_DeleteTopic_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/pubsub_v1_generated_publisher_detach_subscription_async.py b/owl-bot-staging/v1/samples/generated_samples/pubsub_v1_generated_publisher_detach_subscription_async.py deleted file mode 100644 index 86508954b..000000000 --- a/owl-bot-staging/v1/samples/generated_samples/pubsub_v1_generated_publisher_detach_subscription_async.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for DetachSubscription -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-pubsub - - -# [START pubsub_v1_generated_Publisher_DetachSubscription_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 pubsub_v1 - - -async def sample_detach_subscription(): - # Create a client - client = pubsub_v1.PublisherAsyncClient() - - # Initialize request argument(s) - request = pubsub_v1.DetachSubscriptionRequest( - subscription="subscription_value", - ) - - # Make the request - response = await client.detach_subscription(request=request) - - # Handle the response - print(response) - -# [END pubsub_v1_generated_Publisher_DetachSubscription_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/pubsub_v1_generated_publisher_detach_subscription_sync.py b/owl-bot-staging/v1/samples/generated_samples/pubsub_v1_generated_publisher_detach_subscription_sync.py deleted file mode 100644 index af6b45837..000000000 --- a/owl-bot-staging/v1/samples/generated_samples/pubsub_v1_generated_publisher_detach_subscription_sync.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for DetachSubscription -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-pubsub - - -# [START pubsub_v1_generated_Publisher_DetachSubscription_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 pubsub_v1 - - -def sample_detach_subscription(): - # Create a client - client = pubsub_v1.PublisherClient() - - # Initialize request argument(s) - request = pubsub_v1.DetachSubscriptionRequest( - subscription="subscription_value", - ) - - # Make the request - response = client.detach_subscription(request=request) - - # Handle the response - print(response) - -# [END pubsub_v1_generated_Publisher_DetachSubscription_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/pubsub_v1_generated_publisher_get_topic_async.py b/owl-bot-staging/v1/samples/generated_samples/pubsub_v1_generated_publisher_get_topic_async.py deleted file mode 100644 index a8bea68c2..000000000 --- a/owl-bot-staging/v1/samples/generated_samples/pubsub_v1_generated_publisher_get_topic_async.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetTopic -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-pubsub - - -# [START pubsub_v1_generated_Publisher_GetTopic_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 pubsub_v1 - - -async def sample_get_topic(): - # Create a client - client = pubsub_v1.PublisherAsyncClient() - - # Initialize request argument(s) - request = pubsub_v1.GetTopicRequest( - topic="topic_value", - ) - - # Make the request - response = await client.get_topic(request=request) - - # Handle the response - print(response) - -# [END pubsub_v1_generated_Publisher_GetTopic_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/pubsub_v1_generated_publisher_get_topic_sync.py b/owl-bot-staging/v1/samples/generated_samples/pubsub_v1_generated_publisher_get_topic_sync.py deleted file mode 100644 index 051b98093..000000000 --- a/owl-bot-staging/v1/samples/generated_samples/pubsub_v1_generated_publisher_get_topic_sync.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetTopic -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-pubsub - - -# [START pubsub_v1_generated_Publisher_GetTopic_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 pubsub_v1 - - -def sample_get_topic(): - # Create a client - client = pubsub_v1.PublisherClient() - - # Initialize request argument(s) - request = pubsub_v1.GetTopicRequest( - topic="topic_value", - ) - - # Make the request - response = client.get_topic(request=request) - - # Handle the response - print(response) - -# [END pubsub_v1_generated_Publisher_GetTopic_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/pubsub_v1_generated_publisher_list_topic_snapshots_async.py b/owl-bot-staging/v1/samples/generated_samples/pubsub_v1_generated_publisher_list_topic_snapshots_async.py deleted file mode 100644 index 4eed18b38..000000000 --- a/owl-bot-staging/v1/samples/generated_samples/pubsub_v1_generated_publisher_list_topic_snapshots_async.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListTopicSnapshots -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-pubsub - - -# [START pubsub_v1_generated_Publisher_ListTopicSnapshots_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 pubsub_v1 - - -async def sample_list_topic_snapshots(): - # Create a client - client = pubsub_v1.PublisherAsyncClient() - - # Initialize request argument(s) - request = pubsub_v1.ListTopicSnapshotsRequest( - topic="topic_value", - ) - - # Make the request - page_result = client.list_topic_snapshots(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END pubsub_v1_generated_Publisher_ListTopicSnapshots_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/pubsub_v1_generated_publisher_list_topic_snapshots_sync.py b/owl-bot-staging/v1/samples/generated_samples/pubsub_v1_generated_publisher_list_topic_snapshots_sync.py deleted file mode 100644 index 1e2266757..000000000 --- a/owl-bot-staging/v1/samples/generated_samples/pubsub_v1_generated_publisher_list_topic_snapshots_sync.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListTopicSnapshots -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-pubsub - - -# [START pubsub_v1_generated_Publisher_ListTopicSnapshots_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 pubsub_v1 - - -def sample_list_topic_snapshots(): - # Create a client - client = pubsub_v1.PublisherClient() - - # Initialize request argument(s) - request = pubsub_v1.ListTopicSnapshotsRequest( - topic="topic_value", - ) - - # Make the request - page_result = client.list_topic_snapshots(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END pubsub_v1_generated_Publisher_ListTopicSnapshots_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/pubsub_v1_generated_publisher_list_topic_subscriptions_async.py b/owl-bot-staging/v1/samples/generated_samples/pubsub_v1_generated_publisher_list_topic_subscriptions_async.py deleted file mode 100644 index 959f1e824..000000000 --- a/owl-bot-staging/v1/samples/generated_samples/pubsub_v1_generated_publisher_list_topic_subscriptions_async.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListTopicSubscriptions -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-pubsub - - -# [START pubsub_v1_generated_Publisher_ListTopicSubscriptions_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 pubsub_v1 - - -async def sample_list_topic_subscriptions(): - # Create a client - client = pubsub_v1.PublisherAsyncClient() - - # Initialize request argument(s) - request = pubsub_v1.ListTopicSubscriptionsRequest( - topic="topic_value", - ) - - # Make the request - page_result = client.list_topic_subscriptions(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END pubsub_v1_generated_Publisher_ListTopicSubscriptions_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/pubsub_v1_generated_publisher_list_topic_subscriptions_sync.py b/owl-bot-staging/v1/samples/generated_samples/pubsub_v1_generated_publisher_list_topic_subscriptions_sync.py deleted file mode 100644 index c648b8d1a..000000000 --- a/owl-bot-staging/v1/samples/generated_samples/pubsub_v1_generated_publisher_list_topic_subscriptions_sync.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListTopicSubscriptions -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-pubsub - - -# [START pubsub_v1_generated_Publisher_ListTopicSubscriptions_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 pubsub_v1 - - -def sample_list_topic_subscriptions(): - # Create a client - client = pubsub_v1.PublisherClient() - - # Initialize request argument(s) - request = pubsub_v1.ListTopicSubscriptionsRequest( - topic="topic_value", - ) - - # Make the request - page_result = client.list_topic_subscriptions(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END pubsub_v1_generated_Publisher_ListTopicSubscriptions_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/pubsub_v1_generated_publisher_list_topics_async.py b/owl-bot-staging/v1/samples/generated_samples/pubsub_v1_generated_publisher_list_topics_async.py deleted file mode 100644 index dc4a36ef8..000000000 --- a/owl-bot-staging/v1/samples/generated_samples/pubsub_v1_generated_publisher_list_topics_async.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListTopics -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-pubsub - - -# [START pubsub_v1_generated_Publisher_ListTopics_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 pubsub_v1 - - -async def sample_list_topics(): - # Create a client - client = pubsub_v1.PublisherAsyncClient() - - # Initialize request argument(s) - request = pubsub_v1.ListTopicsRequest( - project="project_value", - ) - - # Make the request - page_result = client.list_topics(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END pubsub_v1_generated_Publisher_ListTopics_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/pubsub_v1_generated_publisher_list_topics_sync.py b/owl-bot-staging/v1/samples/generated_samples/pubsub_v1_generated_publisher_list_topics_sync.py deleted file mode 100644 index 8d71be398..000000000 --- a/owl-bot-staging/v1/samples/generated_samples/pubsub_v1_generated_publisher_list_topics_sync.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListTopics -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-pubsub - - -# [START pubsub_v1_generated_Publisher_ListTopics_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 pubsub_v1 - - -def sample_list_topics(): - # Create a client - client = pubsub_v1.PublisherClient() - - # Initialize request argument(s) - request = pubsub_v1.ListTopicsRequest( - project="project_value", - ) - - # Make the request - page_result = client.list_topics(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END pubsub_v1_generated_Publisher_ListTopics_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/pubsub_v1_generated_publisher_publish_async.py b/owl-bot-staging/v1/samples/generated_samples/pubsub_v1_generated_publisher_publish_async.py deleted file mode 100644 index 5c6b63a2d..000000000 --- a/owl-bot-staging/v1/samples/generated_samples/pubsub_v1_generated_publisher_publish_async.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for Publish -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-pubsub - - -# [START pubsub_v1_generated_Publisher_Publish_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 pubsub_v1 - - -async def sample_publish(): - # Create a client - client = pubsub_v1.PublisherAsyncClient() - - # Initialize request argument(s) - request = pubsub_v1.PublishRequest( - topic="topic_value", - ) - - # Make the request - response = await client.publish(request=request) - - # Handle the response - print(response) - -# [END pubsub_v1_generated_Publisher_Publish_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/pubsub_v1_generated_publisher_publish_sync.py b/owl-bot-staging/v1/samples/generated_samples/pubsub_v1_generated_publisher_publish_sync.py deleted file mode 100644 index 9af236d44..000000000 --- a/owl-bot-staging/v1/samples/generated_samples/pubsub_v1_generated_publisher_publish_sync.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for Publish -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-pubsub - - -# [START pubsub_v1_generated_Publisher_Publish_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 pubsub_v1 - - -def sample_publish(): - # Create a client - client = pubsub_v1.PublisherClient() - - # Initialize request argument(s) - request = pubsub_v1.PublishRequest( - topic="topic_value", - ) - - # Make the request - response = client.publish(request=request) - - # Handle the response - print(response) - -# [END pubsub_v1_generated_Publisher_Publish_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/pubsub_v1_generated_publisher_update_topic_async.py b/owl-bot-staging/v1/samples/generated_samples/pubsub_v1_generated_publisher_update_topic_async.py deleted file mode 100644 index d9451b624..000000000 --- a/owl-bot-staging/v1/samples/generated_samples/pubsub_v1_generated_publisher_update_topic_async.py +++ /dev/null @@ -1,55 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateTopic -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-pubsub - - -# [START pubsub_v1_generated_Publisher_UpdateTopic_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 pubsub_v1 - - -async def sample_update_topic(): - # Create a client - client = pubsub_v1.PublisherAsyncClient() - - # Initialize request argument(s) - topic = pubsub_v1.Topic() - topic.name = "name_value" - - request = pubsub_v1.UpdateTopicRequest( - topic=topic, - ) - - # Make the request - response = await client.update_topic(request=request) - - # Handle the response - print(response) - -# [END pubsub_v1_generated_Publisher_UpdateTopic_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/pubsub_v1_generated_publisher_update_topic_sync.py b/owl-bot-staging/v1/samples/generated_samples/pubsub_v1_generated_publisher_update_topic_sync.py deleted file mode 100644 index 9b7326c2c..000000000 --- a/owl-bot-staging/v1/samples/generated_samples/pubsub_v1_generated_publisher_update_topic_sync.py +++ /dev/null @@ -1,55 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateTopic -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-pubsub - - -# [START pubsub_v1_generated_Publisher_UpdateTopic_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 pubsub_v1 - - -def sample_update_topic(): - # Create a client - client = pubsub_v1.PublisherClient() - - # Initialize request argument(s) - topic = pubsub_v1.Topic() - topic.name = "name_value" - - request = pubsub_v1.UpdateTopicRequest( - topic=topic, - ) - - # Make the request - response = client.update_topic(request=request) - - # Handle the response - print(response) - -# [END pubsub_v1_generated_Publisher_UpdateTopic_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/pubsub_v1_generated_schema_service_commit_schema_async.py b/owl-bot-staging/v1/samples/generated_samples/pubsub_v1_generated_schema_service_commit_schema_async.py deleted file mode 100644 index b93ec0b5d..000000000 --- a/owl-bot-staging/v1/samples/generated_samples/pubsub_v1_generated_schema_service_commit_schema_async.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CommitSchema -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-pubsub - - -# [START pubsub_v1_generated_SchemaService_CommitSchema_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 pubsub_v1 - - -async def sample_commit_schema(): - # Create a client - client = pubsub_v1.SchemaServiceAsyncClient() - - # Initialize request argument(s) - schema = pubsub_v1.Schema() - schema.name = "name_value" - - request = pubsub_v1.CommitSchemaRequest( - name="name_value", - schema=schema, - ) - - # Make the request - response = await client.commit_schema(request=request) - - # Handle the response - print(response) - -# [END pubsub_v1_generated_SchemaService_CommitSchema_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/pubsub_v1_generated_schema_service_commit_schema_sync.py b/owl-bot-staging/v1/samples/generated_samples/pubsub_v1_generated_schema_service_commit_schema_sync.py deleted file mode 100644 index c7caa1cbb..000000000 --- a/owl-bot-staging/v1/samples/generated_samples/pubsub_v1_generated_schema_service_commit_schema_sync.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CommitSchema -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-pubsub - - -# [START pubsub_v1_generated_SchemaService_CommitSchema_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 pubsub_v1 - - -def sample_commit_schema(): - # Create a client - client = pubsub_v1.SchemaServiceClient() - - # Initialize request argument(s) - schema = pubsub_v1.Schema() - schema.name = "name_value" - - request = pubsub_v1.CommitSchemaRequest( - name="name_value", - schema=schema, - ) - - # Make the request - response = client.commit_schema(request=request) - - # Handle the response - print(response) - -# [END pubsub_v1_generated_SchemaService_CommitSchema_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/pubsub_v1_generated_schema_service_create_schema_async.py b/owl-bot-staging/v1/samples/generated_samples/pubsub_v1_generated_schema_service_create_schema_async.py deleted file mode 100644 index 9cdd164f5..000000000 --- a/owl-bot-staging/v1/samples/generated_samples/pubsub_v1_generated_schema_service_create_schema_async.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CreateSchema -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-pubsub - - -# [START pubsub_v1_generated_SchemaService_CreateSchema_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 pubsub_v1 - - -async def sample_create_schema(): - # Create a client - client = pubsub_v1.SchemaServiceAsyncClient() - - # Initialize request argument(s) - schema = pubsub_v1.Schema() - schema.name = "name_value" - - request = pubsub_v1.CreateSchemaRequest( - parent="parent_value", - schema=schema, - ) - - # Make the request - response = await client.create_schema(request=request) - - # Handle the response - print(response) - -# [END pubsub_v1_generated_SchemaService_CreateSchema_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/pubsub_v1_generated_schema_service_create_schema_sync.py b/owl-bot-staging/v1/samples/generated_samples/pubsub_v1_generated_schema_service_create_schema_sync.py deleted file mode 100644 index ce8619977..000000000 --- a/owl-bot-staging/v1/samples/generated_samples/pubsub_v1_generated_schema_service_create_schema_sync.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CreateSchema -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-pubsub - - -# [START pubsub_v1_generated_SchemaService_CreateSchema_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 pubsub_v1 - - -def sample_create_schema(): - # Create a client - client = pubsub_v1.SchemaServiceClient() - - # Initialize request argument(s) - schema = pubsub_v1.Schema() - schema.name = "name_value" - - request = pubsub_v1.CreateSchemaRequest( - parent="parent_value", - schema=schema, - ) - - # Make the request - response = client.create_schema(request=request) - - # Handle the response - print(response) - -# [END pubsub_v1_generated_SchemaService_CreateSchema_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/pubsub_v1_generated_schema_service_delete_schema_async.py b/owl-bot-staging/v1/samples/generated_samples/pubsub_v1_generated_schema_service_delete_schema_async.py deleted file mode 100644 index 1bbebfff5..000000000 --- a/owl-bot-staging/v1/samples/generated_samples/pubsub_v1_generated_schema_service_delete_schema_async.py +++ /dev/null @@ -1,50 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for DeleteSchema -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-pubsub - - -# [START pubsub_v1_generated_SchemaService_DeleteSchema_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 pubsub_v1 - - -async def sample_delete_schema(): - # Create a client - client = pubsub_v1.SchemaServiceAsyncClient() - - # Initialize request argument(s) - request = pubsub_v1.DeleteSchemaRequest( - name="name_value", - ) - - # Make the request - await client.delete_schema(request=request) - - -# [END pubsub_v1_generated_SchemaService_DeleteSchema_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/pubsub_v1_generated_schema_service_delete_schema_revision_async.py b/owl-bot-staging/v1/samples/generated_samples/pubsub_v1_generated_schema_service_delete_schema_revision_async.py deleted file mode 100644 index a35c3af1b..000000000 --- a/owl-bot-staging/v1/samples/generated_samples/pubsub_v1_generated_schema_service_delete_schema_revision_async.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for DeleteSchemaRevision -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-pubsub - - -# [START pubsub_v1_generated_SchemaService_DeleteSchemaRevision_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 pubsub_v1 - - -async def sample_delete_schema_revision(): - # Create a client - client = pubsub_v1.SchemaServiceAsyncClient() - - # Initialize request argument(s) - request = pubsub_v1.DeleteSchemaRevisionRequest( - name="name_value", - ) - - # Make the request - response = await client.delete_schema_revision(request=request) - - # Handle the response - print(response) - -# [END pubsub_v1_generated_SchemaService_DeleteSchemaRevision_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/pubsub_v1_generated_schema_service_delete_schema_revision_sync.py b/owl-bot-staging/v1/samples/generated_samples/pubsub_v1_generated_schema_service_delete_schema_revision_sync.py deleted file mode 100644 index 118fe7340..000000000 --- a/owl-bot-staging/v1/samples/generated_samples/pubsub_v1_generated_schema_service_delete_schema_revision_sync.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for DeleteSchemaRevision -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-pubsub - - -# [START pubsub_v1_generated_SchemaService_DeleteSchemaRevision_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 pubsub_v1 - - -def sample_delete_schema_revision(): - # Create a client - client = pubsub_v1.SchemaServiceClient() - - # Initialize request argument(s) - request = pubsub_v1.DeleteSchemaRevisionRequest( - name="name_value", - ) - - # Make the request - response = client.delete_schema_revision(request=request) - - # Handle the response - print(response) - -# [END pubsub_v1_generated_SchemaService_DeleteSchemaRevision_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/pubsub_v1_generated_schema_service_delete_schema_sync.py b/owl-bot-staging/v1/samples/generated_samples/pubsub_v1_generated_schema_service_delete_schema_sync.py deleted file mode 100644 index 77dfe887b..000000000 --- a/owl-bot-staging/v1/samples/generated_samples/pubsub_v1_generated_schema_service_delete_schema_sync.py +++ /dev/null @@ -1,50 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for DeleteSchema -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-pubsub - - -# [START pubsub_v1_generated_SchemaService_DeleteSchema_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 pubsub_v1 - - -def sample_delete_schema(): - # Create a client - client = pubsub_v1.SchemaServiceClient() - - # Initialize request argument(s) - request = pubsub_v1.DeleteSchemaRequest( - name="name_value", - ) - - # Make the request - client.delete_schema(request=request) - - -# [END pubsub_v1_generated_SchemaService_DeleteSchema_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/pubsub_v1_generated_schema_service_get_schema_async.py b/owl-bot-staging/v1/samples/generated_samples/pubsub_v1_generated_schema_service_get_schema_async.py deleted file mode 100644 index 240df5a2a..000000000 --- a/owl-bot-staging/v1/samples/generated_samples/pubsub_v1_generated_schema_service_get_schema_async.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetSchema -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-pubsub - - -# [START pubsub_v1_generated_SchemaService_GetSchema_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 pubsub_v1 - - -async def sample_get_schema(): - # Create a client - client = pubsub_v1.SchemaServiceAsyncClient() - - # Initialize request argument(s) - request = pubsub_v1.GetSchemaRequest( - name="name_value", - ) - - # Make the request - response = await client.get_schema(request=request) - - # Handle the response - print(response) - -# [END pubsub_v1_generated_SchemaService_GetSchema_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/pubsub_v1_generated_schema_service_get_schema_sync.py b/owl-bot-staging/v1/samples/generated_samples/pubsub_v1_generated_schema_service_get_schema_sync.py deleted file mode 100644 index 2d45faebf..000000000 --- a/owl-bot-staging/v1/samples/generated_samples/pubsub_v1_generated_schema_service_get_schema_sync.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetSchema -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-pubsub - - -# [START pubsub_v1_generated_SchemaService_GetSchema_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 pubsub_v1 - - -def sample_get_schema(): - # Create a client - client = pubsub_v1.SchemaServiceClient() - - # Initialize request argument(s) - request = pubsub_v1.GetSchemaRequest( - name="name_value", - ) - - # Make the request - response = client.get_schema(request=request) - - # Handle the response - print(response) - -# [END pubsub_v1_generated_SchemaService_GetSchema_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/pubsub_v1_generated_schema_service_list_schema_revisions_async.py b/owl-bot-staging/v1/samples/generated_samples/pubsub_v1_generated_schema_service_list_schema_revisions_async.py deleted file mode 100644 index 7ea512001..000000000 --- a/owl-bot-staging/v1/samples/generated_samples/pubsub_v1_generated_schema_service_list_schema_revisions_async.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListSchemaRevisions -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-pubsub - - -# [START pubsub_v1_generated_SchemaService_ListSchemaRevisions_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 pubsub_v1 - - -async def sample_list_schema_revisions(): - # Create a client - client = pubsub_v1.SchemaServiceAsyncClient() - - # Initialize request argument(s) - request = pubsub_v1.ListSchemaRevisionsRequest( - name="name_value", - ) - - # Make the request - page_result = client.list_schema_revisions(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END pubsub_v1_generated_SchemaService_ListSchemaRevisions_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/pubsub_v1_generated_schema_service_list_schema_revisions_sync.py b/owl-bot-staging/v1/samples/generated_samples/pubsub_v1_generated_schema_service_list_schema_revisions_sync.py deleted file mode 100644 index 6aebac042..000000000 --- a/owl-bot-staging/v1/samples/generated_samples/pubsub_v1_generated_schema_service_list_schema_revisions_sync.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListSchemaRevisions -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-pubsub - - -# [START pubsub_v1_generated_SchemaService_ListSchemaRevisions_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 pubsub_v1 - - -def sample_list_schema_revisions(): - # Create a client - client = pubsub_v1.SchemaServiceClient() - - # Initialize request argument(s) - request = pubsub_v1.ListSchemaRevisionsRequest( - name="name_value", - ) - - # Make the request - page_result = client.list_schema_revisions(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END pubsub_v1_generated_SchemaService_ListSchemaRevisions_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/pubsub_v1_generated_schema_service_list_schemas_async.py b/owl-bot-staging/v1/samples/generated_samples/pubsub_v1_generated_schema_service_list_schemas_async.py deleted file mode 100644 index 963618fa9..000000000 --- a/owl-bot-staging/v1/samples/generated_samples/pubsub_v1_generated_schema_service_list_schemas_async.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListSchemas -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-pubsub - - -# [START pubsub_v1_generated_SchemaService_ListSchemas_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 pubsub_v1 - - -async def sample_list_schemas(): - # Create a client - client = pubsub_v1.SchemaServiceAsyncClient() - - # Initialize request argument(s) - request = pubsub_v1.ListSchemasRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_schemas(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END pubsub_v1_generated_SchemaService_ListSchemas_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/pubsub_v1_generated_schema_service_list_schemas_sync.py b/owl-bot-staging/v1/samples/generated_samples/pubsub_v1_generated_schema_service_list_schemas_sync.py deleted file mode 100644 index d7b9e6464..000000000 --- a/owl-bot-staging/v1/samples/generated_samples/pubsub_v1_generated_schema_service_list_schemas_sync.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListSchemas -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-pubsub - - -# [START pubsub_v1_generated_SchemaService_ListSchemas_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 pubsub_v1 - - -def sample_list_schemas(): - # Create a client - client = pubsub_v1.SchemaServiceClient() - - # Initialize request argument(s) - request = pubsub_v1.ListSchemasRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_schemas(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END pubsub_v1_generated_SchemaService_ListSchemas_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/pubsub_v1_generated_schema_service_rollback_schema_async.py b/owl-bot-staging/v1/samples/generated_samples/pubsub_v1_generated_schema_service_rollback_schema_async.py deleted file mode 100644 index b50a08b18..000000000 --- a/owl-bot-staging/v1/samples/generated_samples/pubsub_v1_generated_schema_service_rollback_schema_async.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for RollbackSchema -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-pubsub - - -# [START pubsub_v1_generated_SchemaService_RollbackSchema_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 pubsub_v1 - - -async def sample_rollback_schema(): - # Create a client - client = pubsub_v1.SchemaServiceAsyncClient() - - # Initialize request argument(s) - request = pubsub_v1.RollbackSchemaRequest( - name="name_value", - revision_id="revision_id_value", - ) - - # Make the request - response = await client.rollback_schema(request=request) - - # Handle the response - print(response) - -# [END pubsub_v1_generated_SchemaService_RollbackSchema_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/pubsub_v1_generated_schema_service_rollback_schema_sync.py b/owl-bot-staging/v1/samples/generated_samples/pubsub_v1_generated_schema_service_rollback_schema_sync.py deleted file mode 100644 index 4d83c8cac..000000000 --- a/owl-bot-staging/v1/samples/generated_samples/pubsub_v1_generated_schema_service_rollback_schema_sync.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for RollbackSchema -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-pubsub - - -# [START pubsub_v1_generated_SchemaService_RollbackSchema_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 pubsub_v1 - - -def sample_rollback_schema(): - # Create a client - client = pubsub_v1.SchemaServiceClient() - - # Initialize request argument(s) - request = pubsub_v1.RollbackSchemaRequest( - name="name_value", - revision_id="revision_id_value", - ) - - # Make the request - response = client.rollback_schema(request=request) - - # Handle the response - print(response) - -# [END pubsub_v1_generated_SchemaService_RollbackSchema_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/pubsub_v1_generated_schema_service_validate_message_async.py b/owl-bot-staging/v1/samples/generated_samples/pubsub_v1_generated_schema_service_validate_message_async.py deleted file mode 100644 index 3dcd25490..000000000 --- a/owl-bot-staging/v1/samples/generated_samples/pubsub_v1_generated_schema_service_validate_message_async.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ValidateMessage -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-pubsub - - -# [START pubsub_v1_generated_SchemaService_ValidateMessage_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 pubsub_v1 - - -async def sample_validate_message(): - # Create a client - client = pubsub_v1.SchemaServiceAsyncClient() - - # Initialize request argument(s) - request = pubsub_v1.ValidateMessageRequest( - name="name_value", - parent="parent_value", - ) - - # Make the request - response = await client.validate_message(request=request) - - # Handle the response - print(response) - -# [END pubsub_v1_generated_SchemaService_ValidateMessage_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/pubsub_v1_generated_schema_service_validate_message_sync.py b/owl-bot-staging/v1/samples/generated_samples/pubsub_v1_generated_schema_service_validate_message_sync.py deleted file mode 100644 index 4f509d6b3..000000000 --- a/owl-bot-staging/v1/samples/generated_samples/pubsub_v1_generated_schema_service_validate_message_sync.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ValidateMessage -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-pubsub - - -# [START pubsub_v1_generated_SchemaService_ValidateMessage_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 pubsub_v1 - - -def sample_validate_message(): - # Create a client - client = pubsub_v1.SchemaServiceClient() - - # Initialize request argument(s) - request = pubsub_v1.ValidateMessageRequest( - name="name_value", - parent="parent_value", - ) - - # Make the request - response = client.validate_message(request=request) - - # Handle the response - print(response) - -# [END pubsub_v1_generated_SchemaService_ValidateMessage_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/pubsub_v1_generated_schema_service_validate_schema_async.py b/owl-bot-staging/v1/samples/generated_samples/pubsub_v1_generated_schema_service_validate_schema_async.py deleted file mode 100644 index 5deb08a44..000000000 --- a/owl-bot-staging/v1/samples/generated_samples/pubsub_v1_generated_schema_service_validate_schema_async.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ValidateSchema -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-pubsub - - -# [START pubsub_v1_generated_SchemaService_ValidateSchema_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 pubsub_v1 - - -async def sample_validate_schema(): - # Create a client - client = pubsub_v1.SchemaServiceAsyncClient() - - # Initialize request argument(s) - schema = pubsub_v1.Schema() - schema.name = "name_value" - - request = pubsub_v1.ValidateSchemaRequest( - parent="parent_value", - schema=schema, - ) - - # Make the request - response = await client.validate_schema(request=request) - - # Handle the response - print(response) - -# [END pubsub_v1_generated_SchemaService_ValidateSchema_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/pubsub_v1_generated_schema_service_validate_schema_sync.py b/owl-bot-staging/v1/samples/generated_samples/pubsub_v1_generated_schema_service_validate_schema_sync.py deleted file mode 100644 index cc7826792..000000000 --- a/owl-bot-staging/v1/samples/generated_samples/pubsub_v1_generated_schema_service_validate_schema_sync.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ValidateSchema -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-pubsub - - -# [START pubsub_v1_generated_SchemaService_ValidateSchema_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 pubsub_v1 - - -def sample_validate_schema(): - # Create a client - client = pubsub_v1.SchemaServiceClient() - - # Initialize request argument(s) - schema = pubsub_v1.Schema() - schema.name = "name_value" - - request = pubsub_v1.ValidateSchemaRequest( - parent="parent_value", - schema=schema, - ) - - # Make the request - response = client.validate_schema(request=request) - - # Handle the response - print(response) - -# [END pubsub_v1_generated_SchemaService_ValidateSchema_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/pubsub_v1_generated_subscriber_acknowledge_async.py b/owl-bot-staging/v1/samples/generated_samples/pubsub_v1_generated_subscriber_acknowledge_async.py deleted file mode 100644 index 7fc2967d5..000000000 --- a/owl-bot-staging/v1/samples/generated_samples/pubsub_v1_generated_subscriber_acknowledge_async.py +++ /dev/null @@ -1,51 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for Acknowledge -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-pubsub - - -# [START pubsub_v1_generated_Subscriber_Acknowledge_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 pubsub_v1 - - -async def sample_acknowledge(): - # Create a client - client = pubsub_v1.SubscriberAsyncClient() - - # Initialize request argument(s) - request = pubsub_v1.AcknowledgeRequest( - subscription="subscription_value", - ack_ids=['ack_ids_value1', 'ack_ids_value2'], - ) - - # Make the request - await client.acknowledge(request=request) - - -# [END pubsub_v1_generated_Subscriber_Acknowledge_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/pubsub_v1_generated_subscriber_acknowledge_sync.py b/owl-bot-staging/v1/samples/generated_samples/pubsub_v1_generated_subscriber_acknowledge_sync.py deleted file mode 100644 index 85b492df0..000000000 --- a/owl-bot-staging/v1/samples/generated_samples/pubsub_v1_generated_subscriber_acknowledge_sync.py +++ /dev/null @@ -1,51 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for Acknowledge -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-pubsub - - -# [START pubsub_v1_generated_Subscriber_Acknowledge_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 pubsub_v1 - - -def sample_acknowledge(): - # Create a client - client = pubsub_v1.SubscriberClient() - - # Initialize request argument(s) - request = pubsub_v1.AcknowledgeRequest( - subscription="subscription_value", - ack_ids=['ack_ids_value1', 'ack_ids_value2'], - ) - - # Make the request - client.acknowledge(request=request) - - -# [END pubsub_v1_generated_Subscriber_Acknowledge_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/pubsub_v1_generated_subscriber_create_snapshot_async.py b/owl-bot-staging/v1/samples/generated_samples/pubsub_v1_generated_subscriber_create_snapshot_async.py deleted file mode 100644 index 3f7c691da..000000000 --- a/owl-bot-staging/v1/samples/generated_samples/pubsub_v1_generated_subscriber_create_snapshot_async.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CreateSnapshot -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-pubsub - - -# [START pubsub_v1_generated_Subscriber_CreateSnapshot_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 pubsub_v1 - - -async def sample_create_snapshot(): - # Create a client - client = pubsub_v1.SubscriberAsyncClient() - - # Initialize request argument(s) - request = pubsub_v1.CreateSnapshotRequest( - name="name_value", - subscription="subscription_value", - ) - - # Make the request - response = await client.create_snapshot(request=request) - - # Handle the response - print(response) - -# [END pubsub_v1_generated_Subscriber_CreateSnapshot_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/pubsub_v1_generated_subscriber_create_snapshot_sync.py b/owl-bot-staging/v1/samples/generated_samples/pubsub_v1_generated_subscriber_create_snapshot_sync.py deleted file mode 100644 index 7738b03da..000000000 --- a/owl-bot-staging/v1/samples/generated_samples/pubsub_v1_generated_subscriber_create_snapshot_sync.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CreateSnapshot -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-pubsub - - -# [START pubsub_v1_generated_Subscriber_CreateSnapshot_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 pubsub_v1 - - -def sample_create_snapshot(): - # Create a client - client = pubsub_v1.SubscriberClient() - - # Initialize request argument(s) - request = pubsub_v1.CreateSnapshotRequest( - name="name_value", - subscription="subscription_value", - ) - - # Make the request - response = client.create_snapshot(request=request) - - # Handle the response - print(response) - -# [END pubsub_v1_generated_Subscriber_CreateSnapshot_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/pubsub_v1_generated_subscriber_create_subscription_async.py b/owl-bot-staging/v1/samples/generated_samples/pubsub_v1_generated_subscriber_create_subscription_async.py deleted file mode 100644 index 306218036..000000000 --- a/owl-bot-staging/v1/samples/generated_samples/pubsub_v1_generated_subscriber_create_subscription_async.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CreateSubscription -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-pubsub - - -# [START pubsub_v1_generated_Subscriber_CreateSubscription_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 pubsub_v1 - - -async def sample_create_subscription(): - # Create a client - client = pubsub_v1.SubscriberAsyncClient() - - # Initialize request argument(s) - request = pubsub_v1.Subscription( - name="name_value", - topic="topic_value", - ) - - # Make the request - response = await client.create_subscription(request=request) - - # Handle the response - print(response) - -# [END pubsub_v1_generated_Subscriber_CreateSubscription_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/pubsub_v1_generated_subscriber_create_subscription_sync.py b/owl-bot-staging/v1/samples/generated_samples/pubsub_v1_generated_subscriber_create_subscription_sync.py deleted file mode 100644 index cbb05f62a..000000000 --- a/owl-bot-staging/v1/samples/generated_samples/pubsub_v1_generated_subscriber_create_subscription_sync.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CreateSubscription -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-pubsub - - -# [START pubsub_v1_generated_Subscriber_CreateSubscription_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 pubsub_v1 - - -def sample_create_subscription(): - # Create a client - client = pubsub_v1.SubscriberClient() - - # Initialize request argument(s) - request = pubsub_v1.Subscription( - name="name_value", - topic="topic_value", - ) - - # Make the request - response = client.create_subscription(request=request) - - # Handle the response - print(response) - -# [END pubsub_v1_generated_Subscriber_CreateSubscription_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/pubsub_v1_generated_subscriber_delete_snapshot_async.py b/owl-bot-staging/v1/samples/generated_samples/pubsub_v1_generated_subscriber_delete_snapshot_async.py deleted file mode 100644 index 5bea031a7..000000000 --- a/owl-bot-staging/v1/samples/generated_samples/pubsub_v1_generated_subscriber_delete_snapshot_async.py +++ /dev/null @@ -1,50 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for DeleteSnapshot -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-pubsub - - -# [START pubsub_v1_generated_Subscriber_DeleteSnapshot_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 pubsub_v1 - - -async def sample_delete_snapshot(): - # Create a client - client = pubsub_v1.SubscriberAsyncClient() - - # Initialize request argument(s) - request = pubsub_v1.DeleteSnapshotRequest( - snapshot="snapshot_value", - ) - - # Make the request - await client.delete_snapshot(request=request) - - -# [END pubsub_v1_generated_Subscriber_DeleteSnapshot_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/pubsub_v1_generated_subscriber_delete_snapshot_sync.py b/owl-bot-staging/v1/samples/generated_samples/pubsub_v1_generated_subscriber_delete_snapshot_sync.py deleted file mode 100644 index 01342901b..000000000 --- a/owl-bot-staging/v1/samples/generated_samples/pubsub_v1_generated_subscriber_delete_snapshot_sync.py +++ /dev/null @@ -1,50 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for DeleteSnapshot -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-pubsub - - -# [START pubsub_v1_generated_Subscriber_DeleteSnapshot_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 pubsub_v1 - - -def sample_delete_snapshot(): - # Create a client - client = pubsub_v1.SubscriberClient() - - # Initialize request argument(s) - request = pubsub_v1.DeleteSnapshotRequest( - snapshot="snapshot_value", - ) - - # Make the request - client.delete_snapshot(request=request) - - -# [END pubsub_v1_generated_Subscriber_DeleteSnapshot_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/pubsub_v1_generated_subscriber_delete_subscription_async.py b/owl-bot-staging/v1/samples/generated_samples/pubsub_v1_generated_subscriber_delete_subscription_async.py deleted file mode 100644 index 08a15f4ed..000000000 --- a/owl-bot-staging/v1/samples/generated_samples/pubsub_v1_generated_subscriber_delete_subscription_async.py +++ /dev/null @@ -1,50 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for DeleteSubscription -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-pubsub - - -# [START pubsub_v1_generated_Subscriber_DeleteSubscription_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 pubsub_v1 - - -async def sample_delete_subscription(): - # Create a client - client = pubsub_v1.SubscriberAsyncClient() - - # Initialize request argument(s) - request = pubsub_v1.DeleteSubscriptionRequest( - subscription="subscription_value", - ) - - # Make the request - await client.delete_subscription(request=request) - - -# [END pubsub_v1_generated_Subscriber_DeleteSubscription_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/pubsub_v1_generated_subscriber_delete_subscription_sync.py b/owl-bot-staging/v1/samples/generated_samples/pubsub_v1_generated_subscriber_delete_subscription_sync.py deleted file mode 100644 index 1cde73a72..000000000 --- a/owl-bot-staging/v1/samples/generated_samples/pubsub_v1_generated_subscriber_delete_subscription_sync.py +++ /dev/null @@ -1,50 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for DeleteSubscription -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-pubsub - - -# [START pubsub_v1_generated_Subscriber_DeleteSubscription_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 pubsub_v1 - - -def sample_delete_subscription(): - # Create a client - client = pubsub_v1.SubscriberClient() - - # Initialize request argument(s) - request = pubsub_v1.DeleteSubscriptionRequest( - subscription="subscription_value", - ) - - # Make the request - client.delete_subscription(request=request) - - -# [END pubsub_v1_generated_Subscriber_DeleteSubscription_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/pubsub_v1_generated_subscriber_get_snapshot_async.py b/owl-bot-staging/v1/samples/generated_samples/pubsub_v1_generated_subscriber_get_snapshot_async.py deleted file mode 100644 index 40960acc7..000000000 --- a/owl-bot-staging/v1/samples/generated_samples/pubsub_v1_generated_subscriber_get_snapshot_async.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetSnapshot -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-pubsub - - -# [START pubsub_v1_generated_Subscriber_GetSnapshot_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 pubsub_v1 - - -async def sample_get_snapshot(): - # Create a client - client = pubsub_v1.SubscriberAsyncClient() - - # Initialize request argument(s) - request = pubsub_v1.GetSnapshotRequest( - snapshot="snapshot_value", - ) - - # Make the request - response = await client.get_snapshot(request=request) - - # Handle the response - print(response) - -# [END pubsub_v1_generated_Subscriber_GetSnapshot_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/pubsub_v1_generated_subscriber_get_snapshot_sync.py b/owl-bot-staging/v1/samples/generated_samples/pubsub_v1_generated_subscriber_get_snapshot_sync.py deleted file mode 100644 index 3ee2e9c62..000000000 --- a/owl-bot-staging/v1/samples/generated_samples/pubsub_v1_generated_subscriber_get_snapshot_sync.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetSnapshot -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-pubsub - - -# [START pubsub_v1_generated_Subscriber_GetSnapshot_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 pubsub_v1 - - -def sample_get_snapshot(): - # Create a client - client = pubsub_v1.SubscriberClient() - - # Initialize request argument(s) - request = pubsub_v1.GetSnapshotRequest( - snapshot="snapshot_value", - ) - - # Make the request - response = client.get_snapshot(request=request) - - # Handle the response - print(response) - -# [END pubsub_v1_generated_Subscriber_GetSnapshot_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/pubsub_v1_generated_subscriber_get_subscription_async.py b/owl-bot-staging/v1/samples/generated_samples/pubsub_v1_generated_subscriber_get_subscription_async.py deleted file mode 100644 index 47c739998..000000000 --- a/owl-bot-staging/v1/samples/generated_samples/pubsub_v1_generated_subscriber_get_subscription_async.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetSubscription -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-pubsub - - -# [START pubsub_v1_generated_Subscriber_GetSubscription_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 pubsub_v1 - - -async def sample_get_subscription(): - # Create a client - client = pubsub_v1.SubscriberAsyncClient() - - # Initialize request argument(s) - request = pubsub_v1.GetSubscriptionRequest( - subscription="subscription_value", - ) - - # Make the request - response = await client.get_subscription(request=request) - - # Handle the response - print(response) - -# [END pubsub_v1_generated_Subscriber_GetSubscription_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/pubsub_v1_generated_subscriber_get_subscription_sync.py b/owl-bot-staging/v1/samples/generated_samples/pubsub_v1_generated_subscriber_get_subscription_sync.py deleted file mode 100644 index 22832bc89..000000000 --- a/owl-bot-staging/v1/samples/generated_samples/pubsub_v1_generated_subscriber_get_subscription_sync.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetSubscription -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-pubsub - - -# [START pubsub_v1_generated_Subscriber_GetSubscription_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 pubsub_v1 - - -def sample_get_subscription(): - # Create a client - client = pubsub_v1.SubscriberClient() - - # Initialize request argument(s) - request = pubsub_v1.GetSubscriptionRequest( - subscription="subscription_value", - ) - - # Make the request - response = client.get_subscription(request=request) - - # Handle the response - print(response) - -# [END pubsub_v1_generated_Subscriber_GetSubscription_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/pubsub_v1_generated_subscriber_list_snapshots_async.py b/owl-bot-staging/v1/samples/generated_samples/pubsub_v1_generated_subscriber_list_snapshots_async.py deleted file mode 100644 index bcc3be15d..000000000 --- a/owl-bot-staging/v1/samples/generated_samples/pubsub_v1_generated_subscriber_list_snapshots_async.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListSnapshots -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-pubsub - - -# [START pubsub_v1_generated_Subscriber_ListSnapshots_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 pubsub_v1 - - -async def sample_list_snapshots(): - # Create a client - client = pubsub_v1.SubscriberAsyncClient() - - # Initialize request argument(s) - request = pubsub_v1.ListSnapshotsRequest( - project="project_value", - ) - - # Make the request - page_result = client.list_snapshots(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END pubsub_v1_generated_Subscriber_ListSnapshots_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/pubsub_v1_generated_subscriber_list_snapshots_sync.py b/owl-bot-staging/v1/samples/generated_samples/pubsub_v1_generated_subscriber_list_snapshots_sync.py deleted file mode 100644 index 3477e32d3..000000000 --- a/owl-bot-staging/v1/samples/generated_samples/pubsub_v1_generated_subscriber_list_snapshots_sync.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListSnapshots -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-pubsub - - -# [START pubsub_v1_generated_Subscriber_ListSnapshots_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 pubsub_v1 - - -def sample_list_snapshots(): - # Create a client - client = pubsub_v1.SubscriberClient() - - # Initialize request argument(s) - request = pubsub_v1.ListSnapshotsRequest( - project="project_value", - ) - - # Make the request - page_result = client.list_snapshots(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END pubsub_v1_generated_Subscriber_ListSnapshots_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/pubsub_v1_generated_subscriber_list_subscriptions_async.py b/owl-bot-staging/v1/samples/generated_samples/pubsub_v1_generated_subscriber_list_subscriptions_async.py deleted file mode 100644 index 7b00831a3..000000000 --- a/owl-bot-staging/v1/samples/generated_samples/pubsub_v1_generated_subscriber_list_subscriptions_async.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListSubscriptions -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-pubsub - - -# [START pubsub_v1_generated_Subscriber_ListSubscriptions_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 pubsub_v1 - - -async def sample_list_subscriptions(): - # Create a client - client = pubsub_v1.SubscriberAsyncClient() - - # Initialize request argument(s) - request = pubsub_v1.ListSubscriptionsRequest( - project="project_value", - ) - - # Make the request - page_result = client.list_subscriptions(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END pubsub_v1_generated_Subscriber_ListSubscriptions_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/pubsub_v1_generated_subscriber_list_subscriptions_sync.py b/owl-bot-staging/v1/samples/generated_samples/pubsub_v1_generated_subscriber_list_subscriptions_sync.py deleted file mode 100644 index 8e1a96487..000000000 --- a/owl-bot-staging/v1/samples/generated_samples/pubsub_v1_generated_subscriber_list_subscriptions_sync.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListSubscriptions -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-pubsub - - -# [START pubsub_v1_generated_Subscriber_ListSubscriptions_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 pubsub_v1 - - -def sample_list_subscriptions(): - # Create a client - client = pubsub_v1.SubscriberClient() - - # Initialize request argument(s) - request = pubsub_v1.ListSubscriptionsRequest( - project="project_value", - ) - - # Make the request - page_result = client.list_subscriptions(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END pubsub_v1_generated_Subscriber_ListSubscriptions_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/pubsub_v1_generated_subscriber_modify_ack_deadline_async.py b/owl-bot-staging/v1/samples/generated_samples/pubsub_v1_generated_subscriber_modify_ack_deadline_async.py deleted file mode 100644 index 8e9372292..000000000 --- a/owl-bot-staging/v1/samples/generated_samples/pubsub_v1_generated_subscriber_modify_ack_deadline_async.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ModifyAckDeadline -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-pubsub - - -# [START pubsub_v1_generated_Subscriber_ModifyAckDeadline_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 pubsub_v1 - - -async def sample_modify_ack_deadline(): - # Create a client - client = pubsub_v1.SubscriberAsyncClient() - - # Initialize request argument(s) - request = pubsub_v1.ModifyAckDeadlineRequest( - subscription="subscription_value", - ack_ids=['ack_ids_value1', 'ack_ids_value2'], - ack_deadline_seconds=2066, - ) - - # Make the request - await client.modify_ack_deadline(request=request) - - -# [END pubsub_v1_generated_Subscriber_ModifyAckDeadline_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/pubsub_v1_generated_subscriber_modify_ack_deadline_sync.py b/owl-bot-staging/v1/samples/generated_samples/pubsub_v1_generated_subscriber_modify_ack_deadline_sync.py deleted file mode 100644 index 1d32afec2..000000000 --- a/owl-bot-staging/v1/samples/generated_samples/pubsub_v1_generated_subscriber_modify_ack_deadline_sync.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ModifyAckDeadline -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-pubsub - - -# [START pubsub_v1_generated_Subscriber_ModifyAckDeadline_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 pubsub_v1 - - -def sample_modify_ack_deadline(): - # Create a client - client = pubsub_v1.SubscriberClient() - - # Initialize request argument(s) - request = pubsub_v1.ModifyAckDeadlineRequest( - subscription="subscription_value", - ack_ids=['ack_ids_value1', 'ack_ids_value2'], - ack_deadline_seconds=2066, - ) - - # Make the request - client.modify_ack_deadline(request=request) - - -# [END pubsub_v1_generated_Subscriber_ModifyAckDeadline_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/pubsub_v1_generated_subscriber_modify_push_config_async.py b/owl-bot-staging/v1/samples/generated_samples/pubsub_v1_generated_subscriber_modify_push_config_async.py deleted file mode 100644 index 1d88c9590..000000000 --- a/owl-bot-staging/v1/samples/generated_samples/pubsub_v1_generated_subscriber_modify_push_config_async.py +++ /dev/null @@ -1,50 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ModifyPushConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-pubsub - - -# [START pubsub_v1_generated_Subscriber_ModifyPushConfig_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 pubsub_v1 - - -async def sample_modify_push_config(): - # Create a client - client = pubsub_v1.SubscriberAsyncClient() - - # Initialize request argument(s) - request = pubsub_v1.ModifyPushConfigRequest( - subscription="subscription_value", - ) - - # Make the request - await client.modify_push_config(request=request) - - -# [END pubsub_v1_generated_Subscriber_ModifyPushConfig_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/pubsub_v1_generated_subscriber_modify_push_config_sync.py b/owl-bot-staging/v1/samples/generated_samples/pubsub_v1_generated_subscriber_modify_push_config_sync.py deleted file mode 100644 index 43ac23e4f..000000000 --- a/owl-bot-staging/v1/samples/generated_samples/pubsub_v1_generated_subscriber_modify_push_config_sync.py +++ /dev/null @@ -1,50 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ModifyPushConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-pubsub - - -# [START pubsub_v1_generated_Subscriber_ModifyPushConfig_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 pubsub_v1 - - -def sample_modify_push_config(): - # Create a client - client = pubsub_v1.SubscriberClient() - - # Initialize request argument(s) - request = pubsub_v1.ModifyPushConfigRequest( - subscription="subscription_value", - ) - - # Make the request - client.modify_push_config(request=request) - - -# [END pubsub_v1_generated_Subscriber_ModifyPushConfig_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/pubsub_v1_generated_subscriber_pull_async.py b/owl-bot-staging/v1/samples/generated_samples/pubsub_v1_generated_subscriber_pull_async.py deleted file mode 100644 index 3e6f26a0b..000000000 --- a/owl-bot-staging/v1/samples/generated_samples/pubsub_v1_generated_subscriber_pull_async.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for Pull -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-pubsub - - -# [START pubsub_v1_generated_Subscriber_Pull_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 pubsub_v1 - - -async def sample_pull(): - # Create a client - client = pubsub_v1.SubscriberAsyncClient() - - # Initialize request argument(s) - request = pubsub_v1.PullRequest( - subscription="subscription_value", - max_messages=1277, - ) - - # Make the request - response = await client.pull(request=request) - - # Handle the response - print(response) - -# [END pubsub_v1_generated_Subscriber_Pull_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/pubsub_v1_generated_subscriber_pull_sync.py b/owl-bot-staging/v1/samples/generated_samples/pubsub_v1_generated_subscriber_pull_sync.py deleted file mode 100644 index 950f18cc1..000000000 --- a/owl-bot-staging/v1/samples/generated_samples/pubsub_v1_generated_subscriber_pull_sync.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for Pull -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-pubsub - - -# [START pubsub_v1_generated_Subscriber_Pull_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 pubsub_v1 - - -def sample_pull(): - # Create a client - client = pubsub_v1.SubscriberClient() - - # Initialize request argument(s) - request = pubsub_v1.PullRequest( - subscription="subscription_value", - max_messages=1277, - ) - - # Make the request - response = client.pull(request=request) - - # Handle the response - print(response) - -# [END pubsub_v1_generated_Subscriber_Pull_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/pubsub_v1_generated_subscriber_seek_async.py b/owl-bot-staging/v1/samples/generated_samples/pubsub_v1_generated_subscriber_seek_async.py deleted file mode 100644 index 9038bfd11..000000000 --- a/owl-bot-staging/v1/samples/generated_samples/pubsub_v1_generated_subscriber_seek_async.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for Seek -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-pubsub - - -# [START pubsub_v1_generated_Subscriber_Seek_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 pubsub_v1 - - -async def sample_seek(): - # Create a client - client = pubsub_v1.SubscriberAsyncClient() - - # Initialize request argument(s) - request = pubsub_v1.SeekRequest( - subscription="subscription_value", - ) - - # Make the request - response = await client.seek(request=request) - - # Handle the response - print(response) - -# [END pubsub_v1_generated_Subscriber_Seek_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/pubsub_v1_generated_subscriber_seek_sync.py b/owl-bot-staging/v1/samples/generated_samples/pubsub_v1_generated_subscriber_seek_sync.py deleted file mode 100644 index b57af8fb0..000000000 --- a/owl-bot-staging/v1/samples/generated_samples/pubsub_v1_generated_subscriber_seek_sync.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for Seek -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-pubsub - - -# [START pubsub_v1_generated_Subscriber_Seek_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 pubsub_v1 - - -def sample_seek(): - # Create a client - client = pubsub_v1.SubscriberClient() - - # Initialize request argument(s) - request = pubsub_v1.SeekRequest( - subscription="subscription_value", - ) - - # Make the request - response = client.seek(request=request) - - # Handle the response - print(response) - -# [END pubsub_v1_generated_Subscriber_Seek_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/pubsub_v1_generated_subscriber_streaming_pull_async.py b/owl-bot-staging/v1/samples/generated_samples/pubsub_v1_generated_subscriber_streaming_pull_async.py deleted file mode 100644 index 332c12895..000000000 --- a/owl-bot-staging/v1/samples/generated_samples/pubsub_v1_generated_subscriber_streaming_pull_async.py +++ /dev/null @@ -1,64 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for StreamingPull -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-pubsub - - -# [START pubsub_v1_generated_Subscriber_StreamingPull_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 pubsub_v1 - - -async def sample_streaming_pull(): - # Create a client - client = pubsub_v1.SubscriberAsyncClient() - - # Initialize request argument(s) - request = pubsub_v1.StreamingPullRequest( - subscription="subscription_value", - stream_ack_deadline_seconds=2813, - ) - - # This method expects an iterator which contains - # 'pubsub_v1.StreamingPullRequest' 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.streaming_pull(requests=request_generator()) - - # Handle the response - async for response in stream: - print(response) - -# [END pubsub_v1_generated_Subscriber_StreamingPull_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/pubsub_v1_generated_subscriber_streaming_pull_sync.py b/owl-bot-staging/v1/samples/generated_samples/pubsub_v1_generated_subscriber_streaming_pull_sync.py deleted file mode 100644 index 47926a80a..000000000 --- a/owl-bot-staging/v1/samples/generated_samples/pubsub_v1_generated_subscriber_streaming_pull_sync.py +++ /dev/null @@ -1,64 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for StreamingPull -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-pubsub - - -# [START pubsub_v1_generated_Subscriber_StreamingPull_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 pubsub_v1 - - -def sample_streaming_pull(): - # Create a client - client = pubsub_v1.SubscriberClient() - - # Initialize request argument(s) - request = pubsub_v1.StreamingPullRequest( - subscription="subscription_value", - stream_ack_deadline_seconds=2813, - ) - - # This method expects an iterator which contains - # 'pubsub_v1.StreamingPullRequest' 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.streaming_pull(requests=request_generator()) - - # Handle the response - for response in stream: - print(response) - -# [END pubsub_v1_generated_Subscriber_StreamingPull_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/pubsub_v1_generated_subscriber_update_snapshot_async.py b/owl-bot-staging/v1/samples/generated_samples/pubsub_v1_generated_subscriber_update_snapshot_async.py deleted file mode 100644 index 833885af5..000000000 --- a/owl-bot-staging/v1/samples/generated_samples/pubsub_v1_generated_subscriber_update_snapshot_async.py +++ /dev/null @@ -1,51 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateSnapshot -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-pubsub - - -# [START pubsub_v1_generated_Subscriber_UpdateSnapshot_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 pubsub_v1 - - -async def sample_update_snapshot(): - # Create a client - client = pubsub_v1.SubscriberAsyncClient() - - # Initialize request argument(s) - request = pubsub_v1.UpdateSnapshotRequest( - ) - - # Make the request - response = await client.update_snapshot(request=request) - - # Handle the response - print(response) - -# [END pubsub_v1_generated_Subscriber_UpdateSnapshot_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/pubsub_v1_generated_subscriber_update_snapshot_sync.py b/owl-bot-staging/v1/samples/generated_samples/pubsub_v1_generated_subscriber_update_snapshot_sync.py deleted file mode 100644 index 1c8f8530d..000000000 --- a/owl-bot-staging/v1/samples/generated_samples/pubsub_v1_generated_subscriber_update_snapshot_sync.py +++ /dev/null @@ -1,51 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateSnapshot -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-pubsub - - -# [START pubsub_v1_generated_Subscriber_UpdateSnapshot_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 pubsub_v1 - - -def sample_update_snapshot(): - # Create a client - client = pubsub_v1.SubscriberClient() - - # Initialize request argument(s) - request = pubsub_v1.UpdateSnapshotRequest( - ) - - # Make the request - response = client.update_snapshot(request=request) - - # Handle the response - print(response) - -# [END pubsub_v1_generated_Subscriber_UpdateSnapshot_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/pubsub_v1_generated_subscriber_update_subscription_async.py b/owl-bot-staging/v1/samples/generated_samples/pubsub_v1_generated_subscriber_update_subscription_async.py deleted file mode 100644 index 5c00a74dc..000000000 --- a/owl-bot-staging/v1/samples/generated_samples/pubsub_v1_generated_subscriber_update_subscription_async.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateSubscription -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-pubsub - - -# [START pubsub_v1_generated_Subscriber_UpdateSubscription_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 pubsub_v1 - - -async def sample_update_subscription(): - # Create a client - client = pubsub_v1.SubscriberAsyncClient() - - # Initialize request argument(s) - subscription = pubsub_v1.Subscription() - subscription.name = "name_value" - subscription.topic = "topic_value" - - request = pubsub_v1.UpdateSubscriptionRequest( - subscription=subscription, - ) - - # Make the request - response = await client.update_subscription(request=request) - - # Handle the response - print(response) - -# [END pubsub_v1_generated_Subscriber_UpdateSubscription_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/pubsub_v1_generated_subscriber_update_subscription_sync.py b/owl-bot-staging/v1/samples/generated_samples/pubsub_v1_generated_subscriber_update_subscription_sync.py deleted file mode 100644 index 5cc3de6ec..000000000 --- a/owl-bot-staging/v1/samples/generated_samples/pubsub_v1_generated_subscriber_update_subscription_sync.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateSubscription -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-pubsub - - -# [START pubsub_v1_generated_Subscriber_UpdateSubscription_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 pubsub_v1 - - -def sample_update_subscription(): - # Create a client - client = pubsub_v1.SubscriberClient() - - # Initialize request argument(s) - subscription = pubsub_v1.Subscription() - subscription.name = "name_value" - subscription.topic = "topic_value" - - request = pubsub_v1.UpdateSubscriptionRequest( - subscription=subscription, - ) - - # Make the request - response = client.update_subscription(request=request) - - # Handle the response - print(response) - -# [END pubsub_v1_generated_Subscriber_UpdateSubscription_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/snippet_metadata_google.pubsub.v1.json b/owl-bot-staging/v1/samples/generated_samples/snippet_metadata_google.pubsub.v1.json deleted file mode 100644 index d66015ac4..000000000 --- a/owl-bot-staging/v1/samples/generated_samples/snippet_metadata_google.pubsub.v1.json +++ /dev/null @@ -1,5736 +0,0 @@ -{ - "clientLibrary": { - "apis": [ - { - "id": "google.pubsub.v1", - "version": "v1" - } - ], - "language": "PYTHON", - "name": "google-cloud-pubsub", - "version": "0.1.0" - }, - "snippets": [ - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.pubsub_v1.PublisherAsyncClient", - "shortName": "PublisherAsyncClient" - }, - "fullName": "google.pubsub_v1.PublisherAsyncClient.create_topic", - "method": { - "fullName": "google.pubsub.v1.Publisher.CreateTopic", - "service": { - "fullName": "google.pubsub.v1.Publisher", - "shortName": "Publisher" - }, - "shortName": "CreateTopic" - }, - "parameters": [ - { - "name": "request", - "type": "google.pubsub_v1.types.Topic" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.pubsub_v1.types.Topic", - "shortName": "create_topic" - }, - "description": "Sample for CreateTopic", - "file": "pubsub_v1_generated_publisher_create_topic_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "pubsub_v1_generated_Publisher_CreateTopic_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": "pubsub_v1_generated_publisher_create_topic_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.pubsub_v1.PublisherClient", - "shortName": "PublisherClient" - }, - "fullName": "google.pubsub_v1.PublisherClient.create_topic", - "method": { - "fullName": "google.pubsub.v1.Publisher.CreateTopic", - "service": { - "fullName": "google.pubsub.v1.Publisher", - "shortName": "Publisher" - }, - "shortName": "CreateTopic" - }, - "parameters": [ - { - "name": "request", - "type": "google.pubsub_v1.types.Topic" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.pubsub_v1.types.Topic", - "shortName": "create_topic" - }, - "description": "Sample for CreateTopic", - "file": "pubsub_v1_generated_publisher_create_topic_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "pubsub_v1_generated_Publisher_CreateTopic_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": "pubsub_v1_generated_publisher_create_topic_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.pubsub_v1.PublisherAsyncClient", - "shortName": "PublisherAsyncClient" - }, - "fullName": "google.pubsub_v1.PublisherAsyncClient.delete_topic", - "method": { - "fullName": "google.pubsub.v1.Publisher.DeleteTopic", - "service": { - "fullName": "google.pubsub.v1.Publisher", - "shortName": "Publisher" - }, - "shortName": "DeleteTopic" - }, - "parameters": [ - { - "name": "request", - "type": "google.pubsub_v1.types.DeleteTopicRequest" - }, - { - "name": "topic", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "shortName": "delete_topic" - }, - "description": "Sample for DeleteTopic", - "file": "pubsub_v1_generated_publisher_delete_topic_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "pubsub_v1_generated_Publisher_DeleteTopic_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": "pubsub_v1_generated_publisher_delete_topic_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.pubsub_v1.PublisherClient", - "shortName": "PublisherClient" - }, - "fullName": "google.pubsub_v1.PublisherClient.delete_topic", - "method": { - "fullName": "google.pubsub.v1.Publisher.DeleteTopic", - "service": { - "fullName": "google.pubsub.v1.Publisher", - "shortName": "Publisher" - }, - "shortName": "DeleteTopic" - }, - "parameters": [ - { - "name": "request", - "type": "google.pubsub_v1.types.DeleteTopicRequest" - }, - { - "name": "topic", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "shortName": "delete_topic" - }, - "description": "Sample for DeleteTopic", - "file": "pubsub_v1_generated_publisher_delete_topic_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "pubsub_v1_generated_Publisher_DeleteTopic_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": "pubsub_v1_generated_publisher_delete_topic_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.pubsub_v1.PublisherAsyncClient", - "shortName": "PublisherAsyncClient" - }, - "fullName": "google.pubsub_v1.PublisherAsyncClient.detach_subscription", - "method": { - "fullName": "google.pubsub.v1.Publisher.DetachSubscription", - "service": { - "fullName": "google.pubsub.v1.Publisher", - "shortName": "Publisher" - }, - "shortName": "DetachSubscription" - }, - "parameters": [ - { - "name": "request", - "type": "google.pubsub_v1.types.DetachSubscriptionRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.pubsub_v1.types.DetachSubscriptionResponse", - "shortName": "detach_subscription" - }, - "description": "Sample for DetachSubscription", - "file": "pubsub_v1_generated_publisher_detach_subscription_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "pubsub_v1_generated_Publisher_DetachSubscription_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": "pubsub_v1_generated_publisher_detach_subscription_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.pubsub_v1.PublisherClient", - "shortName": "PublisherClient" - }, - "fullName": "google.pubsub_v1.PublisherClient.detach_subscription", - "method": { - "fullName": "google.pubsub.v1.Publisher.DetachSubscription", - "service": { - "fullName": "google.pubsub.v1.Publisher", - "shortName": "Publisher" - }, - "shortName": "DetachSubscription" - }, - "parameters": [ - { - "name": "request", - "type": "google.pubsub_v1.types.DetachSubscriptionRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.pubsub_v1.types.DetachSubscriptionResponse", - "shortName": "detach_subscription" - }, - "description": "Sample for DetachSubscription", - "file": "pubsub_v1_generated_publisher_detach_subscription_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "pubsub_v1_generated_Publisher_DetachSubscription_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": "pubsub_v1_generated_publisher_detach_subscription_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.pubsub_v1.PublisherAsyncClient", - "shortName": "PublisherAsyncClient" - }, - "fullName": "google.pubsub_v1.PublisherAsyncClient.get_topic", - "method": { - "fullName": "google.pubsub.v1.Publisher.GetTopic", - "service": { - "fullName": "google.pubsub.v1.Publisher", - "shortName": "Publisher" - }, - "shortName": "GetTopic" - }, - "parameters": [ - { - "name": "request", - "type": "google.pubsub_v1.types.GetTopicRequest" - }, - { - "name": "topic", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.pubsub_v1.types.Topic", - "shortName": "get_topic" - }, - "description": "Sample for GetTopic", - "file": "pubsub_v1_generated_publisher_get_topic_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "pubsub_v1_generated_Publisher_GetTopic_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": "pubsub_v1_generated_publisher_get_topic_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.pubsub_v1.PublisherClient", - "shortName": "PublisherClient" - }, - "fullName": "google.pubsub_v1.PublisherClient.get_topic", - "method": { - "fullName": "google.pubsub.v1.Publisher.GetTopic", - "service": { - "fullName": "google.pubsub.v1.Publisher", - "shortName": "Publisher" - }, - "shortName": "GetTopic" - }, - "parameters": [ - { - "name": "request", - "type": "google.pubsub_v1.types.GetTopicRequest" - }, - { - "name": "topic", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.pubsub_v1.types.Topic", - "shortName": "get_topic" - }, - "description": "Sample for GetTopic", - "file": "pubsub_v1_generated_publisher_get_topic_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "pubsub_v1_generated_Publisher_GetTopic_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": "pubsub_v1_generated_publisher_get_topic_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.pubsub_v1.PublisherAsyncClient", - "shortName": "PublisherAsyncClient" - }, - "fullName": "google.pubsub_v1.PublisherAsyncClient.list_topic_snapshots", - "method": { - "fullName": "google.pubsub.v1.Publisher.ListTopicSnapshots", - "service": { - "fullName": "google.pubsub.v1.Publisher", - "shortName": "Publisher" - }, - "shortName": "ListTopicSnapshots" - }, - "parameters": [ - { - "name": "request", - "type": "google.pubsub_v1.types.ListTopicSnapshotsRequest" - }, - { - "name": "topic", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.pubsub_v1.services.publisher.pagers.ListTopicSnapshotsAsyncPager", - "shortName": "list_topic_snapshots" - }, - "description": "Sample for ListTopicSnapshots", - "file": "pubsub_v1_generated_publisher_list_topic_snapshots_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "pubsub_v1_generated_Publisher_ListTopicSnapshots_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": "pubsub_v1_generated_publisher_list_topic_snapshots_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.pubsub_v1.PublisherClient", - "shortName": "PublisherClient" - }, - "fullName": "google.pubsub_v1.PublisherClient.list_topic_snapshots", - "method": { - "fullName": "google.pubsub.v1.Publisher.ListTopicSnapshots", - "service": { - "fullName": "google.pubsub.v1.Publisher", - "shortName": "Publisher" - }, - "shortName": "ListTopicSnapshots" - }, - "parameters": [ - { - "name": "request", - "type": "google.pubsub_v1.types.ListTopicSnapshotsRequest" - }, - { - "name": "topic", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.pubsub_v1.services.publisher.pagers.ListTopicSnapshotsPager", - "shortName": "list_topic_snapshots" - }, - "description": "Sample for ListTopicSnapshots", - "file": "pubsub_v1_generated_publisher_list_topic_snapshots_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "pubsub_v1_generated_Publisher_ListTopicSnapshots_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": "pubsub_v1_generated_publisher_list_topic_snapshots_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.pubsub_v1.PublisherAsyncClient", - "shortName": "PublisherAsyncClient" - }, - "fullName": "google.pubsub_v1.PublisherAsyncClient.list_topic_subscriptions", - "method": { - "fullName": "google.pubsub.v1.Publisher.ListTopicSubscriptions", - "service": { - "fullName": "google.pubsub.v1.Publisher", - "shortName": "Publisher" - }, - "shortName": "ListTopicSubscriptions" - }, - "parameters": [ - { - "name": "request", - "type": "google.pubsub_v1.types.ListTopicSubscriptionsRequest" - }, - { - "name": "topic", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.pubsub_v1.services.publisher.pagers.ListTopicSubscriptionsAsyncPager", - "shortName": "list_topic_subscriptions" - }, - "description": "Sample for ListTopicSubscriptions", - "file": "pubsub_v1_generated_publisher_list_topic_subscriptions_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "pubsub_v1_generated_Publisher_ListTopicSubscriptions_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": "pubsub_v1_generated_publisher_list_topic_subscriptions_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.pubsub_v1.PublisherClient", - "shortName": "PublisherClient" - }, - "fullName": "google.pubsub_v1.PublisherClient.list_topic_subscriptions", - "method": { - "fullName": "google.pubsub.v1.Publisher.ListTopicSubscriptions", - "service": { - "fullName": "google.pubsub.v1.Publisher", - "shortName": "Publisher" - }, - "shortName": "ListTopicSubscriptions" - }, - "parameters": [ - { - "name": "request", - "type": "google.pubsub_v1.types.ListTopicSubscriptionsRequest" - }, - { - "name": "topic", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.pubsub_v1.services.publisher.pagers.ListTopicSubscriptionsPager", - "shortName": "list_topic_subscriptions" - }, - "description": "Sample for ListTopicSubscriptions", - "file": "pubsub_v1_generated_publisher_list_topic_subscriptions_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "pubsub_v1_generated_Publisher_ListTopicSubscriptions_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": "pubsub_v1_generated_publisher_list_topic_subscriptions_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.pubsub_v1.PublisherAsyncClient", - "shortName": "PublisherAsyncClient" - }, - "fullName": "google.pubsub_v1.PublisherAsyncClient.list_topics", - "method": { - "fullName": "google.pubsub.v1.Publisher.ListTopics", - "service": { - "fullName": "google.pubsub.v1.Publisher", - "shortName": "Publisher" - }, - "shortName": "ListTopics" - }, - "parameters": [ - { - "name": "request", - "type": "google.pubsub_v1.types.ListTopicsRequest" - }, - { - "name": "project", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.pubsub_v1.services.publisher.pagers.ListTopicsAsyncPager", - "shortName": "list_topics" - }, - "description": "Sample for ListTopics", - "file": "pubsub_v1_generated_publisher_list_topics_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "pubsub_v1_generated_Publisher_ListTopics_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": "pubsub_v1_generated_publisher_list_topics_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.pubsub_v1.PublisherClient", - "shortName": "PublisherClient" - }, - "fullName": "google.pubsub_v1.PublisherClient.list_topics", - "method": { - "fullName": "google.pubsub.v1.Publisher.ListTopics", - "service": { - "fullName": "google.pubsub.v1.Publisher", - "shortName": "Publisher" - }, - "shortName": "ListTopics" - }, - "parameters": [ - { - "name": "request", - "type": "google.pubsub_v1.types.ListTopicsRequest" - }, - { - "name": "project", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.pubsub_v1.services.publisher.pagers.ListTopicsPager", - "shortName": "list_topics" - }, - "description": "Sample for ListTopics", - "file": "pubsub_v1_generated_publisher_list_topics_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "pubsub_v1_generated_Publisher_ListTopics_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": "pubsub_v1_generated_publisher_list_topics_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.pubsub_v1.PublisherAsyncClient", - "shortName": "PublisherAsyncClient" - }, - "fullName": "google.pubsub_v1.PublisherAsyncClient.publish", - "method": { - "fullName": "google.pubsub.v1.Publisher.Publish", - "service": { - "fullName": "google.pubsub.v1.Publisher", - "shortName": "Publisher" - }, - "shortName": "Publish" - }, - "parameters": [ - { - "name": "request", - "type": "google.pubsub_v1.types.PublishRequest" - }, - { - "name": "topic", - "type": "str" - }, - { - "name": "messages", - "type": "MutableSequence[google.pubsub_v1.types.PubsubMessage]" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.pubsub_v1.types.PublishResponse", - "shortName": "publish" - }, - "description": "Sample for Publish", - "file": "pubsub_v1_generated_publisher_publish_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "pubsub_v1_generated_Publisher_Publish_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": "pubsub_v1_generated_publisher_publish_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.pubsub_v1.PublisherClient", - "shortName": "PublisherClient" - }, - "fullName": "google.pubsub_v1.PublisherClient.publish", - "method": { - "fullName": "google.pubsub.v1.Publisher.Publish", - "service": { - "fullName": "google.pubsub.v1.Publisher", - "shortName": "Publisher" - }, - "shortName": "Publish" - }, - "parameters": [ - { - "name": "request", - "type": "google.pubsub_v1.types.PublishRequest" - }, - { - "name": "topic", - "type": "str" - }, - { - "name": "messages", - "type": "MutableSequence[google.pubsub_v1.types.PubsubMessage]" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.pubsub_v1.types.PublishResponse", - "shortName": "publish" - }, - "description": "Sample for Publish", - "file": "pubsub_v1_generated_publisher_publish_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "pubsub_v1_generated_Publisher_Publish_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": "pubsub_v1_generated_publisher_publish_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.pubsub_v1.PublisherAsyncClient", - "shortName": "PublisherAsyncClient" - }, - "fullName": "google.pubsub_v1.PublisherAsyncClient.update_topic", - "method": { - "fullName": "google.pubsub.v1.Publisher.UpdateTopic", - "service": { - "fullName": "google.pubsub.v1.Publisher", - "shortName": "Publisher" - }, - "shortName": "UpdateTopic" - }, - "parameters": [ - { - "name": "request", - "type": "google.pubsub_v1.types.UpdateTopicRequest" - }, - { - "name": "topic", - "type": "google.pubsub_v1.types.Topic" - }, - { - "name": "update_mask", - "type": "google.protobuf.field_mask_pb2.FieldMask" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.pubsub_v1.types.Topic", - "shortName": "update_topic" - }, - "description": "Sample for UpdateTopic", - "file": "pubsub_v1_generated_publisher_update_topic_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "pubsub_v1_generated_Publisher_UpdateTopic_async", - "segments": [ - { - "end": 54, - "start": 27, - "type": "FULL" - }, - { - "end": 54, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 48, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 51, - "start": 49, - "type": "REQUEST_EXECUTION" - }, - { - "end": 55, - "start": 52, - "type": "RESPONSE_HANDLING" - } - ], - "title": "pubsub_v1_generated_publisher_update_topic_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.pubsub_v1.PublisherClient", - "shortName": "PublisherClient" - }, - "fullName": "google.pubsub_v1.PublisherClient.update_topic", - "method": { - "fullName": "google.pubsub.v1.Publisher.UpdateTopic", - "service": { - "fullName": "google.pubsub.v1.Publisher", - "shortName": "Publisher" - }, - "shortName": "UpdateTopic" - }, - "parameters": [ - { - "name": "request", - "type": "google.pubsub_v1.types.UpdateTopicRequest" - }, - { - "name": "topic", - "type": "google.pubsub_v1.types.Topic" - }, - { - "name": "update_mask", - "type": "google.protobuf.field_mask_pb2.FieldMask" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.pubsub_v1.types.Topic", - "shortName": "update_topic" - }, - "description": "Sample for UpdateTopic", - "file": "pubsub_v1_generated_publisher_update_topic_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "pubsub_v1_generated_Publisher_UpdateTopic_sync", - "segments": [ - { - "end": 54, - "start": 27, - "type": "FULL" - }, - { - "end": 54, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 48, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 51, - "start": 49, - "type": "REQUEST_EXECUTION" - }, - { - "end": 55, - "start": 52, - "type": "RESPONSE_HANDLING" - } - ], - "title": "pubsub_v1_generated_publisher_update_topic_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.pubsub_v1.SchemaServiceAsyncClient", - "shortName": "SchemaServiceAsyncClient" - }, - "fullName": "google.pubsub_v1.SchemaServiceAsyncClient.commit_schema", - "method": { - "fullName": "google.pubsub.v1.SchemaService.CommitSchema", - "service": { - "fullName": "google.pubsub.v1.SchemaService", - "shortName": "SchemaService" - }, - "shortName": "CommitSchema" - }, - "parameters": [ - { - "name": "request", - "type": "google.pubsub_v1.types.CommitSchemaRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "schema", - "type": "google.pubsub_v1.types.Schema" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.pubsub_v1.types.Schema", - "shortName": "commit_schema" - }, - "description": "Sample for CommitSchema", - "file": "pubsub_v1_generated_schema_service_commit_schema_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "pubsub_v1_generated_SchemaService_CommitSchema_async", - "segments": [ - { - "end": 55, - "start": 27, - "type": "FULL" - }, - { - "end": 55, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 49, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 52, - "start": 50, - "type": "REQUEST_EXECUTION" - }, - { - "end": 56, - "start": 53, - "type": "RESPONSE_HANDLING" - } - ], - "title": "pubsub_v1_generated_schema_service_commit_schema_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.pubsub_v1.SchemaServiceClient", - "shortName": "SchemaServiceClient" - }, - "fullName": "google.pubsub_v1.SchemaServiceClient.commit_schema", - "method": { - "fullName": "google.pubsub.v1.SchemaService.CommitSchema", - "service": { - "fullName": "google.pubsub.v1.SchemaService", - "shortName": "SchemaService" - }, - "shortName": "CommitSchema" - }, - "parameters": [ - { - "name": "request", - "type": "google.pubsub_v1.types.CommitSchemaRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "schema", - "type": "google.pubsub_v1.types.Schema" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.pubsub_v1.types.Schema", - "shortName": "commit_schema" - }, - "description": "Sample for CommitSchema", - "file": "pubsub_v1_generated_schema_service_commit_schema_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "pubsub_v1_generated_SchemaService_CommitSchema_sync", - "segments": [ - { - "end": 55, - "start": 27, - "type": "FULL" - }, - { - "end": 55, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 49, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 52, - "start": 50, - "type": "REQUEST_EXECUTION" - }, - { - "end": 56, - "start": 53, - "type": "RESPONSE_HANDLING" - } - ], - "title": "pubsub_v1_generated_schema_service_commit_schema_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.pubsub_v1.SchemaServiceAsyncClient", - "shortName": "SchemaServiceAsyncClient" - }, - "fullName": "google.pubsub_v1.SchemaServiceAsyncClient.create_schema", - "method": { - "fullName": "google.pubsub.v1.SchemaService.CreateSchema", - "service": { - "fullName": "google.pubsub.v1.SchemaService", - "shortName": "SchemaService" - }, - "shortName": "CreateSchema" - }, - "parameters": [ - { - "name": "request", - "type": "google.pubsub_v1.types.CreateSchemaRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "schema", - "type": "google.pubsub_v1.types.Schema" - }, - { - "name": "schema_id", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.pubsub_v1.types.Schema", - "shortName": "create_schema" - }, - "description": "Sample for CreateSchema", - "file": "pubsub_v1_generated_schema_service_create_schema_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "pubsub_v1_generated_SchemaService_CreateSchema_async", - "segments": [ - { - "end": 55, - "start": 27, - "type": "FULL" - }, - { - "end": 55, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 49, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 52, - "start": 50, - "type": "REQUEST_EXECUTION" - }, - { - "end": 56, - "start": 53, - "type": "RESPONSE_HANDLING" - } - ], - "title": "pubsub_v1_generated_schema_service_create_schema_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.pubsub_v1.SchemaServiceClient", - "shortName": "SchemaServiceClient" - }, - "fullName": "google.pubsub_v1.SchemaServiceClient.create_schema", - "method": { - "fullName": "google.pubsub.v1.SchemaService.CreateSchema", - "service": { - "fullName": "google.pubsub.v1.SchemaService", - "shortName": "SchemaService" - }, - "shortName": "CreateSchema" - }, - "parameters": [ - { - "name": "request", - "type": "google.pubsub_v1.types.CreateSchemaRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "schema", - "type": "google.pubsub_v1.types.Schema" - }, - { - "name": "schema_id", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.pubsub_v1.types.Schema", - "shortName": "create_schema" - }, - "description": "Sample for CreateSchema", - "file": "pubsub_v1_generated_schema_service_create_schema_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "pubsub_v1_generated_SchemaService_CreateSchema_sync", - "segments": [ - { - "end": 55, - "start": 27, - "type": "FULL" - }, - { - "end": 55, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 49, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 52, - "start": 50, - "type": "REQUEST_EXECUTION" - }, - { - "end": 56, - "start": 53, - "type": "RESPONSE_HANDLING" - } - ], - "title": "pubsub_v1_generated_schema_service_create_schema_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.pubsub_v1.SchemaServiceAsyncClient", - "shortName": "SchemaServiceAsyncClient" - }, - "fullName": "google.pubsub_v1.SchemaServiceAsyncClient.delete_schema_revision", - "method": { - "fullName": "google.pubsub.v1.SchemaService.DeleteSchemaRevision", - "service": { - "fullName": "google.pubsub.v1.SchemaService", - "shortName": "SchemaService" - }, - "shortName": "DeleteSchemaRevision" - }, - "parameters": [ - { - "name": "request", - "type": "google.pubsub_v1.types.DeleteSchemaRevisionRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "revision_id", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.pubsub_v1.types.Schema", - "shortName": "delete_schema_revision" - }, - "description": "Sample for DeleteSchemaRevision", - "file": "pubsub_v1_generated_schema_service_delete_schema_revision_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "pubsub_v1_generated_SchemaService_DeleteSchemaRevision_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": "pubsub_v1_generated_schema_service_delete_schema_revision_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.pubsub_v1.SchemaServiceClient", - "shortName": "SchemaServiceClient" - }, - "fullName": "google.pubsub_v1.SchemaServiceClient.delete_schema_revision", - "method": { - "fullName": "google.pubsub.v1.SchemaService.DeleteSchemaRevision", - "service": { - "fullName": "google.pubsub.v1.SchemaService", - "shortName": "SchemaService" - }, - "shortName": "DeleteSchemaRevision" - }, - "parameters": [ - { - "name": "request", - "type": "google.pubsub_v1.types.DeleteSchemaRevisionRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "revision_id", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.pubsub_v1.types.Schema", - "shortName": "delete_schema_revision" - }, - "description": "Sample for DeleteSchemaRevision", - "file": "pubsub_v1_generated_schema_service_delete_schema_revision_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "pubsub_v1_generated_SchemaService_DeleteSchemaRevision_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": "pubsub_v1_generated_schema_service_delete_schema_revision_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.pubsub_v1.SchemaServiceAsyncClient", - "shortName": "SchemaServiceAsyncClient" - }, - "fullName": "google.pubsub_v1.SchemaServiceAsyncClient.delete_schema", - "method": { - "fullName": "google.pubsub.v1.SchemaService.DeleteSchema", - "service": { - "fullName": "google.pubsub.v1.SchemaService", - "shortName": "SchemaService" - }, - "shortName": "DeleteSchema" - }, - "parameters": [ - { - "name": "request", - "type": "google.pubsub_v1.types.DeleteSchemaRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "shortName": "delete_schema" - }, - "description": "Sample for DeleteSchema", - "file": "pubsub_v1_generated_schema_service_delete_schema_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "pubsub_v1_generated_SchemaService_DeleteSchema_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": "pubsub_v1_generated_schema_service_delete_schema_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.pubsub_v1.SchemaServiceClient", - "shortName": "SchemaServiceClient" - }, - "fullName": "google.pubsub_v1.SchemaServiceClient.delete_schema", - "method": { - "fullName": "google.pubsub.v1.SchemaService.DeleteSchema", - "service": { - "fullName": "google.pubsub.v1.SchemaService", - "shortName": "SchemaService" - }, - "shortName": "DeleteSchema" - }, - "parameters": [ - { - "name": "request", - "type": "google.pubsub_v1.types.DeleteSchemaRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "shortName": "delete_schema" - }, - "description": "Sample for DeleteSchema", - "file": "pubsub_v1_generated_schema_service_delete_schema_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "pubsub_v1_generated_SchemaService_DeleteSchema_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": "pubsub_v1_generated_schema_service_delete_schema_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.pubsub_v1.SchemaServiceAsyncClient", - "shortName": "SchemaServiceAsyncClient" - }, - "fullName": "google.pubsub_v1.SchemaServiceAsyncClient.get_schema", - "method": { - "fullName": "google.pubsub.v1.SchemaService.GetSchema", - "service": { - "fullName": "google.pubsub.v1.SchemaService", - "shortName": "SchemaService" - }, - "shortName": "GetSchema" - }, - "parameters": [ - { - "name": "request", - "type": "google.pubsub_v1.types.GetSchemaRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.pubsub_v1.types.Schema", - "shortName": "get_schema" - }, - "description": "Sample for GetSchema", - "file": "pubsub_v1_generated_schema_service_get_schema_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "pubsub_v1_generated_SchemaService_GetSchema_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": "pubsub_v1_generated_schema_service_get_schema_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.pubsub_v1.SchemaServiceClient", - "shortName": "SchemaServiceClient" - }, - "fullName": "google.pubsub_v1.SchemaServiceClient.get_schema", - "method": { - "fullName": "google.pubsub.v1.SchemaService.GetSchema", - "service": { - "fullName": "google.pubsub.v1.SchemaService", - "shortName": "SchemaService" - }, - "shortName": "GetSchema" - }, - "parameters": [ - { - "name": "request", - "type": "google.pubsub_v1.types.GetSchemaRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.pubsub_v1.types.Schema", - "shortName": "get_schema" - }, - "description": "Sample for GetSchema", - "file": "pubsub_v1_generated_schema_service_get_schema_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "pubsub_v1_generated_SchemaService_GetSchema_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": "pubsub_v1_generated_schema_service_get_schema_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.pubsub_v1.SchemaServiceAsyncClient", - "shortName": "SchemaServiceAsyncClient" - }, - "fullName": "google.pubsub_v1.SchemaServiceAsyncClient.list_schema_revisions", - "method": { - "fullName": "google.pubsub.v1.SchemaService.ListSchemaRevisions", - "service": { - "fullName": "google.pubsub.v1.SchemaService", - "shortName": "SchemaService" - }, - "shortName": "ListSchemaRevisions" - }, - "parameters": [ - { - "name": "request", - "type": "google.pubsub_v1.types.ListSchemaRevisionsRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.pubsub_v1.services.schema_service.pagers.ListSchemaRevisionsAsyncPager", - "shortName": "list_schema_revisions" - }, - "description": "Sample for ListSchemaRevisions", - "file": "pubsub_v1_generated_schema_service_list_schema_revisions_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "pubsub_v1_generated_SchemaService_ListSchemaRevisions_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": "pubsub_v1_generated_schema_service_list_schema_revisions_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.pubsub_v1.SchemaServiceClient", - "shortName": "SchemaServiceClient" - }, - "fullName": "google.pubsub_v1.SchemaServiceClient.list_schema_revisions", - "method": { - "fullName": "google.pubsub.v1.SchemaService.ListSchemaRevisions", - "service": { - "fullName": "google.pubsub.v1.SchemaService", - "shortName": "SchemaService" - }, - "shortName": "ListSchemaRevisions" - }, - "parameters": [ - { - "name": "request", - "type": "google.pubsub_v1.types.ListSchemaRevisionsRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.pubsub_v1.services.schema_service.pagers.ListSchemaRevisionsPager", - "shortName": "list_schema_revisions" - }, - "description": "Sample for ListSchemaRevisions", - "file": "pubsub_v1_generated_schema_service_list_schema_revisions_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "pubsub_v1_generated_SchemaService_ListSchemaRevisions_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": "pubsub_v1_generated_schema_service_list_schema_revisions_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.pubsub_v1.SchemaServiceAsyncClient", - "shortName": "SchemaServiceAsyncClient" - }, - "fullName": "google.pubsub_v1.SchemaServiceAsyncClient.list_schemas", - "method": { - "fullName": "google.pubsub.v1.SchemaService.ListSchemas", - "service": { - "fullName": "google.pubsub.v1.SchemaService", - "shortName": "SchemaService" - }, - "shortName": "ListSchemas" - }, - "parameters": [ - { - "name": "request", - "type": "google.pubsub_v1.types.ListSchemasRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.pubsub_v1.services.schema_service.pagers.ListSchemasAsyncPager", - "shortName": "list_schemas" - }, - "description": "Sample for ListSchemas", - "file": "pubsub_v1_generated_schema_service_list_schemas_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "pubsub_v1_generated_SchemaService_ListSchemas_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": "pubsub_v1_generated_schema_service_list_schemas_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.pubsub_v1.SchemaServiceClient", - "shortName": "SchemaServiceClient" - }, - "fullName": "google.pubsub_v1.SchemaServiceClient.list_schemas", - "method": { - "fullName": "google.pubsub.v1.SchemaService.ListSchemas", - "service": { - "fullName": "google.pubsub.v1.SchemaService", - "shortName": "SchemaService" - }, - "shortName": "ListSchemas" - }, - "parameters": [ - { - "name": "request", - "type": "google.pubsub_v1.types.ListSchemasRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.pubsub_v1.services.schema_service.pagers.ListSchemasPager", - "shortName": "list_schemas" - }, - "description": "Sample for ListSchemas", - "file": "pubsub_v1_generated_schema_service_list_schemas_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "pubsub_v1_generated_SchemaService_ListSchemas_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": "pubsub_v1_generated_schema_service_list_schemas_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.pubsub_v1.SchemaServiceAsyncClient", - "shortName": "SchemaServiceAsyncClient" - }, - "fullName": "google.pubsub_v1.SchemaServiceAsyncClient.rollback_schema", - "method": { - "fullName": "google.pubsub.v1.SchemaService.RollbackSchema", - "service": { - "fullName": "google.pubsub.v1.SchemaService", - "shortName": "SchemaService" - }, - "shortName": "RollbackSchema" - }, - "parameters": [ - { - "name": "request", - "type": "google.pubsub_v1.types.RollbackSchemaRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "revision_id", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.pubsub_v1.types.Schema", - "shortName": "rollback_schema" - }, - "description": "Sample for RollbackSchema", - "file": "pubsub_v1_generated_schema_service_rollback_schema_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "pubsub_v1_generated_SchemaService_RollbackSchema_async", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 46, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 49, - "start": 47, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 50, - "type": "RESPONSE_HANDLING" - } - ], - "title": "pubsub_v1_generated_schema_service_rollback_schema_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.pubsub_v1.SchemaServiceClient", - "shortName": "SchemaServiceClient" - }, - "fullName": "google.pubsub_v1.SchemaServiceClient.rollback_schema", - "method": { - "fullName": "google.pubsub.v1.SchemaService.RollbackSchema", - "service": { - "fullName": "google.pubsub.v1.SchemaService", - "shortName": "SchemaService" - }, - "shortName": "RollbackSchema" - }, - "parameters": [ - { - "name": "request", - "type": "google.pubsub_v1.types.RollbackSchemaRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "revision_id", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.pubsub_v1.types.Schema", - "shortName": "rollback_schema" - }, - "description": "Sample for RollbackSchema", - "file": "pubsub_v1_generated_schema_service_rollback_schema_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "pubsub_v1_generated_SchemaService_RollbackSchema_sync", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 46, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 49, - "start": 47, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 50, - "type": "RESPONSE_HANDLING" - } - ], - "title": "pubsub_v1_generated_schema_service_rollback_schema_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.pubsub_v1.SchemaServiceAsyncClient", - "shortName": "SchemaServiceAsyncClient" - }, - "fullName": "google.pubsub_v1.SchemaServiceAsyncClient.validate_message", - "method": { - "fullName": "google.pubsub.v1.SchemaService.ValidateMessage", - "service": { - "fullName": "google.pubsub.v1.SchemaService", - "shortName": "SchemaService" - }, - "shortName": "ValidateMessage" - }, - "parameters": [ - { - "name": "request", - "type": "google.pubsub_v1.types.ValidateMessageRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.pubsub_v1.types.ValidateMessageResponse", - "shortName": "validate_message" - }, - "description": "Sample for ValidateMessage", - "file": "pubsub_v1_generated_schema_service_validate_message_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "pubsub_v1_generated_SchemaService_ValidateMessage_async", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 46, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 49, - "start": 47, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 50, - "type": "RESPONSE_HANDLING" - } - ], - "title": "pubsub_v1_generated_schema_service_validate_message_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.pubsub_v1.SchemaServiceClient", - "shortName": "SchemaServiceClient" - }, - "fullName": "google.pubsub_v1.SchemaServiceClient.validate_message", - "method": { - "fullName": "google.pubsub.v1.SchemaService.ValidateMessage", - "service": { - "fullName": "google.pubsub.v1.SchemaService", - "shortName": "SchemaService" - }, - "shortName": "ValidateMessage" - }, - "parameters": [ - { - "name": "request", - "type": "google.pubsub_v1.types.ValidateMessageRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.pubsub_v1.types.ValidateMessageResponse", - "shortName": "validate_message" - }, - "description": "Sample for ValidateMessage", - "file": "pubsub_v1_generated_schema_service_validate_message_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "pubsub_v1_generated_SchemaService_ValidateMessage_sync", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 46, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 49, - "start": 47, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 50, - "type": "RESPONSE_HANDLING" - } - ], - "title": "pubsub_v1_generated_schema_service_validate_message_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.pubsub_v1.SchemaServiceAsyncClient", - "shortName": "SchemaServiceAsyncClient" - }, - "fullName": "google.pubsub_v1.SchemaServiceAsyncClient.validate_schema", - "method": { - "fullName": "google.pubsub.v1.SchemaService.ValidateSchema", - "service": { - "fullName": "google.pubsub.v1.SchemaService", - "shortName": "SchemaService" - }, - "shortName": "ValidateSchema" - }, - "parameters": [ - { - "name": "request", - "type": "google.pubsub_v1.types.ValidateSchemaRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "schema", - "type": "google.pubsub_v1.types.Schema" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.pubsub_v1.types.ValidateSchemaResponse", - "shortName": "validate_schema" - }, - "description": "Sample for ValidateSchema", - "file": "pubsub_v1_generated_schema_service_validate_schema_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "pubsub_v1_generated_SchemaService_ValidateSchema_async", - "segments": [ - { - "end": 55, - "start": 27, - "type": "FULL" - }, - { - "end": 55, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 49, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 52, - "start": 50, - "type": "REQUEST_EXECUTION" - }, - { - "end": 56, - "start": 53, - "type": "RESPONSE_HANDLING" - } - ], - "title": "pubsub_v1_generated_schema_service_validate_schema_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.pubsub_v1.SchemaServiceClient", - "shortName": "SchemaServiceClient" - }, - "fullName": "google.pubsub_v1.SchemaServiceClient.validate_schema", - "method": { - "fullName": "google.pubsub.v1.SchemaService.ValidateSchema", - "service": { - "fullName": "google.pubsub.v1.SchemaService", - "shortName": "SchemaService" - }, - "shortName": "ValidateSchema" - }, - "parameters": [ - { - "name": "request", - "type": "google.pubsub_v1.types.ValidateSchemaRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "schema", - "type": "google.pubsub_v1.types.Schema" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.pubsub_v1.types.ValidateSchemaResponse", - "shortName": "validate_schema" - }, - "description": "Sample for ValidateSchema", - "file": "pubsub_v1_generated_schema_service_validate_schema_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "pubsub_v1_generated_SchemaService_ValidateSchema_sync", - "segments": [ - { - "end": 55, - "start": 27, - "type": "FULL" - }, - { - "end": 55, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 49, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 52, - "start": 50, - "type": "REQUEST_EXECUTION" - }, - { - "end": 56, - "start": 53, - "type": "RESPONSE_HANDLING" - } - ], - "title": "pubsub_v1_generated_schema_service_validate_schema_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.pubsub_v1.SubscriberAsyncClient", - "shortName": "SubscriberAsyncClient" - }, - "fullName": "google.pubsub_v1.SubscriberAsyncClient.acknowledge", - "method": { - "fullName": "google.pubsub.v1.Subscriber.Acknowledge", - "service": { - "fullName": "google.pubsub.v1.Subscriber", - "shortName": "Subscriber" - }, - "shortName": "Acknowledge" - }, - "parameters": [ - { - "name": "request", - "type": "google.pubsub_v1.types.AcknowledgeRequest" - }, - { - "name": "subscription", - "type": "str" - }, - { - "name": "ack_ids", - "type": "MutableSequence[str]" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "shortName": "acknowledge" - }, - "description": "Sample for Acknowledge", - "file": "pubsub_v1_generated_subscriber_acknowledge_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "pubsub_v1_generated_Subscriber_Acknowledge_async", - "segments": [ - { - "end": 50, - "start": 27, - "type": "FULL" - }, - { - "end": 50, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 46, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "start": 47, - "type": "REQUEST_EXECUTION" - }, - { - "end": 51, - "type": "RESPONSE_HANDLING" - } - ], - "title": "pubsub_v1_generated_subscriber_acknowledge_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.pubsub_v1.SubscriberClient", - "shortName": "SubscriberClient" - }, - "fullName": "google.pubsub_v1.SubscriberClient.acknowledge", - "method": { - "fullName": "google.pubsub.v1.Subscriber.Acknowledge", - "service": { - "fullName": "google.pubsub.v1.Subscriber", - "shortName": "Subscriber" - }, - "shortName": "Acknowledge" - }, - "parameters": [ - { - "name": "request", - "type": "google.pubsub_v1.types.AcknowledgeRequest" - }, - { - "name": "subscription", - "type": "str" - }, - { - "name": "ack_ids", - "type": "MutableSequence[str]" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "shortName": "acknowledge" - }, - "description": "Sample for Acknowledge", - "file": "pubsub_v1_generated_subscriber_acknowledge_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "pubsub_v1_generated_Subscriber_Acknowledge_sync", - "segments": [ - { - "end": 50, - "start": 27, - "type": "FULL" - }, - { - "end": 50, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 46, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "start": 47, - "type": "REQUEST_EXECUTION" - }, - { - "end": 51, - "type": "RESPONSE_HANDLING" - } - ], - "title": "pubsub_v1_generated_subscriber_acknowledge_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.pubsub_v1.SubscriberAsyncClient", - "shortName": "SubscriberAsyncClient" - }, - "fullName": "google.pubsub_v1.SubscriberAsyncClient.create_snapshot", - "method": { - "fullName": "google.pubsub.v1.Subscriber.CreateSnapshot", - "service": { - "fullName": "google.pubsub.v1.Subscriber", - "shortName": "Subscriber" - }, - "shortName": "CreateSnapshot" - }, - "parameters": [ - { - "name": "request", - "type": "google.pubsub_v1.types.CreateSnapshotRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "subscription", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.pubsub_v1.types.Snapshot", - "shortName": "create_snapshot" - }, - "description": "Sample for CreateSnapshot", - "file": "pubsub_v1_generated_subscriber_create_snapshot_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "pubsub_v1_generated_Subscriber_CreateSnapshot_async", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 46, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 49, - "start": 47, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 50, - "type": "RESPONSE_HANDLING" - } - ], - "title": "pubsub_v1_generated_subscriber_create_snapshot_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.pubsub_v1.SubscriberClient", - "shortName": "SubscriberClient" - }, - "fullName": "google.pubsub_v1.SubscriberClient.create_snapshot", - "method": { - "fullName": "google.pubsub.v1.Subscriber.CreateSnapshot", - "service": { - "fullName": "google.pubsub.v1.Subscriber", - "shortName": "Subscriber" - }, - "shortName": "CreateSnapshot" - }, - "parameters": [ - { - "name": "request", - "type": "google.pubsub_v1.types.CreateSnapshotRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "subscription", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.pubsub_v1.types.Snapshot", - "shortName": "create_snapshot" - }, - "description": "Sample for CreateSnapshot", - "file": "pubsub_v1_generated_subscriber_create_snapshot_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "pubsub_v1_generated_Subscriber_CreateSnapshot_sync", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 46, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 49, - "start": 47, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 50, - "type": "RESPONSE_HANDLING" - } - ], - "title": "pubsub_v1_generated_subscriber_create_snapshot_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.pubsub_v1.SubscriberAsyncClient", - "shortName": "SubscriberAsyncClient" - }, - "fullName": "google.pubsub_v1.SubscriberAsyncClient.create_subscription", - "method": { - "fullName": "google.pubsub.v1.Subscriber.CreateSubscription", - "service": { - "fullName": "google.pubsub.v1.Subscriber", - "shortName": "Subscriber" - }, - "shortName": "CreateSubscription" - }, - "parameters": [ - { - "name": "request", - "type": "google.pubsub_v1.types.Subscription" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "topic", - "type": "str" - }, - { - "name": "push_config", - "type": "google.pubsub_v1.types.PushConfig" - }, - { - "name": "ack_deadline_seconds", - "type": "int" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.pubsub_v1.types.Subscription", - "shortName": "create_subscription" - }, - "description": "Sample for CreateSubscription", - "file": "pubsub_v1_generated_subscriber_create_subscription_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "pubsub_v1_generated_Subscriber_CreateSubscription_async", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 46, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 49, - "start": 47, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 50, - "type": "RESPONSE_HANDLING" - } - ], - "title": "pubsub_v1_generated_subscriber_create_subscription_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.pubsub_v1.SubscriberClient", - "shortName": "SubscriberClient" - }, - "fullName": "google.pubsub_v1.SubscriberClient.create_subscription", - "method": { - "fullName": "google.pubsub.v1.Subscriber.CreateSubscription", - "service": { - "fullName": "google.pubsub.v1.Subscriber", - "shortName": "Subscriber" - }, - "shortName": "CreateSubscription" - }, - "parameters": [ - { - "name": "request", - "type": "google.pubsub_v1.types.Subscription" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "topic", - "type": "str" - }, - { - "name": "push_config", - "type": "google.pubsub_v1.types.PushConfig" - }, - { - "name": "ack_deadline_seconds", - "type": "int" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.pubsub_v1.types.Subscription", - "shortName": "create_subscription" - }, - "description": "Sample for CreateSubscription", - "file": "pubsub_v1_generated_subscriber_create_subscription_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "pubsub_v1_generated_Subscriber_CreateSubscription_sync", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 46, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 49, - "start": 47, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 50, - "type": "RESPONSE_HANDLING" - } - ], - "title": "pubsub_v1_generated_subscriber_create_subscription_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.pubsub_v1.SubscriberAsyncClient", - "shortName": "SubscriberAsyncClient" - }, - "fullName": "google.pubsub_v1.SubscriberAsyncClient.delete_snapshot", - "method": { - "fullName": "google.pubsub.v1.Subscriber.DeleteSnapshot", - "service": { - "fullName": "google.pubsub.v1.Subscriber", - "shortName": "Subscriber" - }, - "shortName": "DeleteSnapshot" - }, - "parameters": [ - { - "name": "request", - "type": "google.pubsub_v1.types.DeleteSnapshotRequest" - }, - { - "name": "snapshot", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "shortName": "delete_snapshot" - }, - "description": "Sample for DeleteSnapshot", - "file": "pubsub_v1_generated_subscriber_delete_snapshot_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "pubsub_v1_generated_Subscriber_DeleteSnapshot_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": "pubsub_v1_generated_subscriber_delete_snapshot_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.pubsub_v1.SubscriberClient", - "shortName": "SubscriberClient" - }, - "fullName": "google.pubsub_v1.SubscriberClient.delete_snapshot", - "method": { - "fullName": "google.pubsub.v1.Subscriber.DeleteSnapshot", - "service": { - "fullName": "google.pubsub.v1.Subscriber", - "shortName": "Subscriber" - }, - "shortName": "DeleteSnapshot" - }, - "parameters": [ - { - "name": "request", - "type": "google.pubsub_v1.types.DeleteSnapshotRequest" - }, - { - "name": "snapshot", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "shortName": "delete_snapshot" - }, - "description": "Sample for DeleteSnapshot", - "file": "pubsub_v1_generated_subscriber_delete_snapshot_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "pubsub_v1_generated_Subscriber_DeleteSnapshot_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": "pubsub_v1_generated_subscriber_delete_snapshot_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.pubsub_v1.SubscriberAsyncClient", - "shortName": "SubscriberAsyncClient" - }, - "fullName": "google.pubsub_v1.SubscriberAsyncClient.delete_subscription", - "method": { - "fullName": "google.pubsub.v1.Subscriber.DeleteSubscription", - "service": { - "fullName": "google.pubsub.v1.Subscriber", - "shortName": "Subscriber" - }, - "shortName": "DeleteSubscription" - }, - "parameters": [ - { - "name": "request", - "type": "google.pubsub_v1.types.DeleteSubscriptionRequest" - }, - { - "name": "subscription", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "shortName": "delete_subscription" - }, - "description": "Sample for DeleteSubscription", - "file": "pubsub_v1_generated_subscriber_delete_subscription_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "pubsub_v1_generated_Subscriber_DeleteSubscription_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": "pubsub_v1_generated_subscriber_delete_subscription_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.pubsub_v1.SubscriberClient", - "shortName": "SubscriberClient" - }, - "fullName": "google.pubsub_v1.SubscriberClient.delete_subscription", - "method": { - "fullName": "google.pubsub.v1.Subscriber.DeleteSubscription", - "service": { - "fullName": "google.pubsub.v1.Subscriber", - "shortName": "Subscriber" - }, - "shortName": "DeleteSubscription" - }, - "parameters": [ - { - "name": "request", - "type": "google.pubsub_v1.types.DeleteSubscriptionRequest" - }, - { - "name": "subscription", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "shortName": "delete_subscription" - }, - "description": "Sample for DeleteSubscription", - "file": "pubsub_v1_generated_subscriber_delete_subscription_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "pubsub_v1_generated_Subscriber_DeleteSubscription_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": "pubsub_v1_generated_subscriber_delete_subscription_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.pubsub_v1.SubscriberAsyncClient", - "shortName": "SubscriberAsyncClient" - }, - "fullName": "google.pubsub_v1.SubscriberAsyncClient.get_snapshot", - "method": { - "fullName": "google.pubsub.v1.Subscriber.GetSnapshot", - "service": { - "fullName": "google.pubsub.v1.Subscriber", - "shortName": "Subscriber" - }, - "shortName": "GetSnapshot" - }, - "parameters": [ - { - "name": "request", - "type": "google.pubsub_v1.types.GetSnapshotRequest" - }, - { - "name": "snapshot", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.pubsub_v1.types.Snapshot", - "shortName": "get_snapshot" - }, - "description": "Sample for GetSnapshot", - "file": "pubsub_v1_generated_subscriber_get_snapshot_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "pubsub_v1_generated_Subscriber_GetSnapshot_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": "pubsub_v1_generated_subscriber_get_snapshot_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.pubsub_v1.SubscriberClient", - "shortName": "SubscriberClient" - }, - "fullName": "google.pubsub_v1.SubscriberClient.get_snapshot", - "method": { - "fullName": "google.pubsub.v1.Subscriber.GetSnapshot", - "service": { - "fullName": "google.pubsub.v1.Subscriber", - "shortName": "Subscriber" - }, - "shortName": "GetSnapshot" - }, - "parameters": [ - { - "name": "request", - "type": "google.pubsub_v1.types.GetSnapshotRequest" - }, - { - "name": "snapshot", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.pubsub_v1.types.Snapshot", - "shortName": "get_snapshot" - }, - "description": "Sample for GetSnapshot", - "file": "pubsub_v1_generated_subscriber_get_snapshot_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "pubsub_v1_generated_Subscriber_GetSnapshot_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": "pubsub_v1_generated_subscriber_get_snapshot_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.pubsub_v1.SubscriberAsyncClient", - "shortName": "SubscriberAsyncClient" - }, - "fullName": "google.pubsub_v1.SubscriberAsyncClient.get_subscription", - "method": { - "fullName": "google.pubsub.v1.Subscriber.GetSubscription", - "service": { - "fullName": "google.pubsub.v1.Subscriber", - "shortName": "Subscriber" - }, - "shortName": "GetSubscription" - }, - "parameters": [ - { - "name": "request", - "type": "google.pubsub_v1.types.GetSubscriptionRequest" - }, - { - "name": "subscription", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.pubsub_v1.types.Subscription", - "shortName": "get_subscription" - }, - "description": "Sample for GetSubscription", - "file": "pubsub_v1_generated_subscriber_get_subscription_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "pubsub_v1_generated_Subscriber_GetSubscription_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": "pubsub_v1_generated_subscriber_get_subscription_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.pubsub_v1.SubscriberClient", - "shortName": "SubscriberClient" - }, - "fullName": "google.pubsub_v1.SubscriberClient.get_subscription", - "method": { - "fullName": "google.pubsub.v1.Subscriber.GetSubscription", - "service": { - "fullName": "google.pubsub.v1.Subscriber", - "shortName": "Subscriber" - }, - "shortName": "GetSubscription" - }, - "parameters": [ - { - "name": "request", - "type": "google.pubsub_v1.types.GetSubscriptionRequest" - }, - { - "name": "subscription", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.pubsub_v1.types.Subscription", - "shortName": "get_subscription" - }, - "description": "Sample for GetSubscription", - "file": "pubsub_v1_generated_subscriber_get_subscription_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "pubsub_v1_generated_Subscriber_GetSubscription_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": "pubsub_v1_generated_subscriber_get_subscription_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.pubsub_v1.SubscriberAsyncClient", - "shortName": "SubscriberAsyncClient" - }, - "fullName": "google.pubsub_v1.SubscriberAsyncClient.list_snapshots", - "method": { - "fullName": "google.pubsub.v1.Subscriber.ListSnapshots", - "service": { - "fullName": "google.pubsub.v1.Subscriber", - "shortName": "Subscriber" - }, - "shortName": "ListSnapshots" - }, - "parameters": [ - { - "name": "request", - "type": "google.pubsub_v1.types.ListSnapshotsRequest" - }, - { - "name": "project", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.pubsub_v1.services.subscriber.pagers.ListSnapshotsAsyncPager", - "shortName": "list_snapshots" - }, - "description": "Sample for ListSnapshots", - "file": "pubsub_v1_generated_subscriber_list_snapshots_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "pubsub_v1_generated_Subscriber_ListSnapshots_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": "pubsub_v1_generated_subscriber_list_snapshots_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.pubsub_v1.SubscriberClient", - "shortName": "SubscriberClient" - }, - "fullName": "google.pubsub_v1.SubscriberClient.list_snapshots", - "method": { - "fullName": "google.pubsub.v1.Subscriber.ListSnapshots", - "service": { - "fullName": "google.pubsub.v1.Subscriber", - "shortName": "Subscriber" - }, - "shortName": "ListSnapshots" - }, - "parameters": [ - { - "name": "request", - "type": "google.pubsub_v1.types.ListSnapshotsRequest" - }, - { - "name": "project", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.pubsub_v1.services.subscriber.pagers.ListSnapshotsPager", - "shortName": "list_snapshots" - }, - "description": "Sample for ListSnapshots", - "file": "pubsub_v1_generated_subscriber_list_snapshots_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "pubsub_v1_generated_Subscriber_ListSnapshots_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": "pubsub_v1_generated_subscriber_list_snapshots_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.pubsub_v1.SubscriberAsyncClient", - "shortName": "SubscriberAsyncClient" - }, - "fullName": "google.pubsub_v1.SubscriberAsyncClient.list_subscriptions", - "method": { - "fullName": "google.pubsub.v1.Subscriber.ListSubscriptions", - "service": { - "fullName": "google.pubsub.v1.Subscriber", - "shortName": "Subscriber" - }, - "shortName": "ListSubscriptions" - }, - "parameters": [ - { - "name": "request", - "type": "google.pubsub_v1.types.ListSubscriptionsRequest" - }, - { - "name": "project", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.pubsub_v1.services.subscriber.pagers.ListSubscriptionsAsyncPager", - "shortName": "list_subscriptions" - }, - "description": "Sample for ListSubscriptions", - "file": "pubsub_v1_generated_subscriber_list_subscriptions_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "pubsub_v1_generated_Subscriber_ListSubscriptions_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": "pubsub_v1_generated_subscriber_list_subscriptions_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.pubsub_v1.SubscriberClient", - "shortName": "SubscriberClient" - }, - "fullName": "google.pubsub_v1.SubscriberClient.list_subscriptions", - "method": { - "fullName": "google.pubsub.v1.Subscriber.ListSubscriptions", - "service": { - "fullName": "google.pubsub.v1.Subscriber", - "shortName": "Subscriber" - }, - "shortName": "ListSubscriptions" - }, - "parameters": [ - { - "name": "request", - "type": "google.pubsub_v1.types.ListSubscriptionsRequest" - }, - { - "name": "project", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.pubsub_v1.services.subscriber.pagers.ListSubscriptionsPager", - "shortName": "list_subscriptions" - }, - "description": "Sample for ListSubscriptions", - "file": "pubsub_v1_generated_subscriber_list_subscriptions_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "pubsub_v1_generated_Subscriber_ListSubscriptions_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": "pubsub_v1_generated_subscriber_list_subscriptions_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.pubsub_v1.SubscriberAsyncClient", - "shortName": "SubscriberAsyncClient" - }, - "fullName": "google.pubsub_v1.SubscriberAsyncClient.modify_ack_deadline", - "method": { - "fullName": "google.pubsub.v1.Subscriber.ModifyAckDeadline", - "service": { - "fullName": "google.pubsub.v1.Subscriber", - "shortName": "Subscriber" - }, - "shortName": "ModifyAckDeadline" - }, - "parameters": [ - { - "name": "request", - "type": "google.pubsub_v1.types.ModifyAckDeadlineRequest" - }, - { - "name": "subscription", - "type": "str" - }, - { - "name": "ack_ids", - "type": "MutableSequence[str]" - }, - { - "name": "ack_deadline_seconds", - "type": "int" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "shortName": "modify_ack_deadline" - }, - "description": "Sample for ModifyAckDeadline", - "file": "pubsub_v1_generated_subscriber_modify_ack_deadline_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "pubsub_v1_generated_Subscriber_ModifyAckDeadline_async", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 47, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "start": 48, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "type": "RESPONSE_HANDLING" - } - ], - "title": "pubsub_v1_generated_subscriber_modify_ack_deadline_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.pubsub_v1.SubscriberClient", - "shortName": "SubscriberClient" - }, - "fullName": "google.pubsub_v1.SubscriberClient.modify_ack_deadline", - "method": { - "fullName": "google.pubsub.v1.Subscriber.ModifyAckDeadline", - "service": { - "fullName": "google.pubsub.v1.Subscriber", - "shortName": "Subscriber" - }, - "shortName": "ModifyAckDeadline" - }, - "parameters": [ - { - "name": "request", - "type": "google.pubsub_v1.types.ModifyAckDeadlineRequest" - }, - { - "name": "subscription", - "type": "str" - }, - { - "name": "ack_ids", - "type": "MutableSequence[str]" - }, - { - "name": "ack_deadline_seconds", - "type": "int" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "shortName": "modify_ack_deadline" - }, - "description": "Sample for ModifyAckDeadline", - "file": "pubsub_v1_generated_subscriber_modify_ack_deadline_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "pubsub_v1_generated_Subscriber_ModifyAckDeadline_sync", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 47, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "start": 48, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "type": "RESPONSE_HANDLING" - } - ], - "title": "pubsub_v1_generated_subscriber_modify_ack_deadline_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.pubsub_v1.SubscriberAsyncClient", - "shortName": "SubscriberAsyncClient" - }, - "fullName": "google.pubsub_v1.SubscriberAsyncClient.modify_push_config", - "method": { - "fullName": "google.pubsub.v1.Subscriber.ModifyPushConfig", - "service": { - "fullName": "google.pubsub.v1.Subscriber", - "shortName": "Subscriber" - }, - "shortName": "ModifyPushConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.pubsub_v1.types.ModifyPushConfigRequest" - }, - { - "name": "subscription", - "type": "str" - }, - { - "name": "push_config", - "type": "google.pubsub_v1.types.PushConfig" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "shortName": "modify_push_config" - }, - "description": "Sample for ModifyPushConfig", - "file": "pubsub_v1_generated_subscriber_modify_push_config_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "pubsub_v1_generated_Subscriber_ModifyPushConfig_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": "pubsub_v1_generated_subscriber_modify_push_config_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.pubsub_v1.SubscriberClient", - "shortName": "SubscriberClient" - }, - "fullName": "google.pubsub_v1.SubscriberClient.modify_push_config", - "method": { - "fullName": "google.pubsub.v1.Subscriber.ModifyPushConfig", - "service": { - "fullName": "google.pubsub.v1.Subscriber", - "shortName": "Subscriber" - }, - "shortName": "ModifyPushConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.pubsub_v1.types.ModifyPushConfigRequest" - }, - { - "name": "subscription", - "type": "str" - }, - { - "name": "push_config", - "type": "google.pubsub_v1.types.PushConfig" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "shortName": "modify_push_config" - }, - "description": "Sample for ModifyPushConfig", - "file": "pubsub_v1_generated_subscriber_modify_push_config_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "pubsub_v1_generated_Subscriber_ModifyPushConfig_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": "pubsub_v1_generated_subscriber_modify_push_config_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.pubsub_v1.SubscriberAsyncClient", - "shortName": "SubscriberAsyncClient" - }, - "fullName": "google.pubsub_v1.SubscriberAsyncClient.pull", - "method": { - "fullName": "google.pubsub.v1.Subscriber.Pull", - "service": { - "fullName": "google.pubsub.v1.Subscriber", - "shortName": "Subscriber" - }, - "shortName": "Pull" - }, - "parameters": [ - { - "name": "request", - "type": "google.pubsub_v1.types.PullRequest" - }, - { - "name": "subscription", - "type": "str" - }, - { - "name": "return_immediately", - "type": "bool" - }, - { - "name": "max_messages", - "type": "int" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.pubsub_v1.types.PullResponse", - "shortName": "pull" - }, - "description": "Sample for Pull", - "file": "pubsub_v1_generated_subscriber_pull_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "pubsub_v1_generated_Subscriber_Pull_async", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 46, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 49, - "start": 47, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 50, - "type": "RESPONSE_HANDLING" - } - ], - "title": "pubsub_v1_generated_subscriber_pull_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.pubsub_v1.SubscriberClient", - "shortName": "SubscriberClient" - }, - "fullName": "google.pubsub_v1.SubscriberClient.pull", - "method": { - "fullName": "google.pubsub.v1.Subscriber.Pull", - "service": { - "fullName": "google.pubsub.v1.Subscriber", - "shortName": "Subscriber" - }, - "shortName": "Pull" - }, - "parameters": [ - { - "name": "request", - "type": "google.pubsub_v1.types.PullRequest" - }, - { - "name": "subscription", - "type": "str" - }, - { - "name": "return_immediately", - "type": "bool" - }, - { - "name": "max_messages", - "type": "int" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.pubsub_v1.types.PullResponse", - "shortName": "pull" - }, - "description": "Sample for Pull", - "file": "pubsub_v1_generated_subscriber_pull_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "pubsub_v1_generated_Subscriber_Pull_sync", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 46, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 49, - "start": 47, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 50, - "type": "RESPONSE_HANDLING" - } - ], - "title": "pubsub_v1_generated_subscriber_pull_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.pubsub_v1.SubscriberAsyncClient", - "shortName": "SubscriberAsyncClient" - }, - "fullName": "google.pubsub_v1.SubscriberAsyncClient.seek", - "method": { - "fullName": "google.pubsub.v1.Subscriber.Seek", - "service": { - "fullName": "google.pubsub.v1.Subscriber", - "shortName": "Subscriber" - }, - "shortName": "Seek" - }, - "parameters": [ - { - "name": "request", - "type": "google.pubsub_v1.types.SeekRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.pubsub_v1.types.SeekResponse", - "shortName": "seek" - }, - "description": "Sample for Seek", - "file": "pubsub_v1_generated_subscriber_seek_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "pubsub_v1_generated_Subscriber_Seek_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": "pubsub_v1_generated_subscriber_seek_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.pubsub_v1.SubscriberClient", - "shortName": "SubscriberClient" - }, - "fullName": "google.pubsub_v1.SubscriberClient.seek", - "method": { - "fullName": "google.pubsub.v1.Subscriber.Seek", - "service": { - "fullName": "google.pubsub.v1.Subscriber", - "shortName": "Subscriber" - }, - "shortName": "Seek" - }, - "parameters": [ - { - "name": "request", - "type": "google.pubsub_v1.types.SeekRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.pubsub_v1.types.SeekResponse", - "shortName": "seek" - }, - "description": "Sample for Seek", - "file": "pubsub_v1_generated_subscriber_seek_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "pubsub_v1_generated_Subscriber_Seek_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": "pubsub_v1_generated_subscriber_seek_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.pubsub_v1.SubscriberAsyncClient", - "shortName": "SubscriberAsyncClient" - }, - "fullName": "google.pubsub_v1.SubscriberAsyncClient.streaming_pull", - "method": { - "fullName": "google.pubsub.v1.Subscriber.StreamingPull", - "service": { - "fullName": "google.pubsub.v1.Subscriber", - "shortName": "Subscriber" - }, - "shortName": "StreamingPull" - }, - "parameters": [ - { - "name": "requests", - "type": "Iterator[google.pubsub_v1.types.StreamingPullRequest]" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "Iterable[google.pubsub_v1.types.StreamingPullResponse]", - "shortName": "streaming_pull" - }, - "description": "Sample for StreamingPull", - "file": "pubsub_v1_generated_subscriber_streaming_pull_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "pubsub_v1_generated_Subscriber_StreamingPull_async", - "segments": [ - { - "end": 63, - "start": 27, - "type": "FULL" - }, - { - "end": 63, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 56, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 59, - "start": 57, - "type": "REQUEST_EXECUTION" - }, - { - "end": 64, - "start": 60, - "type": "RESPONSE_HANDLING" - } - ], - "title": "pubsub_v1_generated_subscriber_streaming_pull_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.pubsub_v1.SubscriberClient", - "shortName": "SubscriberClient" - }, - "fullName": "google.pubsub_v1.SubscriberClient.streaming_pull", - "method": { - "fullName": "google.pubsub.v1.Subscriber.StreamingPull", - "service": { - "fullName": "google.pubsub.v1.Subscriber", - "shortName": "Subscriber" - }, - "shortName": "StreamingPull" - }, - "parameters": [ - { - "name": "requests", - "type": "Iterator[google.pubsub_v1.types.StreamingPullRequest]" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "Iterable[google.pubsub_v1.types.StreamingPullResponse]", - "shortName": "streaming_pull" - }, - "description": "Sample for StreamingPull", - "file": "pubsub_v1_generated_subscriber_streaming_pull_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "pubsub_v1_generated_Subscriber_StreamingPull_sync", - "segments": [ - { - "end": 63, - "start": 27, - "type": "FULL" - }, - { - "end": 63, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 56, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 59, - "start": 57, - "type": "REQUEST_EXECUTION" - }, - { - "end": 64, - "start": 60, - "type": "RESPONSE_HANDLING" - } - ], - "title": "pubsub_v1_generated_subscriber_streaming_pull_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.pubsub_v1.SubscriberAsyncClient", - "shortName": "SubscriberAsyncClient" - }, - "fullName": "google.pubsub_v1.SubscriberAsyncClient.update_snapshot", - "method": { - "fullName": "google.pubsub.v1.Subscriber.UpdateSnapshot", - "service": { - "fullName": "google.pubsub.v1.Subscriber", - "shortName": "Subscriber" - }, - "shortName": "UpdateSnapshot" - }, - "parameters": [ - { - "name": "request", - "type": "google.pubsub_v1.types.UpdateSnapshotRequest" - }, - { - "name": "snapshot", - "type": "google.pubsub_v1.types.Snapshot" - }, - { - "name": "update_mask", - "type": "google.protobuf.field_mask_pb2.FieldMask" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.pubsub_v1.types.Snapshot", - "shortName": "update_snapshot" - }, - "description": "Sample for UpdateSnapshot", - "file": "pubsub_v1_generated_subscriber_update_snapshot_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "pubsub_v1_generated_Subscriber_UpdateSnapshot_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": "pubsub_v1_generated_subscriber_update_snapshot_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.pubsub_v1.SubscriberClient", - "shortName": "SubscriberClient" - }, - "fullName": "google.pubsub_v1.SubscriberClient.update_snapshot", - "method": { - "fullName": "google.pubsub.v1.Subscriber.UpdateSnapshot", - "service": { - "fullName": "google.pubsub.v1.Subscriber", - "shortName": "Subscriber" - }, - "shortName": "UpdateSnapshot" - }, - "parameters": [ - { - "name": "request", - "type": "google.pubsub_v1.types.UpdateSnapshotRequest" - }, - { - "name": "snapshot", - "type": "google.pubsub_v1.types.Snapshot" - }, - { - "name": "update_mask", - "type": "google.protobuf.field_mask_pb2.FieldMask" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.pubsub_v1.types.Snapshot", - "shortName": "update_snapshot" - }, - "description": "Sample for UpdateSnapshot", - "file": "pubsub_v1_generated_subscriber_update_snapshot_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "pubsub_v1_generated_Subscriber_UpdateSnapshot_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": "pubsub_v1_generated_subscriber_update_snapshot_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.pubsub_v1.SubscriberAsyncClient", - "shortName": "SubscriberAsyncClient" - }, - "fullName": "google.pubsub_v1.SubscriberAsyncClient.update_subscription", - "method": { - "fullName": "google.pubsub.v1.Subscriber.UpdateSubscription", - "service": { - "fullName": "google.pubsub.v1.Subscriber", - "shortName": "Subscriber" - }, - "shortName": "UpdateSubscription" - }, - "parameters": [ - { - "name": "request", - "type": "google.pubsub_v1.types.UpdateSubscriptionRequest" - }, - { - "name": "subscription", - "type": "google.pubsub_v1.types.Subscription" - }, - { - "name": "update_mask", - "type": "google.protobuf.field_mask_pb2.FieldMask" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.pubsub_v1.types.Subscription", - "shortName": "update_subscription" - }, - "description": "Sample for UpdateSubscription", - "file": "pubsub_v1_generated_subscriber_update_subscription_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "pubsub_v1_generated_Subscriber_UpdateSubscription_async", - "segments": [ - { - "end": 55, - "start": 27, - "type": "FULL" - }, - { - "end": 55, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 49, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 52, - "start": 50, - "type": "REQUEST_EXECUTION" - }, - { - "end": 56, - "start": 53, - "type": "RESPONSE_HANDLING" - } - ], - "title": "pubsub_v1_generated_subscriber_update_subscription_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.pubsub_v1.SubscriberClient", - "shortName": "SubscriberClient" - }, - "fullName": "google.pubsub_v1.SubscriberClient.update_subscription", - "method": { - "fullName": "google.pubsub.v1.Subscriber.UpdateSubscription", - "service": { - "fullName": "google.pubsub.v1.Subscriber", - "shortName": "Subscriber" - }, - "shortName": "UpdateSubscription" - }, - "parameters": [ - { - "name": "request", - "type": "google.pubsub_v1.types.UpdateSubscriptionRequest" - }, - { - "name": "subscription", - "type": "google.pubsub_v1.types.Subscription" - }, - { - "name": "update_mask", - "type": "google.protobuf.field_mask_pb2.FieldMask" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.pubsub_v1.types.Subscription", - "shortName": "update_subscription" - }, - "description": "Sample for UpdateSubscription", - "file": "pubsub_v1_generated_subscriber_update_subscription_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "pubsub_v1_generated_Subscriber_UpdateSubscription_sync", - "segments": [ - { - "end": 55, - "start": 27, - "type": "FULL" - }, - { - "end": 55, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 49, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 52, - "start": 50, - "type": "REQUEST_EXECUTION" - }, - { - "end": 56, - "start": 53, - "type": "RESPONSE_HANDLING" - } - ], - "title": "pubsub_v1_generated_subscriber_update_subscription_sync.py" - } - ] -} diff --git a/owl-bot-staging/v1/scripts/fixup_pubsub_v1_keywords.py b/owl-bot-staging/v1/scripts/fixup_pubsub_v1_keywords.py deleted file mode 100644 index 35262ea8d..000000000 --- a/owl-bot-staging/v1/scripts/fixup_pubsub_v1_keywords.py +++ /dev/null @@ -1,213 +0,0 @@ -#! /usr/bin/env python3 -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import argparse -import os -import libcst as cst -import pathlib -import sys -from typing import (Any, Callable, Dict, List, Sequence, Tuple) - - -def partition( - predicate: Callable[[Any], bool], - iterator: Sequence[Any] -) -> Tuple[List[Any], List[Any]]: - """A stable, out-of-place partition.""" - results = ([], []) - - for i in iterator: - results[int(predicate(i))].append(i) - - # Returns trueList, falseList - return results[1], results[0] - - -class pubsubCallTransformer(cst.CSTTransformer): - CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') - METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { - 'acknowledge': ('subscription', 'ack_ids', ), - 'commit_schema': ('name', 'schema', ), - 'create_schema': ('parent', 'schema', 'schema_id', ), - 'create_snapshot': ('name', 'subscription', 'labels', ), - 'create_subscription': ('name', 'topic', 'push_config', 'bigquery_config', 'cloud_storage_config', 'ack_deadline_seconds', 'retain_acked_messages', 'message_retention_duration', 'labels', 'enable_message_ordering', 'expiration_policy', 'filter', 'dead_letter_policy', 'retry_policy', 'detached', 'enable_exactly_once_delivery', 'topic_message_retention_duration', 'state', ), - 'create_topic': ('name', 'labels', 'message_storage_policy', 'kms_key_name', 'schema_settings', 'satisfies_pzs', 'message_retention_duration', 'state', 'ingestion_data_source_settings', ), - 'delete_schema': ('name', ), - 'delete_schema_revision': ('name', 'revision_id', ), - 'delete_snapshot': ('snapshot', ), - 'delete_subscription': ('subscription', ), - 'delete_topic': ('topic', ), - 'detach_subscription': ('subscription', ), - 'get_schema': ('name', 'view', ), - 'get_snapshot': ('snapshot', ), - 'get_subscription': ('subscription', ), - 'get_topic': ('topic', ), - 'list_schema_revisions': ('name', 'view', 'page_size', 'page_token', ), - 'list_schemas': ('parent', 'view', 'page_size', 'page_token', ), - 'list_snapshots': ('project', 'page_size', 'page_token', ), - 'list_subscriptions': ('project', 'page_size', 'page_token', ), - 'list_topics': ('project', 'page_size', 'page_token', ), - 'list_topic_snapshots': ('topic', 'page_size', 'page_token', ), - 'list_topic_subscriptions': ('topic', 'page_size', 'page_token', ), - 'modify_ack_deadline': ('subscription', 'ack_ids', 'ack_deadline_seconds', ), - 'modify_push_config': ('subscription', 'push_config', ), - 'publish': ('topic', 'messages', ), - 'pull': ('subscription', 'max_messages', 'return_immediately', ), - 'rollback_schema': ('name', 'revision_id', ), - 'seek': ('subscription', 'time', 'snapshot', ), - 'streaming_pull': ('subscription', 'stream_ack_deadline_seconds', 'ack_ids', 'modify_deadline_seconds', 'modify_deadline_ack_ids', 'client_id', 'max_outstanding_messages', 'max_outstanding_bytes', ), - 'update_snapshot': ('snapshot', 'update_mask', ), - 'update_subscription': ('subscription', 'update_mask', ), - 'update_topic': ('topic', 'update_mask', ), - 'validate_message': ('parent', 'name', 'schema', 'message', 'encoding', ), - 'validate_schema': ('parent', 'schema', ), - 'get_iam_policy': ('resource', 'options', ), - 'set_iam_policy': ('resource', 'policy', ), - 'test_iam_permissions': ('resource', 'permissions', ), - } - - def leave_Call(self, original: cst.Call, updated: cst.Call) -> cst.CSTNode: - try: - key = original.func.attr.value - kword_params = self.METHOD_TO_PARAMS[key] - except (AttributeError, KeyError): - # Either not a method from the API or too convoluted to be sure. - return updated - - # If the existing code is valid, keyword args come after positional args. - # Therefore, all positional args must map to the first parameters. - args, kwargs = partition(lambda a: not bool(a.keyword), updated.args) - if any(k.keyword.value == "request" for k in kwargs): - # We've already fixed this file, don't fix it again. - return updated - - kwargs, ctrl_kwargs = partition( - lambda a: a.keyword.value not in self.CTRL_PARAMS, - kwargs - ) - - args, ctrl_args = args[:len(kword_params)], args[len(kword_params):] - ctrl_kwargs.extend(cst.Arg(value=a.value, keyword=cst.Name(value=ctrl)) - for a, ctrl in zip(ctrl_args, self.CTRL_PARAMS)) - - request_arg = cst.Arg( - value=cst.Dict([ - cst.DictElement( - cst.SimpleString("'{}'".format(name)), -cst.Element(value=arg.value) - ) - # Note: the args + kwargs looks silly, but keep in mind that - # the control parameters had to be stripped out, and that - # those could have been passed positionally or by keyword. - for name, arg in zip(kword_params, args + kwargs)]), - keyword=cst.Name("request") - ) - - return updated.with_changes( - args=[request_arg] + ctrl_kwargs - ) - - -def fix_files( - in_dir: pathlib.Path, - out_dir: pathlib.Path, - *, - transformer=pubsubCallTransformer(), -): - """Duplicate the input dir to the output dir, fixing file method calls. - - Preconditions: - * in_dir is a real directory - * out_dir is a real, empty directory - """ - pyfile_gen = ( - pathlib.Path(os.path.join(root, f)) - for root, _, files in os.walk(in_dir) - for f in files if os.path.splitext(f)[1] == ".py" - ) - - for fpath in pyfile_gen: - with open(fpath, 'r') as f: - src = f.read() - - # Parse the code and insert method call fixes. - tree = cst.parse_module(src) - updated = tree.visit(transformer) - - # Create the path and directory structure for the new file. - updated_path = out_dir.joinpath(fpath.relative_to(in_dir)) - updated_path.parent.mkdir(parents=True, exist_ok=True) - - # Generate the updated source file at the corresponding path. - with open(updated_path, 'w') as f: - f.write(updated.code) - - -if __name__ == '__main__': - parser = argparse.ArgumentParser( - description="""Fix up source that uses the pubsub client library. - -The existing sources are NOT overwritten but are copied to output_dir with changes made. - -Note: This tool operates at a best-effort level at converting positional - parameters in client method calls to keyword based parameters. - Cases where it WILL FAIL include - A) * or ** expansion in a method call. - B) Calls via function or method alias (includes free function calls) - C) Indirect or dispatched calls (e.g. the method is looked up dynamically) - - These all constitute false negatives. The tool will also detect false - positives when an API method shares a name with another method. -""") - parser.add_argument( - '-d', - '--input-directory', - required=True, - dest='input_dir', - help='the input directory to walk for python files to fix up', - ) - parser.add_argument( - '-o', - '--output-directory', - required=True, - dest='output_dir', - help='the directory to output files fixed via un-flattening', - ) - args = parser.parse_args() - input_dir = pathlib.Path(args.input_dir) - output_dir = pathlib.Path(args.output_dir) - if not input_dir.is_dir(): - print( - f"input directory '{input_dir}' does not exist or is not a directory", - file=sys.stderr, - ) - sys.exit(-1) - - if not output_dir.is_dir(): - print( - f"output directory '{output_dir}' does not exist or is not a directory", - file=sys.stderr, - ) - sys.exit(-1) - - if os.listdir(output_dir): - print( - f"output directory '{output_dir}' is not empty", - file=sys.stderr, - ) - sys.exit(-1) - - fix_files(input_dir, output_dir) diff --git a/owl-bot-staging/v1/setup.py b/owl-bot-staging/v1/setup.py deleted file mode 100644 index d4a8adac3..000000000 --- a/owl-bot-staging/v1/setup.py +++ /dev/null @@ -1,94 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import io -import os -import re - -import setuptools # type: ignore - -package_root = os.path.abspath(os.path.dirname(__file__)) - -name = 'google-cloud-pubsub' - - -description = "Google Cloud Pubsub API client library" - -version = None - -with open(os.path.join(package_root, 'google/pubsub/gapic_version.py')) as fp: - version_candidates = re.findall(r"(?<=\")\d+.\d+.\d+(?=\")", fp.read()) - assert (len(version_candidates) == 1) - version = version_candidates[0] - -if version[0] == "0": - release_status = "Development Status :: 4 - Beta" -else: - release_status = "Development Status :: 5 - Production/Stable" - -dependencies = [ - "google-api-core[grpc] >= 1.34.1, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*", - # Exclude incompatible versions of `google-auth` - # See https://github.com/googleapis/google-cloud-python/issues/12364 - "google-auth >= 2.14.1, <3.0.0dev,!=2.24.0,!=2.25.0", - "proto-plus >= 1.22.3, <2.0.0dev", - "protobuf>=3.20.2,<6.0.0dev,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", - "grpc-google-iam-v1 >= 0.12.4, <1.0.0dev", -] -url = "https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-pubsub" - -package_root = os.path.abspath(os.path.dirname(__file__)) - -readme_filename = os.path.join(package_root, "README.rst") -with io.open(readme_filename, encoding="utf-8") as readme_file: - readme = readme_file.read() - -packages = [ - package - for package in setuptools.find_namespace_packages() - if package.startswith("google") -] - -setuptools.setup( - name=name, - version=version, - description=description, - long_description=readme, - author="Google LLC", - author_email="googleapis-packages@google.com", - license="Apache 2.0", - url=url, - classifiers=[ - release_status, - "Intended Audience :: Developers", - "License :: OSI Approved :: Apache Software License", - "Programming Language :: Python", - "Programming Language :: Python :: 3", - "Programming Language :: Python :: 3.7", - "Programming Language :: Python :: 3.8", - "Programming Language :: Python :: 3.9", - "Programming Language :: Python :: 3.10", - "Programming Language :: Python :: 3.11", - "Programming Language :: Python :: 3.12", - "Operating System :: OS Independent", - "Topic :: Internet", - ], - platforms="Posix; MacOS X; Windows", - packages=packages, - python_requires=">=3.7", - install_requires=dependencies, - include_package_data=True, - zip_safe=False, -) diff --git a/owl-bot-staging/v1/testing/constraints-3.10.txt b/owl-bot-staging/v1/testing/constraints-3.10.txt deleted file mode 100644 index ad3f0fa58..000000000 --- a/owl-bot-staging/v1/testing/constraints-3.10.txt +++ /dev/null @@ -1,7 +0,0 @@ -# -*- coding: utf-8 -*- -# This constraints file is required for unit tests. -# List all library dependencies and extras in this file. -google-api-core -proto-plus -protobuf -grpc-google-iam-v1 diff --git a/owl-bot-staging/v1/testing/constraints-3.11.txt b/owl-bot-staging/v1/testing/constraints-3.11.txt deleted file mode 100644 index ad3f0fa58..000000000 --- a/owl-bot-staging/v1/testing/constraints-3.11.txt +++ /dev/null @@ -1,7 +0,0 @@ -# -*- coding: utf-8 -*- -# This constraints file is required for unit tests. -# List all library dependencies and extras in this file. -google-api-core -proto-plus -protobuf -grpc-google-iam-v1 diff --git a/owl-bot-staging/v1/testing/constraints-3.12.txt b/owl-bot-staging/v1/testing/constraints-3.12.txt deleted file mode 100644 index ad3f0fa58..000000000 --- a/owl-bot-staging/v1/testing/constraints-3.12.txt +++ /dev/null @@ -1,7 +0,0 @@ -# -*- coding: utf-8 -*- -# This constraints file is required for unit tests. -# List all library dependencies and extras in this file. -google-api-core -proto-plus -protobuf -grpc-google-iam-v1 diff --git a/owl-bot-staging/v1/testing/constraints-3.7.txt b/owl-bot-staging/v1/testing/constraints-3.7.txt deleted file mode 100644 index a81fb6bcd..000000000 --- a/owl-bot-staging/v1/testing/constraints-3.7.txt +++ /dev/null @@ -1,11 +0,0 @@ -# This constraints file is used to check that lower bounds -# are correct in setup.py -# List all library dependencies and extras in this file. -# Pin the version to the lower bound. -# e.g., if setup.py has "google-cloud-foo >= 1.14.0, < 2.0.0dev", -# Then this file should have google-cloud-foo==1.14.0 -google-api-core==1.34.1 -google-auth==2.14.1 -proto-plus==1.22.3 -protobuf==3.20.2 -grpc-google-iam-v1==0.12.4 diff --git a/owl-bot-staging/v1/testing/constraints-3.8.txt b/owl-bot-staging/v1/testing/constraints-3.8.txt deleted file mode 100644 index ad3f0fa58..000000000 --- a/owl-bot-staging/v1/testing/constraints-3.8.txt +++ /dev/null @@ -1,7 +0,0 @@ -# -*- coding: utf-8 -*- -# This constraints file is required for unit tests. -# List all library dependencies and extras in this file. -google-api-core -proto-plus -protobuf -grpc-google-iam-v1 diff --git a/owl-bot-staging/v1/testing/constraints-3.9.txt b/owl-bot-staging/v1/testing/constraints-3.9.txt deleted file mode 100644 index ad3f0fa58..000000000 --- a/owl-bot-staging/v1/testing/constraints-3.9.txt +++ /dev/null @@ -1,7 +0,0 @@ -# -*- coding: utf-8 -*- -# This constraints file is required for unit tests. -# List all library dependencies and extras in this file. -google-api-core -proto-plus -protobuf -grpc-google-iam-v1 diff --git a/owl-bot-staging/v1/tests/__init__.py b/owl-bot-staging/v1/tests/__init__.py deleted file mode 100644 index 7b3de3117..000000000 --- a/owl-bot-staging/v1/tests/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# diff --git a/owl-bot-staging/v1/tests/unit/__init__.py b/owl-bot-staging/v1/tests/unit/__init__.py deleted file mode 100644 index 7b3de3117..000000000 --- a/owl-bot-staging/v1/tests/unit/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# diff --git a/owl-bot-staging/v1/tests/unit/gapic/__init__.py b/owl-bot-staging/v1/tests/unit/gapic/__init__.py deleted file mode 100644 index 7b3de3117..000000000 --- a/owl-bot-staging/v1/tests/unit/gapic/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# diff --git a/owl-bot-staging/v1/tests/unit/gapic/pubsub_v1/__init__.py b/owl-bot-staging/v1/tests/unit/gapic/pubsub_v1/__init__.py deleted file mode 100644 index 7b3de3117..000000000 --- a/owl-bot-staging/v1/tests/unit/gapic/pubsub_v1/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# diff --git a/owl-bot-staging/v1/tests/unit/gapic/pubsub_v1/test_publisher.py b/owl-bot-staging/v1/tests/unit/gapic/pubsub_v1/test_publisher.py deleted file mode 100644 index f6b425ca6..000000000 --- a/owl-bot-staging/v1/tests/unit/gapic/pubsub_v1/test_publisher.py +++ /dev/null @@ -1,8402 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import os -# try/except added for compatibility with python < 3.8 -try: - from unittest import mock - from unittest.mock import AsyncMock # pragma: NO COVER -except ImportError: # pragma: NO COVER - import mock - -import grpc -from grpc.experimental import aio -from collections.abc import Iterable -from google.protobuf import json_format -import json -import math -import pytest -from google.api_core import api_core_version -from proto.marshal.rules.dates import DurationRule, TimestampRule -from proto.marshal.rules import wrappers -from requests import Response -from requests import Request, PreparedRequest -from requests.sessions import Session -from google.protobuf import json_format - -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.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.oauth2 import service_account -from google.protobuf import duration_pb2 # type: ignore -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from google.pubsub_v1.services.publisher import PublisherAsyncClient -from google.pubsub_v1.services.publisher import PublisherClient -from google.pubsub_v1.services.publisher import pagers -from google.pubsub_v1.services.publisher import transports -from google.pubsub_v1.types import pubsub -from google.pubsub_v1.types import schema -import google.auth - - -def client_cert_source_callback(): - return b"cert bytes", b"key bytes" - -# If default endpoint is localhost, then default mtls endpoint will be the same. -# This method modifies the default endpoint so the client can produce a different -# mtls endpoint for endpoint testing purposes. -def modify_default_endpoint(client): - return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT - -# If default endpoint template is localhost, then default mtls endpoint will be the same. -# This method modifies the default endpoint template so the client can produce a different -# mtls endpoint for endpoint testing purposes. -def modify_default_endpoint_template(client): - return "test.{UNIVERSE_DOMAIN}" if ("localhost" in client._DEFAULT_ENDPOINT_TEMPLATE) else client._DEFAULT_ENDPOINT_TEMPLATE - - -def test__get_default_mtls_endpoint(): - api_endpoint = "example.googleapis.com" - api_mtls_endpoint = "example.mtls.googleapis.com" - sandbox_endpoint = "example.sandbox.googleapis.com" - sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" - non_googleapi = "api.example.com" - - assert PublisherClient._get_default_mtls_endpoint(None) is None - assert PublisherClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert PublisherClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert PublisherClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert PublisherClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert PublisherClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - -def test__read_environment_variables(): - assert PublisherClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - assert PublisherClient._read_environment_variables() == (True, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - assert PublisherClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError) as excinfo: - PublisherClient._read_environment_variables() - assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - assert PublisherClient._read_environment_variables() == (False, "never", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - assert PublisherClient._read_environment_variables() == (False, "always", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): - assert PublisherClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError) as excinfo: - PublisherClient._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 PublisherClient._read_environment_variables() == (False, "auto", "foo.com") - -def test__get_client_cert_source(): - mock_provided_cert_source = mock.Mock() - mock_default_cert_source = mock.Mock() - - assert PublisherClient._get_client_cert_source(None, False) is None - assert PublisherClient._get_client_cert_source(mock_provided_cert_source, False) is None - assert PublisherClient._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 PublisherClient._get_client_cert_source(None, True) is mock_default_cert_source - assert PublisherClient._get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source - -@mock.patch.object(PublisherClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(PublisherClient)) -@mock.patch.object(PublisherAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(PublisherAsyncClient)) -def test__get_api_endpoint(): - api_override = "foo.com" - mock_client_cert_source = mock.Mock() - default_universe = PublisherClient._DEFAULT_UNIVERSE - default_endpoint = PublisherClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) - mock_universe = "bar.com" - mock_endpoint = PublisherClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) - - assert PublisherClient._get_api_endpoint(api_override, mock_client_cert_source, default_universe, "always") == api_override - assert PublisherClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "auto") == PublisherClient.DEFAULT_MTLS_ENDPOINT - assert PublisherClient._get_api_endpoint(None, None, default_universe, "auto") == default_endpoint - assert PublisherClient._get_api_endpoint(None, None, default_universe, "always") == PublisherClient.DEFAULT_MTLS_ENDPOINT - assert PublisherClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "always") == PublisherClient.DEFAULT_MTLS_ENDPOINT - assert PublisherClient._get_api_endpoint(None, None, mock_universe, "never") == mock_endpoint - assert PublisherClient._get_api_endpoint(None, None, default_universe, "never") == default_endpoint - - with pytest.raises(MutualTLSChannelError) as excinfo: - PublisherClient._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 PublisherClient._get_universe_domain(client_universe_domain, universe_domain_env) == client_universe_domain - assert PublisherClient._get_universe_domain(None, universe_domain_env) == universe_domain_env - assert PublisherClient._get_universe_domain(None, None) == PublisherClient._DEFAULT_UNIVERSE - - with pytest.raises(ValueError) as excinfo: - PublisherClient._get_universe_domain("", None) - assert str(excinfo.value) == "Universe Domain cannot be an empty string." - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (PublisherClient, transports.PublisherGrpcTransport, "grpc"), - (PublisherClient, transports.PublisherRestTransport, "rest"), -]) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials() - ) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - transport=transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [int(part) for part in google.auth.__version__.split(".")[0:2]] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class( - transport=transport_class(credentials=credentials) - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert str(excinfo.value) == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.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 >= 15): - client = client_class(client_options={"universe_domain": "bar.com"}, transport=transport_class(credentials=ga_credentials.AnonymousCredentials(),)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert str(excinfo.value) == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - -@pytest.mark.parametrize("client_class,transport_name", [ - (PublisherClient, "grpc"), - (PublisherAsyncClient, "grpc_asyncio"), - (PublisherClient, "rest"), -]) -def test_publisher_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 == ( - 'pubsub.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://pubsub.googleapis.com' - ) - - -@pytest.mark.parametrize("transport_class,transport_name", [ - (transports.PublisherGrpcTransport, "grpc"), - (transports.PublisherGrpcAsyncIOTransport, "grpc_asyncio"), - (transports.PublisherRestTransport, "rest"), -]) -def test_publisher_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", [ - (PublisherClient, "grpc"), - (PublisherAsyncClient, "grpc_asyncio"), - (PublisherClient, "rest"), -]) -def test_publisher_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 == ( - 'pubsub.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://pubsub.googleapis.com' - ) - - -def test_publisher_client_get_transport_class(): - transport = PublisherClient.get_transport_class() - available_transports = [ - transports.PublisherGrpcTransport, - transports.PublisherRestTransport, - ] - assert transport in available_transports - - transport = PublisherClient.get_transport_class("grpc") - assert transport == transports.PublisherGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (PublisherClient, transports.PublisherGrpcTransport, "grpc"), - (PublisherAsyncClient, transports.PublisherGrpcAsyncIOTransport, "grpc_asyncio"), - (PublisherClient, transports.PublisherRestTransport, "rest"), -]) -@mock.patch.object(PublisherClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(PublisherClient)) -@mock.patch.object(PublisherAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(PublisherAsyncClient)) -def test_publisher_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(PublisherClient, '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(PublisherClient, 'get_transport_class') as gtc: - client = client_class(transport=transport_name) - gtc.assert_called() - - # Check the case api_endpoint is provided. - options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name, client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_MTLS_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has - # unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError) as excinfo: - client = client_class(transport=transport_name) - assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" - - # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError) as excinfo: - client = client_class(transport=transport_name) - assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - - # Check the case quota_project_id is provided - options = client_options.ClientOptions(quota_project_id="octopus") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id="octopus", - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - # Check the case api_endpoint is provided - options = client_options.ClientOptions(api_audience="https://language.googleapis.com") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience="https://language.googleapis.com" - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ - (PublisherClient, transports.PublisherGrpcTransport, "grpc", "true"), - (PublisherAsyncClient, transports.PublisherGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (PublisherClient, transports.PublisherGrpcTransport, "grpc", "false"), - (PublisherAsyncClient, transports.PublisherGrpcAsyncIOTransport, "grpc_asyncio", "false"), - (PublisherClient, transports.PublisherRestTransport, "rest", "true"), - (PublisherClient, transports.PublisherRestTransport, "rest", "false"), -]) -@mock.patch.object(PublisherClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(PublisherClient)) -@mock.patch.object(PublisherAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(PublisherAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_publisher_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", [ - PublisherClient, PublisherAsyncClient -]) -@mock.patch.object(PublisherClient, "DEFAULT_ENDPOINT", modify_default_endpoint(PublisherClient)) -@mock.patch.object(PublisherAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(PublisherAsyncClient)) -def test_publisher_client_get_mtls_endpoint_and_cert_source(client_class): - mock_client_cert_source = mock.Mock() - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source == mock_client_cert_source - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - mock_client_cert_source = mock.Mock() - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source == mock_client_cert_source - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has - # unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError) as excinfo: - client_class.get_mtls_endpoint_and_cert_source() - - assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" - - # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError) as excinfo: - client_class.get_mtls_endpoint_and_cert_source() - - assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - -@pytest.mark.parametrize("client_class", [ - PublisherClient, PublisherAsyncClient -]) -@mock.patch.object(PublisherClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(PublisherClient)) -@mock.patch.object(PublisherAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(PublisherAsyncClient)) -def test_publisher_client_client_api_endpoint(client_class): - mock_client_cert_source = client_cert_source_callback - api_override = "foo.com" - default_universe = PublisherClient._DEFAULT_UNIVERSE - default_endpoint = PublisherClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) - mock_universe = "bar.com" - mock_endpoint = PublisherClient._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", [ - (PublisherClient, transports.PublisherGrpcTransport, "grpc"), - (PublisherAsyncClient, transports.PublisherGrpcAsyncIOTransport, "grpc_asyncio"), - (PublisherClient, transports.PublisherRestTransport, "rest"), -]) -def test_publisher_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", [ - (PublisherClient, transports.PublisherGrpcTransport, "grpc", grpc_helpers), - (PublisherAsyncClient, transports.PublisherGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), - (PublisherClient, transports.PublisherRestTransport, "rest", None), -]) -def test_publisher_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_publisher_client_client_options_from_dict(): - with mock.patch('google.pubsub_v1.services.publisher.transports.PublisherGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = PublisherClient( - 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", [ - (PublisherClient, transports.PublisherGrpcTransport, "grpc", grpc_helpers), - (PublisherAsyncClient, transports.PublisherGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_publisher_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( - "pubsub.googleapis.com:443", - credentials=file_creds, - credentials_file=None, - quota_project_id=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/pubsub', -), - scopes=None, - default_host="pubsub.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("request_type", [ - pubsub.Topic, - dict, -]) -def test_create_topic(request_type, transport: str = 'grpc'): - client = PublisherClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_topic), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = pubsub.Topic( - name='name_value', - kms_key_name='kms_key_name_value', - satisfies_pzs=True, - state=pubsub.Topic.State.ACTIVE, - ) - response = client.create_topic(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = pubsub.Topic() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pubsub.Topic) - assert response.name == 'name_value' - assert response.kms_key_name == 'kms_key_name_value' - assert response.satisfies_pzs is True - assert response.state == pubsub.Topic.State.ACTIVE - - -def test_create_topic_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = PublisherClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_topic), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.create_topic() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == pubsub.Topic() - - -def test_create_topic_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 = PublisherClient( - 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 = pubsub.Topic( - name='name_value', - kms_key_name='kms_key_name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_topic), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.create_topic(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == pubsub.Topic( - name='name_value', - kms_key_name='kms_key_name_value', - ) - -def test_create_topic_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = PublisherClient( - 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_topic in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_topic] = mock_rpc - request = {} - client.create_topic(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.create_topic(request) - - # Establish that a new wrapper 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_topic_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = PublisherAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_topic), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(pubsub.Topic( - name='name_value', - kms_key_name='kms_key_name_value', - satisfies_pzs=True, - state=pubsub.Topic.State.ACTIVE, - )) - response = await client.create_topic() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == pubsub.Topic() - -@pytest.mark.asyncio -async def test_create_topic_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 = PublisherAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - 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_topic 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_topic] = mock_rpc - - request = {} - await client.create_topic(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.create_topic(request) - - # Establish that a new wrapper 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_topic_async(transport: str = 'grpc_asyncio', request_type=pubsub.Topic): - client = PublisherAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_topic), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(pubsub.Topic( - name='name_value', - kms_key_name='kms_key_name_value', - satisfies_pzs=True, - state=pubsub.Topic.State.ACTIVE, - )) - response = await client.create_topic(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = pubsub.Topic() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pubsub.Topic) - assert response.name == 'name_value' - assert response.kms_key_name == 'kms_key_name_value' - assert response.satisfies_pzs is True - assert response.state == pubsub.Topic.State.ACTIVE - - -@pytest.mark.asyncio -async def test_create_topic_async_from_dict(): - await test_create_topic_async(request_type=dict) - - -def test_create_topic_field_headers(): - client = PublisherClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = pubsub.Topic() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_topic), - '__call__') as call: - call.return_value = pubsub.Topic() - client.create_topic(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_create_topic_field_headers_async(): - client = PublisherAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = pubsub.Topic() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_topic), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(pubsub.Topic()) - await client.create_topic(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name_value', - ) in kw['metadata'] - - -def test_create_topic_flattened(): - client = PublisherClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_topic), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = pubsub.Topic() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.create_topic( - name='name_value', - ) - - # 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_create_topic_flattened_error(): - client = PublisherClient( - credentials=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_topic( - pubsub.Topic(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_create_topic_flattened_async(): - client = PublisherAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_topic), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = pubsub.Topic() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(pubsub.Topic()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.create_topic( - name='name_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_create_topic_flattened_error_async(): - client = PublisherAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.create_topic( - pubsub.Topic(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - pubsub.UpdateTopicRequest, - dict, -]) -def test_update_topic(request_type, transport: str = 'grpc'): - client = PublisherClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_topic), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = pubsub.Topic( - name='name_value', - kms_key_name='kms_key_name_value', - satisfies_pzs=True, - state=pubsub.Topic.State.ACTIVE, - ) - response = client.update_topic(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = pubsub.UpdateTopicRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pubsub.Topic) - assert response.name == 'name_value' - assert response.kms_key_name == 'kms_key_name_value' - assert response.satisfies_pzs is True - assert response.state == pubsub.Topic.State.ACTIVE - - -def test_update_topic_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = PublisherClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_topic), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.update_topic() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == pubsub.UpdateTopicRequest() - - -def test_update_topic_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 = PublisherClient( - 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 = pubsub.UpdateTopicRequest( - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_topic), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.update_topic(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == pubsub.UpdateTopicRequest( - ) - -def test_update_topic_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = PublisherClient( - 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_topic in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_topic] = mock_rpc - request = {} - client.update_topic(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.update_topic(request) - - # Establish that a new wrapper 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_topic_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = PublisherAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_topic), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(pubsub.Topic( - name='name_value', - kms_key_name='kms_key_name_value', - satisfies_pzs=True, - state=pubsub.Topic.State.ACTIVE, - )) - response = await client.update_topic() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == pubsub.UpdateTopicRequest() - -@pytest.mark.asyncio -async def test_update_topic_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 = PublisherAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - 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_topic 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_topic] = mock_rpc - - request = {} - await client.update_topic(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.update_topic(request) - - # Establish that a new wrapper 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_topic_async(transport: str = 'grpc_asyncio', request_type=pubsub.UpdateTopicRequest): - client = PublisherAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_topic), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(pubsub.Topic( - name='name_value', - kms_key_name='kms_key_name_value', - satisfies_pzs=True, - state=pubsub.Topic.State.ACTIVE, - )) - response = await client.update_topic(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = pubsub.UpdateTopicRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pubsub.Topic) - assert response.name == 'name_value' - assert response.kms_key_name == 'kms_key_name_value' - assert response.satisfies_pzs is True - assert response.state == pubsub.Topic.State.ACTIVE - - -@pytest.mark.asyncio -async def test_update_topic_async_from_dict(): - await test_update_topic_async(request_type=dict) - - -def test_update_topic_field_headers(): - client = PublisherClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = pubsub.UpdateTopicRequest() - - request.topic.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_topic), - '__call__') as call: - call.return_value = pubsub.Topic() - client.update_topic(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'topic.name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_topic_field_headers_async(): - client = PublisherAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = pubsub.UpdateTopicRequest() - - request.topic.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_topic), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(pubsub.Topic()) - await client.update_topic(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'topic.name=name_value', - ) in kw['metadata'] - - -def test_update_topic_flattened(): - client = PublisherClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_topic), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = pubsub.Topic() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.update_topic( - topic=pubsub.Topic(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].topic - mock_val = pubsub.Topic(name='name_value') - assert arg == mock_val - arg = args[0].update_mask - mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) - assert arg == mock_val - - -def test_update_topic_flattened_error(): - client = PublisherClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.update_topic( - pubsub.UpdateTopicRequest(), - topic=pubsub.Topic(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - -@pytest.mark.asyncio -async def test_update_topic_flattened_async(): - client = PublisherAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_topic), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = pubsub.Topic() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(pubsub.Topic()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.update_topic( - topic=pubsub.Topic(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].topic - mock_val = pubsub.Topic(name='name_value') - assert arg == mock_val - arg = args[0].update_mask - mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) - assert arg == mock_val - -@pytest.mark.asyncio -async def test_update_topic_flattened_error_async(): - client = PublisherAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.update_topic( - pubsub.UpdateTopicRequest(), - topic=pubsub.Topic(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -@pytest.mark.parametrize("request_type", [ - pubsub.PublishRequest, - dict, -]) -def test_publish(request_type, transport: str = 'grpc'): - client = PublisherClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.publish), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = pubsub.PublishResponse( - message_ids=['message_ids_value'], - ) - response = client.publish(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = pubsub.PublishRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pubsub.PublishResponse) - assert response.message_ids == ['message_ids_value'] - - -def test_publish_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = PublisherClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.publish), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.publish() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == pubsub.PublishRequest() - - -def test_publish_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 = PublisherClient( - 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 = pubsub.PublishRequest( - topic='topic_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.publish), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.publish(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == pubsub.PublishRequest( - topic='topic_value', - ) - -def test_publish_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = PublisherClient( - 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.publish in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.publish] = mock_rpc - request = {} - client.publish(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.publish(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_publish_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = PublisherAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.publish), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(pubsub.PublishResponse( - message_ids=['message_ids_value'], - )) - response = await client.publish() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == pubsub.PublishRequest() - -@pytest.mark.asyncio -async def test_publish_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 = PublisherAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - 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.publish 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.publish] = mock_rpc - - request = {} - await client.publish(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.publish(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_publish_async(transport: str = 'grpc_asyncio', request_type=pubsub.PublishRequest): - client = PublisherAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.publish), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(pubsub.PublishResponse( - message_ids=['message_ids_value'], - )) - response = await client.publish(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = pubsub.PublishRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pubsub.PublishResponse) - assert response.message_ids == ['message_ids_value'] - - -@pytest.mark.asyncio -async def test_publish_async_from_dict(): - await test_publish_async(request_type=dict) - - -def test_publish_field_headers(): - client = PublisherClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = pubsub.PublishRequest() - - request.topic = 'topic_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.publish), - '__call__') as call: - call.return_value = pubsub.PublishResponse() - client.publish(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'topic=topic_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_publish_field_headers_async(): - client = PublisherAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = pubsub.PublishRequest() - - request.topic = 'topic_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.publish), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(pubsub.PublishResponse()) - await client.publish(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'topic=topic_value', - ) in kw['metadata'] - - -def test_publish_flattened(): - client = PublisherClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.publish), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = pubsub.PublishResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.publish( - topic='topic_value', - messages=[pubsub.PubsubMessage(data=b'data_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].topic - mock_val = 'topic_value' - assert arg == mock_val - arg = args[0].messages - mock_val = [pubsub.PubsubMessage(data=b'data_blob')] - assert arg == mock_val - - -def test_publish_flattened_error(): - client = PublisherClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.publish( - pubsub.PublishRequest(), - topic='topic_value', - messages=[pubsub.PubsubMessage(data=b'data_blob')], - ) - -@pytest.mark.asyncio -async def test_publish_flattened_async(): - client = PublisherAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.publish), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = pubsub.PublishResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(pubsub.PublishResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.publish( - topic='topic_value', - messages=[pubsub.PubsubMessage(data=b'data_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].topic - mock_val = 'topic_value' - assert arg == mock_val - arg = args[0].messages - mock_val = [pubsub.PubsubMessage(data=b'data_blob')] - assert arg == mock_val - -@pytest.mark.asyncio -async def test_publish_flattened_error_async(): - client = PublisherAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.publish( - pubsub.PublishRequest(), - topic='topic_value', - messages=[pubsub.PubsubMessage(data=b'data_blob')], - ) - - -@pytest.mark.parametrize("request_type", [ - pubsub.GetTopicRequest, - dict, -]) -def test_get_topic(request_type, transport: str = 'grpc'): - client = PublisherClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_topic), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = pubsub.Topic( - name='name_value', - kms_key_name='kms_key_name_value', - satisfies_pzs=True, - state=pubsub.Topic.State.ACTIVE, - ) - response = client.get_topic(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = pubsub.GetTopicRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pubsub.Topic) - assert response.name == 'name_value' - assert response.kms_key_name == 'kms_key_name_value' - assert response.satisfies_pzs is True - assert response.state == pubsub.Topic.State.ACTIVE - - -def test_get_topic_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = PublisherClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_topic), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.get_topic() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == pubsub.GetTopicRequest() - - -def test_get_topic_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 = PublisherClient( - 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 = pubsub.GetTopicRequest( - topic='topic_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_topic), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.get_topic(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == pubsub.GetTopicRequest( - topic='topic_value', - ) - -def test_get_topic_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = PublisherClient( - 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_topic in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_topic] = mock_rpc - request = {} - client.get_topic(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_topic(request) - - # Establish that a new wrapper 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_topic_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = PublisherAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_topic), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(pubsub.Topic( - name='name_value', - kms_key_name='kms_key_name_value', - satisfies_pzs=True, - state=pubsub.Topic.State.ACTIVE, - )) - response = await client.get_topic() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == pubsub.GetTopicRequest() - -@pytest.mark.asyncio -async def test_get_topic_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 = PublisherAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - 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_topic 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_topic] = mock_rpc - - request = {} - await client.get_topic(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.get_topic(request) - - # Establish that a new wrapper 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_topic_async(transport: str = 'grpc_asyncio', request_type=pubsub.GetTopicRequest): - client = PublisherAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_topic), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(pubsub.Topic( - name='name_value', - kms_key_name='kms_key_name_value', - satisfies_pzs=True, - state=pubsub.Topic.State.ACTIVE, - )) - response = await client.get_topic(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = pubsub.GetTopicRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pubsub.Topic) - assert response.name == 'name_value' - assert response.kms_key_name == 'kms_key_name_value' - assert response.satisfies_pzs is True - assert response.state == pubsub.Topic.State.ACTIVE - - -@pytest.mark.asyncio -async def test_get_topic_async_from_dict(): - await test_get_topic_async(request_type=dict) - - -def test_get_topic_field_headers(): - client = PublisherClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = pubsub.GetTopicRequest() - - request.topic = 'topic_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_topic), - '__call__') as call: - call.return_value = pubsub.Topic() - client.get_topic(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'topic=topic_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_get_topic_field_headers_async(): - client = PublisherAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = pubsub.GetTopicRequest() - - request.topic = 'topic_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_topic), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(pubsub.Topic()) - await client.get_topic(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'topic=topic_value', - ) in kw['metadata'] - - -def test_get_topic_flattened(): - client = PublisherClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_topic), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = pubsub.Topic() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_topic( - topic='topic_value', - ) - - # 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].topic - mock_val = 'topic_value' - assert arg == mock_val - - -def test_get_topic_flattened_error(): - client = PublisherClient( - credentials=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_topic( - pubsub.GetTopicRequest(), - topic='topic_value', - ) - -@pytest.mark.asyncio -async def test_get_topic_flattened_async(): - client = PublisherAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_topic), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = pubsub.Topic() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(pubsub.Topic()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_topic( - topic='topic_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].topic - mock_val = 'topic_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_get_topic_flattened_error_async(): - client = PublisherAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.get_topic( - pubsub.GetTopicRequest(), - topic='topic_value', - ) - - -@pytest.mark.parametrize("request_type", [ - pubsub.ListTopicsRequest, - dict, -]) -def test_list_topics(request_type, transport: str = 'grpc'): - client = PublisherClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_topics), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = pubsub.ListTopicsResponse( - next_page_token='next_page_token_value', - ) - response = client.list_topics(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = pubsub.ListTopicsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListTopicsPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_topics_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = PublisherClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_topics), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.list_topics() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == pubsub.ListTopicsRequest() - - -def test_list_topics_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 = PublisherClient( - 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 = pubsub.ListTopicsRequest( - project='project_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_topics), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.list_topics(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == pubsub.ListTopicsRequest( - project='project_value', - page_token='page_token_value', - ) - -def test_list_topics_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = PublisherClient( - 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_topics in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_topics] = mock_rpc - request = {} - client.list_topics(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_topics(request) - - # Establish that a new wrapper 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_topics_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = PublisherAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_topics), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(pubsub.ListTopicsResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_topics() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == pubsub.ListTopicsRequest() - -@pytest.mark.asyncio -async def test_list_topics_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 = PublisherAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - 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_topics 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_topics] = mock_rpc - - request = {} - await client.list_topics(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.list_topics(request) - - # Establish that a new wrapper 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_topics_async(transport: str = 'grpc_asyncio', request_type=pubsub.ListTopicsRequest): - client = PublisherAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_topics), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(pubsub.ListTopicsResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_topics(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = pubsub.ListTopicsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListTopicsAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_topics_async_from_dict(): - await test_list_topics_async(request_type=dict) - - -def test_list_topics_field_headers(): - client = PublisherClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = pubsub.ListTopicsRequest() - - request.project = 'project_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_topics), - '__call__') as call: - call.return_value = pubsub.ListTopicsResponse() - client.list_topics(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'project=project_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_list_topics_field_headers_async(): - client = PublisherAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = pubsub.ListTopicsRequest() - - request.project = 'project_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_topics), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(pubsub.ListTopicsResponse()) - await client.list_topics(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'project=project_value', - ) in kw['metadata'] - - -def test_list_topics_flattened(): - client = PublisherClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_topics), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = pubsub.ListTopicsResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_topics( - project='project_value', - ) - - # 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].project - mock_val = 'project_value' - assert arg == mock_val - - -def test_list_topics_flattened_error(): - client = PublisherClient( - credentials=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_topics( - pubsub.ListTopicsRequest(), - project='project_value', - ) - -@pytest.mark.asyncio -async def test_list_topics_flattened_async(): - client = PublisherAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_topics), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = pubsub.ListTopicsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(pubsub.ListTopicsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_topics( - project='project_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].project - mock_val = 'project_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_list_topics_flattened_error_async(): - client = PublisherAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.list_topics( - pubsub.ListTopicsRequest(), - project='project_value', - ) - - -def test_list_topics_pager(transport_name: str = "grpc"): - client = PublisherClient( - 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_topics), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - pubsub.ListTopicsResponse( - topics=[ - pubsub.Topic(), - pubsub.Topic(), - pubsub.Topic(), - ], - next_page_token='abc', - ), - pubsub.ListTopicsResponse( - topics=[], - next_page_token='def', - ), - pubsub.ListTopicsResponse( - topics=[ - pubsub.Topic(), - ], - next_page_token='ghi', - ), - pubsub.ListTopicsResponse( - topics=[ - pubsub.Topic(), - pubsub.Topic(), - ], - ), - RuntimeError, - ) - - expected_metadata = () - retry = retries.Retry() - timeout = 5 - expected_metadata = tuple(expected_metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('project', ''), - )), - ) - pager = client.list_topics(request={}, retry=retry, timeout=timeout) - - assert pager._metadata == expected_metadata - assert pager._retry == retry - assert pager._timeout == timeout - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, pubsub.Topic) - for i in results) -def test_list_topics_pages(transport_name: str = "grpc"): - client = PublisherClient( - 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_topics), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - pubsub.ListTopicsResponse( - topics=[ - pubsub.Topic(), - pubsub.Topic(), - pubsub.Topic(), - ], - next_page_token='abc', - ), - pubsub.ListTopicsResponse( - topics=[], - next_page_token='def', - ), - pubsub.ListTopicsResponse( - topics=[ - pubsub.Topic(), - ], - next_page_token='ghi', - ), - pubsub.ListTopicsResponse( - topics=[ - pubsub.Topic(), - pubsub.Topic(), - ], - ), - RuntimeError, - ) - pages = list(client.list_topics(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_topics_async_pager(): - client = PublisherAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_topics), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - pubsub.ListTopicsResponse( - topics=[ - pubsub.Topic(), - pubsub.Topic(), - pubsub.Topic(), - ], - next_page_token='abc', - ), - pubsub.ListTopicsResponse( - topics=[], - next_page_token='def', - ), - pubsub.ListTopicsResponse( - topics=[ - pubsub.Topic(), - ], - next_page_token='ghi', - ), - pubsub.ListTopicsResponse( - topics=[ - pubsub.Topic(), - pubsub.Topic(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_topics(request={},) - assert async_pager.next_page_token == 'abc' - responses = [] - async for response in async_pager: # pragma: no branch - responses.append(response) - - assert len(responses) == 6 - assert all(isinstance(i, pubsub.Topic) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_topics_async_pages(): - client = PublisherAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_topics), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - pubsub.ListTopicsResponse( - topics=[ - pubsub.Topic(), - pubsub.Topic(), - pubsub.Topic(), - ], - next_page_token='abc', - ), - pubsub.ListTopicsResponse( - topics=[], - next_page_token='def', - ), - pubsub.ListTopicsResponse( - topics=[ - pubsub.Topic(), - ], - next_page_token='ghi', - ), - pubsub.ListTopicsResponse( - topics=[ - pubsub.Topic(), - pubsub.Topic(), - ], - ), - RuntimeError, - ) - pages = [] - # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` - # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 - async for page_ in ( # pragma: no branch - await client.list_topics(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", [ - pubsub.ListTopicSubscriptionsRequest, - dict, -]) -def test_list_topic_subscriptions(request_type, transport: str = 'grpc'): - client = PublisherClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_topic_subscriptions), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = pubsub.ListTopicSubscriptionsResponse( - subscriptions=['subscriptions_value'], - next_page_token='next_page_token_value', - ) - response = client.list_topic_subscriptions(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = pubsub.ListTopicSubscriptionsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListTopicSubscriptionsPager) - assert response.subscriptions == ['subscriptions_value'] - assert response.next_page_token == 'next_page_token_value' - - -def test_list_topic_subscriptions_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = PublisherClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_topic_subscriptions), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.list_topic_subscriptions() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == pubsub.ListTopicSubscriptionsRequest() - - -def test_list_topic_subscriptions_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 = PublisherClient( - 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 = pubsub.ListTopicSubscriptionsRequest( - topic='topic_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_topic_subscriptions), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.list_topic_subscriptions(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == pubsub.ListTopicSubscriptionsRequest( - topic='topic_value', - page_token='page_token_value', - ) - -def test_list_topic_subscriptions_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = PublisherClient( - 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_topic_subscriptions in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_topic_subscriptions] = mock_rpc - request = {} - client.list_topic_subscriptions(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_topic_subscriptions(request) - - # Establish that a new wrapper 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_topic_subscriptions_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = PublisherAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_topic_subscriptions), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(pubsub.ListTopicSubscriptionsResponse( - subscriptions=['subscriptions_value'], - next_page_token='next_page_token_value', - )) - response = await client.list_topic_subscriptions() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == pubsub.ListTopicSubscriptionsRequest() - -@pytest.mark.asyncio -async def test_list_topic_subscriptions_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 = PublisherAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - 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_topic_subscriptions 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_topic_subscriptions] = mock_rpc - - request = {} - await client.list_topic_subscriptions(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.list_topic_subscriptions(request) - - # Establish that a new wrapper 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_topic_subscriptions_async(transport: str = 'grpc_asyncio', request_type=pubsub.ListTopicSubscriptionsRequest): - client = PublisherAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_topic_subscriptions), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(pubsub.ListTopicSubscriptionsResponse( - subscriptions=['subscriptions_value'], - next_page_token='next_page_token_value', - )) - response = await client.list_topic_subscriptions(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = pubsub.ListTopicSubscriptionsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListTopicSubscriptionsAsyncPager) - assert response.subscriptions == ['subscriptions_value'] - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_topic_subscriptions_async_from_dict(): - await test_list_topic_subscriptions_async(request_type=dict) - - -def test_list_topic_subscriptions_field_headers(): - client = PublisherClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = pubsub.ListTopicSubscriptionsRequest() - - request.topic = 'topic_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_topic_subscriptions), - '__call__') as call: - call.return_value = pubsub.ListTopicSubscriptionsResponse() - client.list_topic_subscriptions(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'topic=topic_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_list_topic_subscriptions_field_headers_async(): - client = PublisherAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = pubsub.ListTopicSubscriptionsRequest() - - request.topic = 'topic_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_topic_subscriptions), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(pubsub.ListTopicSubscriptionsResponse()) - await client.list_topic_subscriptions(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'topic=topic_value', - ) in kw['metadata'] - - -def test_list_topic_subscriptions_flattened(): - client = PublisherClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_topic_subscriptions), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = pubsub.ListTopicSubscriptionsResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_topic_subscriptions( - topic='topic_value', - ) - - # 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].topic - mock_val = 'topic_value' - assert arg == mock_val - - -def test_list_topic_subscriptions_flattened_error(): - client = PublisherClient( - credentials=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_topic_subscriptions( - pubsub.ListTopicSubscriptionsRequest(), - topic='topic_value', - ) - -@pytest.mark.asyncio -async def test_list_topic_subscriptions_flattened_async(): - client = PublisherAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_topic_subscriptions), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = pubsub.ListTopicSubscriptionsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(pubsub.ListTopicSubscriptionsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_topic_subscriptions( - topic='topic_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].topic - mock_val = 'topic_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_list_topic_subscriptions_flattened_error_async(): - client = PublisherAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.list_topic_subscriptions( - pubsub.ListTopicSubscriptionsRequest(), - topic='topic_value', - ) - - -def test_list_topic_subscriptions_pager(transport_name: str = "grpc"): - client = PublisherClient( - 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_topic_subscriptions), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - pubsub.ListTopicSubscriptionsResponse( - subscriptions=[ - str(), - str(), - str(), - ], - next_page_token='abc', - ), - pubsub.ListTopicSubscriptionsResponse( - subscriptions=[], - next_page_token='def', - ), - pubsub.ListTopicSubscriptionsResponse( - subscriptions=[ - str(), - ], - next_page_token='ghi', - ), - pubsub.ListTopicSubscriptionsResponse( - subscriptions=[ - str(), - str(), - ], - ), - RuntimeError, - ) - - expected_metadata = () - retry = retries.Retry() - timeout = 5 - expected_metadata = tuple(expected_metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('topic', ''), - )), - ) - pager = client.list_topic_subscriptions(request={}, retry=retry, timeout=timeout) - - assert pager._metadata == expected_metadata - assert pager._retry == retry - assert pager._timeout == timeout - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, str) - for i in results) -def test_list_topic_subscriptions_pages(transport_name: str = "grpc"): - client = PublisherClient( - 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_topic_subscriptions), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - pubsub.ListTopicSubscriptionsResponse( - subscriptions=[ - str(), - str(), - str(), - ], - next_page_token='abc', - ), - pubsub.ListTopicSubscriptionsResponse( - subscriptions=[], - next_page_token='def', - ), - pubsub.ListTopicSubscriptionsResponse( - subscriptions=[ - str(), - ], - next_page_token='ghi', - ), - pubsub.ListTopicSubscriptionsResponse( - subscriptions=[ - str(), - str(), - ], - ), - RuntimeError, - ) - pages = list(client.list_topic_subscriptions(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_topic_subscriptions_async_pager(): - client = PublisherAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_topic_subscriptions), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - pubsub.ListTopicSubscriptionsResponse( - subscriptions=[ - str(), - str(), - str(), - ], - next_page_token='abc', - ), - pubsub.ListTopicSubscriptionsResponse( - subscriptions=[], - next_page_token='def', - ), - pubsub.ListTopicSubscriptionsResponse( - subscriptions=[ - str(), - ], - next_page_token='ghi', - ), - pubsub.ListTopicSubscriptionsResponse( - subscriptions=[ - str(), - str(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_topic_subscriptions(request={},) - assert async_pager.next_page_token == 'abc' - responses = [] - async for response in async_pager: # pragma: no branch - responses.append(response) - - assert len(responses) == 6 - assert all(isinstance(i, str) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_topic_subscriptions_async_pages(): - client = PublisherAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_topic_subscriptions), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - pubsub.ListTopicSubscriptionsResponse( - subscriptions=[ - str(), - str(), - str(), - ], - next_page_token='abc', - ), - pubsub.ListTopicSubscriptionsResponse( - subscriptions=[], - next_page_token='def', - ), - pubsub.ListTopicSubscriptionsResponse( - subscriptions=[ - str(), - ], - next_page_token='ghi', - ), - pubsub.ListTopicSubscriptionsResponse( - subscriptions=[ - str(), - str(), - ], - ), - RuntimeError, - ) - pages = [] - # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` - # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 - async for page_ in ( # pragma: no branch - await client.list_topic_subscriptions(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", [ - pubsub.ListTopicSnapshotsRequest, - dict, -]) -def test_list_topic_snapshots(request_type, transport: str = 'grpc'): - client = PublisherClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_topic_snapshots), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = pubsub.ListTopicSnapshotsResponse( - snapshots=['snapshots_value'], - next_page_token='next_page_token_value', - ) - response = client.list_topic_snapshots(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = pubsub.ListTopicSnapshotsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListTopicSnapshotsPager) - assert response.snapshots == ['snapshots_value'] - assert response.next_page_token == 'next_page_token_value' - - -def test_list_topic_snapshots_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = PublisherClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_topic_snapshots), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.list_topic_snapshots() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == pubsub.ListTopicSnapshotsRequest() - - -def test_list_topic_snapshots_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 = PublisherClient( - 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 = pubsub.ListTopicSnapshotsRequest( - topic='topic_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_topic_snapshots), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.list_topic_snapshots(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == pubsub.ListTopicSnapshotsRequest( - topic='topic_value', - page_token='page_token_value', - ) - -def test_list_topic_snapshots_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = PublisherClient( - 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_topic_snapshots in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_topic_snapshots] = mock_rpc - request = {} - client.list_topic_snapshots(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_topic_snapshots(request) - - # Establish that a new wrapper 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_topic_snapshots_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = PublisherAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_topic_snapshots), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(pubsub.ListTopicSnapshotsResponse( - snapshots=['snapshots_value'], - next_page_token='next_page_token_value', - )) - response = await client.list_topic_snapshots() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == pubsub.ListTopicSnapshotsRequest() - -@pytest.mark.asyncio -async def test_list_topic_snapshots_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 = PublisherAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - 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_topic_snapshots 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_topic_snapshots] = mock_rpc - - request = {} - await client.list_topic_snapshots(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.list_topic_snapshots(request) - - # Establish that a new wrapper 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_topic_snapshots_async(transport: str = 'grpc_asyncio', request_type=pubsub.ListTopicSnapshotsRequest): - client = PublisherAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_topic_snapshots), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(pubsub.ListTopicSnapshotsResponse( - snapshots=['snapshots_value'], - next_page_token='next_page_token_value', - )) - response = await client.list_topic_snapshots(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = pubsub.ListTopicSnapshotsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListTopicSnapshotsAsyncPager) - assert response.snapshots == ['snapshots_value'] - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_topic_snapshots_async_from_dict(): - await test_list_topic_snapshots_async(request_type=dict) - - -def test_list_topic_snapshots_field_headers(): - client = PublisherClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = pubsub.ListTopicSnapshotsRequest() - - request.topic = 'topic_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_topic_snapshots), - '__call__') as call: - call.return_value = pubsub.ListTopicSnapshotsResponse() - client.list_topic_snapshots(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'topic=topic_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_list_topic_snapshots_field_headers_async(): - client = PublisherAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = pubsub.ListTopicSnapshotsRequest() - - request.topic = 'topic_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_topic_snapshots), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(pubsub.ListTopicSnapshotsResponse()) - await client.list_topic_snapshots(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'topic=topic_value', - ) in kw['metadata'] - - -def test_list_topic_snapshots_flattened(): - client = PublisherClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_topic_snapshots), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = pubsub.ListTopicSnapshotsResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_topic_snapshots( - topic='topic_value', - ) - - # 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].topic - mock_val = 'topic_value' - assert arg == mock_val - - -def test_list_topic_snapshots_flattened_error(): - client = PublisherClient( - credentials=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_topic_snapshots( - pubsub.ListTopicSnapshotsRequest(), - topic='topic_value', - ) - -@pytest.mark.asyncio -async def test_list_topic_snapshots_flattened_async(): - client = PublisherAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_topic_snapshots), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = pubsub.ListTopicSnapshotsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(pubsub.ListTopicSnapshotsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_topic_snapshots( - topic='topic_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].topic - mock_val = 'topic_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_list_topic_snapshots_flattened_error_async(): - client = PublisherAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.list_topic_snapshots( - pubsub.ListTopicSnapshotsRequest(), - topic='topic_value', - ) - - -def test_list_topic_snapshots_pager(transport_name: str = "grpc"): - client = PublisherClient( - 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_topic_snapshots), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - pubsub.ListTopicSnapshotsResponse( - snapshots=[ - str(), - str(), - str(), - ], - next_page_token='abc', - ), - pubsub.ListTopicSnapshotsResponse( - snapshots=[], - next_page_token='def', - ), - pubsub.ListTopicSnapshotsResponse( - snapshots=[ - str(), - ], - next_page_token='ghi', - ), - pubsub.ListTopicSnapshotsResponse( - snapshots=[ - str(), - str(), - ], - ), - RuntimeError, - ) - - expected_metadata = () - retry = retries.Retry() - timeout = 5 - expected_metadata = tuple(expected_metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('topic', ''), - )), - ) - pager = client.list_topic_snapshots(request={}, retry=retry, timeout=timeout) - - assert pager._metadata == expected_metadata - assert pager._retry == retry - assert pager._timeout == timeout - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, str) - for i in results) -def test_list_topic_snapshots_pages(transport_name: str = "grpc"): - client = PublisherClient( - 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_topic_snapshots), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - pubsub.ListTopicSnapshotsResponse( - snapshots=[ - str(), - str(), - str(), - ], - next_page_token='abc', - ), - pubsub.ListTopicSnapshotsResponse( - snapshots=[], - next_page_token='def', - ), - pubsub.ListTopicSnapshotsResponse( - snapshots=[ - str(), - ], - next_page_token='ghi', - ), - pubsub.ListTopicSnapshotsResponse( - snapshots=[ - str(), - str(), - ], - ), - RuntimeError, - ) - pages = list(client.list_topic_snapshots(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_topic_snapshots_async_pager(): - client = PublisherAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_topic_snapshots), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - pubsub.ListTopicSnapshotsResponse( - snapshots=[ - str(), - str(), - str(), - ], - next_page_token='abc', - ), - pubsub.ListTopicSnapshotsResponse( - snapshots=[], - next_page_token='def', - ), - pubsub.ListTopicSnapshotsResponse( - snapshots=[ - str(), - ], - next_page_token='ghi', - ), - pubsub.ListTopicSnapshotsResponse( - snapshots=[ - str(), - str(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_topic_snapshots(request={},) - assert async_pager.next_page_token == 'abc' - responses = [] - async for response in async_pager: # pragma: no branch - responses.append(response) - - assert len(responses) == 6 - assert all(isinstance(i, str) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_topic_snapshots_async_pages(): - client = PublisherAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_topic_snapshots), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - pubsub.ListTopicSnapshotsResponse( - snapshots=[ - str(), - str(), - str(), - ], - next_page_token='abc', - ), - pubsub.ListTopicSnapshotsResponse( - snapshots=[], - next_page_token='def', - ), - pubsub.ListTopicSnapshotsResponse( - snapshots=[ - str(), - ], - next_page_token='ghi', - ), - pubsub.ListTopicSnapshotsResponse( - snapshots=[ - str(), - str(), - ], - ), - RuntimeError, - ) - pages = [] - # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` - # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 - async for page_ in ( # pragma: no branch - await client.list_topic_snapshots(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", [ - pubsub.DeleteTopicRequest, - dict, -]) -def test_delete_topic(request_type, transport: str = 'grpc'): - client = PublisherClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_topic), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = None - response = client.delete_topic(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = pubsub.DeleteTopicRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert response is None - - -def test_delete_topic_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = PublisherClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_topic), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.delete_topic() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == pubsub.DeleteTopicRequest() - - -def test_delete_topic_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 = PublisherClient( - 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 = pubsub.DeleteTopicRequest( - topic='topic_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_topic), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.delete_topic(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == pubsub.DeleteTopicRequest( - topic='topic_value', - ) - -def test_delete_topic_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = PublisherClient( - 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_topic in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_topic] = mock_rpc - request = {} - client.delete_topic(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.delete_topic(request) - - # Establish that a new wrapper 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_topic_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = PublisherAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_topic), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_topic() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == pubsub.DeleteTopicRequest() - -@pytest.mark.asyncio -async def test_delete_topic_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 = PublisherAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - 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_topic 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_topic] = mock_rpc - - request = {} - await client.delete_topic(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.delete_topic(request) - - # Establish that a new wrapper 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_topic_async(transport: str = 'grpc_asyncio', request_type=pubsub.DeleteTopicRequest): - client = PublisherAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_topic), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_topic(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = pubsub.DeleteTopicRequest() - 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_topic_async_from_dict(): - await test_delete_topic_async(request_type=dict) - - -def test_delete_topic_field_headers(): - client = PublisherClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = pubsub.DeleteTopicRequest() - - request.topic = 'topic_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_topic), - '__call__') as call: - call.return_value = None - client.delete_topic(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'topic=topic_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_delete_topic_field_headers_async(): - client = PublisherAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = pubsub.DeleteTopicRequest() - - request.topic = 'topic_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_topic), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_topic(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'topic=topic_value', - ) in kw['metadata'] - - -def test_delete_topic_flattened(): - client = PublisherClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_topic), - '__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_topic( - topic='topic_value', - ) - - # 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].topic - mock_val = 'topic_value' - assert arg == mock_val - - -def test_delete_topic_flattened_error(): - client = PublisherClient( - credentials=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_topic( - pubsub.DeleteTopicRequest(), - topic='topic_value', - ) - -@pytest.mark.asyncio -async def test_delete_topic_flattened_async(): - client = PublisherAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_topic), - '__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_topic( - topic='topic_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].topic - mock_val = 'topic_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_delete_topic_flattened_error_async(): - client = PublisherAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.delete_topic( - pubsub.DeleteTopicRequest(), - topic='topic_value', - ) - - -@pytest.mark.parametrize("request_type", [ - pubsub.DetachSubscriptionRequest, - dict, -]) -def test_detach_subscription(request_type, transport: str = 'grpc'): - client = PublisherClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.detach_subscription), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = pubsub.DetachSubscriptionResponse( - ) - response = client.detach_subscription(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = pubsub.DetachSubscriptionRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pubsub.DetachSubscriptionResponse) - - -def test_detach_subscription_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = PublisherClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.detach_subscription), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.detach_subscription() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == pubsub.DetachSubscriptionRequest() - - -def test_detach_subscription_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 = PublisherClient( - 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 = pubsub.DetachSubscriptionRequest( - subscription='subscription_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.detach_subscription), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.detach_subscription(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == pubsub.DetachSubscriptionRequest( - subscription='subscription_value', - ) - -def test_detach_subscription_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = PublisherClient( - 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.detach_subscription in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.detach_subscription] = mock_rpc - request = {} - client.detach_subscription(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.detach_subscription(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_detach_subscription_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = PublisherAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.detach_subscription), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(pubsub.DetachSubscriptionResponse( - )) - response = await client.detach_subscription() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == pubsub.DetachSubscriptionRequest() - -@pytest.mark.asyncio -async def test_detach_subscription_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 = PublisherAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - 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.detach_subscription 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.detach_subscription] = mock_rpc - - request = {} - await client.detach_subscription(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.detach_subscription(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_detach_subscription_async(transport: str = 'grpc_asyncio', request_type=pubsub.DetachSubscriptionRequest): - client = PublisherAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.detach_subscription), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(pubsub.DetachSubscriptionResponse( - )) - response = await client.detach_subscription(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = pubsub.DetachSubscriptionRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pubsub.DetachSubscriptionResponse) - - -@pytest.mark.asyncio -async def test_detach_subscription_async_from_dict(): - await test_detach_subscription_async(request_type=dict) - - -def test_detach_subscription_field_headers(): - client = PublisherClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = pubsub.DetachSubscriptionRequest() - - request.subscription = 'subscription_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.detach_subscription), - '__call__') as call: - call.return_value = pubsub.DetachSubscriptionResponse() - client.detach_subscription(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'subscription=subscription_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_detach_subscription_field_headers_async(): - client = PublisherAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = pubsub.DetachSubscriptionRequest() - - request.subscription = 'subscription_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.detach_subscription), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(pubsub.DetachSubscriptionResponse()) - await client.detach_subscription(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'subscription=subscription_value', - ) in kw['metadata'] - - -@pytest.mark.parametrize("request_type", [ - pubsub.Topic, - dict, -]) -def test_create_topic_rest(request_type): - client = PublisherClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/topics/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 = pubsub.Topic( - name='name_value', - kms_key_name='kms_key_name_value', - satisfies_pzs=True, - state=pubsub.Topic.State.ACTIVE, - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = pubsub.Topic.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.create_topic(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pubsub.Topic) - assert response.name == 'name_value' - assert response.kms_key_name == 'kms_key_name_value' - assert response.satisfies_pzs is True - assert response.state == pubsub.Topic.State.ACTIVE - -def test_create_topic_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 = PublisherClient( - 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_topic in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_topic] = mock_rpc - - request = {} - client.create_topic(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.create_topic(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_topic_rest_required_fields(request_type=pubsub.Topic): - transport_class = transports.PublisherRestTransport - - 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()).create_topic._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()).create_topic._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 = PublisherClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = pubsub.Topic() - # 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': "put", - '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 = pubsub.Topic.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.create_topic(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_create_topic_rest_unset_required_fields(): - transport = transports.PublisherRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.create_topic._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_create_topic_rest_interceptors(null_interceptor): - transport = transports.PublisherRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.PublisherRestInterceptor(), - ) - client = PublisherClient(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.PublisherRestInterceptor, "post_create_topic") as post, \ - mock.patch.object(transports.PublisherRestInterceptor, "pre_create_topic") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = pubsub.Topic.pb(pubsub.Topic()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = pubsub.Topic.to_json(pubsub.Topic()) - - request = pubsub.Topic() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = pubsub.Topic() - - client.create_topic(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_create_topic_rest_bad_request(transport: str = 'rest', request_type=pubsub.Topic): - client = PublisherClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/topics/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 = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.create_topic(request) - - -def test_create_topic_rest_flattened(): - client = PublisherClient( - 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 = pubsub.Topic() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/topics/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 = pubsub.Topic.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.create_topic(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1/{name=projects/*/topics/*}" % client.transport._host, args[1]) - - -def test_create_topic_rest_flattened_error(transport: str = 'rest'): - client = PublisherClient( - 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_topic( - pubsub.Topic(), - name='name_value', - ) - - -def test_create_topic_rest_error(): - client = PublisherClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - pubsub.UpdateTopicRequest, - dict, -]) -def test_update_topic_rest(request_type): - client = PublisherClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'topic': {'name': 'projects/sample1/topics/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 = pubsub.Topic( - name='name_value', - kms_key_name='kms_key_name_value', - satisfies_pzs=True, - state=pubsub.Topic.State.ACTIVE, - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = pubsub.Topic.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.update_topic(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pubsub.Topic) - assert response.name == 'name_value' - assert response.kms_key_name == 'kms_key_name_value' - assert response.satisfies_pzs is True - assert response.state == pubsub.Topic.State.ACTIVE - -def test_update_topic_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 = PublisherClient( - 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_topic in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_topic] = mock_rpc - - request = {} - client.update_topic(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.update_topic(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -def test_update_topic_rest_required_fields(request_type=pubsub.UpdateTopicRequest): - transport_class = transports.PublisherRestTransport - - request_init = {} - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_topic._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_topic._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - - client = PublisherClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = pubsub.Topic() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "patch", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = pubsub.Topic.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.update_topic(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_update_topic_rest_unset_required_fields(): - transport = transports.PublisherRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.update_topic._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("topic", "updateMask", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_topic_rest_interceptors(null_interceptor): - transport = transports.PublisherRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.PublisherRestInterceptor(), - ) - client = PublisherClient(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.PublisherRestInterceptor, "post_update_topic") as post, \ - mock.patch.object(transports.PublisherRestInterceptor, "pre_update_topic") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = pubsub.UpdateTopicRequest.pb(pubsub.UpdateTopicRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = pubsub.Topic.to_json(pubsub.Topic()) - - request = pubsub.UpdateTopicRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = pubsub.Topic() - - client.update_topic(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_update_topic_rest_bad_request(transport: str = 'rest', request_type=pubsub.UpdateTopicRequest): - client = PublisherClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'topic': {'name': 'projects/sample1/topics/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 = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.update_topic(request) - - -def test_update_topic_rest_flattened(): - client = PublisherClient( - 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 = pubsub.Topic() - - # get arguments that satisfy an http rule for this method - sample_request = {'topic': {'name': 'projects/sample1/topics/sample2'}} - - # get truthy value for each flattened field - mock_args = dict( - topic=pubsub.Topic(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = pubsub.Topic.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.update_topic(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1/{topic.name=projects/*/topics/*}" % client.transport._host, args[1]) - - -def test_update_topic_rest_flattened_error(transport: str = 'rest'): - client = PublisherClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.update_topic( - pubsub.UpdateTopicRequest(), - topic=pubsub.Topic(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -def test_update_topic_rest_error(): - client = PublisherClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - pubsub.PublishRequest, - dict, -]) -def test_publish_rest(request_type): - client = PublisherClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'topic': 'projects/sample1/topics/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 = pubsub.PublishResponse( - message_ids=['message_ids_value'], - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = pubsub.PublishResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.publish(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pubsub.PublishResponse) - assert response.message_ids == ['message_ids_value'] - -def test_publish_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 = PublisherClient( - 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.publish in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.publish] = mock_rpc - - request = {} - client.publish(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.publish(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_publish_rest_required_fields(request_type=pubsub.PublishRequest): - transport_class = transports.PublisherRestTransport - - request_init = {} - request_init["topic"] = "" - 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()).publish._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["topic"] = 'topic_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).publish._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "topic" in jsonified_request - assert jsonified_request["topic"] == 'topic_value' - - client = PublisherClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = pubsub.PublishResponse() - # 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 = pubsub.PublishResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.publish(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_publish_rest_unset_required_fields(): - transport = transports.PublisherRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.publish._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("topic", "messages", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_publish_rest_interceptors(null_interceptor): - transport = transports.PublisherRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.PublisherRestInterceptor(), - ) - client = PublisherClient(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.PublisherRestInterceptor, "post_publish") as post, \ - mock.patch.object(transports.PublisherRestInterceptor, "pre_publish") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = pubsub.PublishRequest.pb(pubsub.PublishRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = pubsub.PublishResponse.to_json(pubsub.PublishResponse()) - - request = pubsub.PublishRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = pubsub.PublishResponse() - - client.publish(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_publish_rest_bad_request(transport: str = 'rest', request_type=pubsub.PublishRequest): - client = PublisherClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'topic': 'projects/sample1/topics/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 = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.publish(request) - - -def test_publish_rest_flattened(): - client = PublisherClient( - 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 = pubsub.PublishResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'topic': 'projects/sample1/topics/sample2'} - - # get truthy value for each flattened field - mock_args = dict( - topic='topic_value', - messages=[pubsub.PubsubMessage(data=b'data_blob')], - ) - 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 = pubsub.PublishResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.publish(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1/{topic=projects/*/topics/*}:publish" % client.transport._host, args[1]) - - -def test_publish_rest_flattened_error(transport: str = 'rest'): - client = PublisherClient( - 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.publish( - pubsub.PublishRequest(), - topic='topic_value', - messages=[pubsub.PubsubMessage(data=b'data_blob')], - ) - - -def test_publish_rest_error(): - client = PublisherClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - pubsub.GetTopicRequest, - dict, -]) -def test_get_topic_rest(request_type): - client = PublisherClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'topic': 'projects/sample1/topics/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 = pubsub.Topic( - name='name_value', - kms_key_name='kms_key_name_value', - satisfies_pzs=True, - state=pubsub.Topic.State.ACTIVE, - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = pubsub.Topic.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.get_topic(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pubsub.Topic) - assert response.name == 'name_value' - assert response.kms_key_name == 'kms_key_name_value' - assert response.satisfies_pzs is True - assert response.state == pubsub.Topic.State.ACTIVE - -def test_get_topic_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 = PublisherClient( - 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_topic in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_topic] = mock_rpc - - request = {} - client.get_topic(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_topic(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_topic_rest_required_fields(request_type=pubsub.GetTopicRequest): - transport_class = transports.PublisherRestTransport - - request_init = {} - request_init["topic"] = "" - 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_topic._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["topic"] = 'topic_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_topic._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "topic" in jsonified_request - assert jsonified_request["topic"] == 'topic_value' - - client = PublisherClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = pubsub.Topic() - # 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 = pubsub.Topic.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.get_topic(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_get_topic_rest_unset_required_fields(): - transport = transports.PublisherRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.get_topic._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("topic", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_topic_rest_interceptors(null_interceptor): - transport = transports.PublisherRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.PublisherRestInterceptor(), - ) - client = PublisherClient(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.PublisherRestInterceptor, "post_get_topic") as post, \ - mock.patch.object(transports.PublisherRestInterceptor, "pre_get_topic") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = pubsub.GetTopicRequest.pb(pubsub.GetTopicRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = pubsub.Topic.to_json(pubsub.Topic()) - - request = pubsub.GetTopicRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = pubsub.Topic() - - client.get_topic(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_topic_rest_bad_request(transport: str = 'rest', request_type=pubsub.GetTopicRequest): - client = PublisherClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'topic': 'projects/sample1/topics/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 = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_topic(request) - - -def test_get_topic_rest_flattened(): - client = PublisherClient( - 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 = pubsub.Topic() - - # get arguments that satisfy an http rule for this method - sample_request = {'topic': 'projects/sample1/topics/sample2'} - - # get truthy value for each flattened field - mock_args = dict( - topic='topic_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 = pubsub.Topic.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.get_topic(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1/{topic=projects/*/topics/*}" % client.transport._host, args[1]) - - -def test_get_topic_rest_flattened_error(transport: str = 'rest'): - client = PublisherClient( - 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_topic( - pubsub.GetTopicRequest(), - topic='topic_value', - ) - - -def test_get_topic_rest_error(): - client = PublisherClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - pubsub.ListTopicsRequest, - dict, -]) -def test_list_topics_rest(request_type): - client = PublisherClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'project': 'projects/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 = pubsub.ListTopicsResponse( - next_page_token='next_page_token_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = pubsub.ListTopicsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.list_topics(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListTopicsPager) - assert response.next_page_token == 'next_page_token_value' - -def test_list_topics_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 = PublisherClient( - 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_topics in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_topics] = mock_rpc - - request = {} - client.list_topics(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_topics(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_topics_rest_required_fields(request_type=pubsub.ListTopicsRequest): - transport_class = transports.PublisherRestTransport - - request_init = {} - request_init["project"] = "" - 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_topics._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["project"] = 'project_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_topics._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 "project" in jsonified_request - assert jsonified_request["project"] == 'project_value' - - client = PublisherClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = pubsub.ListTopicsResponse() - # 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 = pubsub.ListTopicsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.list_topics(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_list_topics_rest_unset_required_fields(): - transport = transports.PublisherRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.list_topics._get_unset_required_fields({}) - assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("project", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_topics_rest_interceptors(null_interceptor): - transport = transports.PublisherRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.PublisherRestInterceptor(), - ) - client = PublisherClient(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.PublisherRestInterceptor, "post_list_topics") as post, \ - mock.patch.object(transports.PublisherRestInterceptor, "pre_list_topics") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = pubsub.ListTopicsRequest.pb(pubsub.ListTopicsRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = pubsub.ListTopicsResponse.to_json(pubsub.ListTopicsResponse()) - - request = pubsub.ListTopicsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = pubsub.ListTopicsResponse() - - client.list_topics(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_topics_rest_bad_request(transport: str = 'rest', request_type=pubsub.ListTopicsRequest): - client = PublisherClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'project': 'projects/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 = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_topics(request) - - -def test_list_topics_rest_flattened(): - client = PublisherClient( - 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 = pubsub.ListTopicsResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'project': 'projects/sample1'} - - # get truthy value for each flattened field - mock_args = dict( - project='project_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 = pubsub.ListTopicsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.list_topics(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1/{project=projects/*}/topics" % client.transport._host, args[1]) - - -def test_list_topics_rest_flattened_error(transport: str = 'rest'): - client = PublisherClient( - 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_topics( - pubsub.ListTopicsRequest(), - project='project_value', - ) - - -def test_list_topics_rest_pager(transport: str = 'rest'): - client = PublisherClient( - 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 = ( - pubsub.ListTopicsResponse( - topics=[ - pubsub.Topic(), - pubsub.Topic(), - pubsub.Topic(), - ], - next_page_token='abc', - ), - pubsub.ListTopicsResponse( - topics=[], - next_page_token='def', - ), - pubsub.ListTopicsResponse( - topics=[ - pubsub.Topic(), - ], - next_page_token='ghi', - ), - pubsub.ListTopicsResponse( - topics=[ - pubsub.Topic(), - pubsub.Topic(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(pubsub.ListTopicsResponse.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 = {'project': 'projects/sample1'} - - pager = client.list_topics(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, pubsub.Topic) - for i in results) - - pages = list(client.list_topics(request=sample_request).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -@pytest.mark.parametrize("request_type", [ - pubsub.ListTopicSubscriptionsRequest, - dict, -]) -def test_list_topic_subscriptions_rest(request_type): - client = PublisherClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'topic': 'projects/sample1/topics/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 = pubsub.ListTopicSubscriptionsResponse( - subscriptions=['subscriptions_value'], - next_page_token='next_page_token_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = pubsub.ListTopicSubscriptionsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.list_topic_subscriptions(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListTopicSubscriptionsPager) - assert response.subscriptions == ['subscriptions_value'] - assert response.next_page_token == 'next_page_token_value' - -def test_list_topic_subscriptions_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 = PublisherClient( - 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_topic_subscriptions in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_topic_subscriptions] = mock_rpc - - request = {} - client.list_topic_subscriptions(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_topic_subscriptions(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_topic_subscriptions_rest_required_fields(request_type=pubsub.ListTopicSubscriptionsRequest): - transport_class = transports.PublisherRestTransport - - request_init = {} - request_init["topic"] = "" - 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_topic_subscriptions._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["topic"] = 'topic_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_topic_subscriptions._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 "topic" in jsonified_request - assert jsonified_request["topic"] == 'topic_value' - - client = PublisherClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = pubsub.ListTopicSubscriptionsResponse() - # 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 = pubsub.ListTopicSubscriptionsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.list_topic_subscriptions(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_list_topic_subscriptions_rest_unset_required_fields(): - transport = transports.PublisherRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.list_topic_subscriptions._get_unset_required_fields({}) - assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("topic", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_topic_subscriptions_rest_interceptors(null_interceptor): - transport = transports.PublisherRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.PublisherRestInterceptor(), - ) - client = PublisherClient(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.PublisherRestInterceptor, "post_list_topic_subscriptions") as post, \ - mock.patch.object(transports.PublisherRestInterceptor, "pre_list_topic_subscriptions") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = pubsub.ListTopicSubscriptionsRequest.pb(pubsub.ListTopicSubscriptionsRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = pubsub.ListTopicSubscriptionsResponse.to_json(pubsub.ListTopicSubscriptionsResponse()) - - request = pubsub.ListTopicSubscriptionsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = pubsub.ListTopicSubscriptionsResponse() - - client.list_topic_subscriptions(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_topic_subscriptions_rest_bad_request(transport: str = 'rest', request_type=pubsub.ListTopicSubscriptionsRequest): - client = PublisherClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'topic': 'projects/sample1/topics/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 = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_topic_subscriptions(request) - - -def test_list_topic_subscriptions_rest_flattened(): - client = PublisherClient( - 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 = pubsub.ListTopicSubscriptionsResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'topic': 'projects/sample1/topics/sample2'} - - # get truthy value for each flattened field - mock_args = dict( - topic='topic_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 = pubsub.ListTopicSubscriptionsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.list_topic_subscriptions(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1/{topic=projects/*/topics/*}/subscriptions" % client.transport._host, args[1]) - - -def test_list_topic_subscriptions_rest_flattened_error(transport: str = 'rest'): - client = PublisherClient( - 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_topic_subscriptions( - pubsub.ListTopicSubscriptionsRequest(), - topic='topic_value', - ) - - -def test_list_topic_subscriptions_rest_pager(transport: str = 'rest'): - client = PublisherClient( - 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 = ( - pubsub.ListTopicSubscriptionsResponse( - subscriptions=[ - str(), - str(), - str(), - ], - next_page_token='abc', - ), - pubsub.ListTopicSubscriptionsResponse( - subscriptions=[], - next_page_token='def', - ), - pubsub.ListTopicSubscriptionsResponse( - subscriptions=[ - str(), - ], - next_page_token='ghi', - ), - pubsub.ListTopicSubscriptionsResponse( - subscriptions=[ - str(), - str(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(pubsub.ListTopicSubscriptionsResponse.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 = {'topic': 'projects/sample1/topics/sample2'} - - pager = client.list_topic_subscriptions(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, str) - for i in results) - - pages = list(client.list_topic_subscriptions(request=sample_request).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -@pytest.mark.parametrize("request_type", [ - pubsub.ListTopicSnapshotsRequest, - dict, -]) -def test_list_topic_snapshots_rest(request_type): - client = PublisherClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'topic': 'projects/sample1/topics/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 = pubsub.ListTopicSnapshotsResponse( - snapshots=['snapshots_value'], - next_page_token='next_page_token_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = pubsub.ListTopicSnapshotsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.list_topic_snapshots(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListTopicSnapshotsPager) - assert response.snapshots == ['snapshots_value'] - assert response.next_page_token == 'next_page_token_value' - -def test_list_topic_snapshots_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 = PublisherClient( - 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_topic_snapshots in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_topic_snapshots] = mock_rpc - - request = {} - client.list_topic_snapshots(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_topic_snapshots(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_topic_snapshots_rest_required_fields(request_type=pubsub.ListTopicSnapshotsRequest): - transport_class = transports.PublisherRestTransport - - request_init = {} - request_init["topic"] = "" - 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_topic_snapshots._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["topic"] = 'topic_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_topic_snapshots._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 "topic" in jsonified_request - assert jsonified_request["topic"] == 'topic_value' - - client = PublisherClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = pubsub.ListTopicSnapshotsResponse() - # 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 = pubsub.ListTopicSnapshotsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.list_topic_snapshots(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_list_topic_snapshots_rest_unset_required_fields(): - transport = transports.PublisherRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.list_topic_snapshots._get_unset_required_fields({}) - assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("topic", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_topic_snapshots_rest_interceptors(null_interceptor): - transport = transports.PublisherRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.PublisherRestInterceptor(), - ) - client = PublisherClient(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.PublisherRestInterceptor, "post_list_topic_snapshots") as post, \ - mock.patch.object(transports.PublisherRestInterceptor, "pre_list_topic_snapshots") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = pubsub.ListTopicSnapshotsRequest.pb(pubsub.ListTopicSnapshotsRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = pubsub.ListTopicSnapshotsResponse.to_json(pubsub.ListTopicSnapshotsResponse()) - - request = pubsub.ListTopicSnapshotsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = pubsub.ListTopicSnapshotsResponse() - - client.list_topic_snapshots(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_topic_snapshots_rest_bad_request(transport: str = 'rest', request_type=pubsub.ListTopicSnapshotsRequest): - client = PublisherClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'topic': 'projects/sample1/topics/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 = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_topic_snapshots(request) - - -def test_list_topic_snapshots_rest_flattened(): - client = PublisherClient( - 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 = pubsub.ListTopicSnapshotsResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'topic': 'projects/sample1/topics/sample2'} - - # get truthy value for each flattened field - mock_args = dict( - topic='topic_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 = pubsub.ListTopicSnapshotsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.list_topic_snapshots(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1/{topic=projects/*/topics/*}/snapshots" % client.transport._host, args[1]) - - -def test_list_topic_snapshots_rest_flattened_error(transport: str = 'rest'): - client = PublisherClient( - 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_topic_snapshots( - pubsub.ListTopicSnapshotsRequest(), - topic='topic_value', - ) - - -def test_list_topic_snapshots_rest_pager(transport: str = 'rest'): - client = PublisherClient( - 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 = ( - pubsub.ListTopicSnapshotsResponse( - snapshots=[ - str(), - str(), - str(), - ], - next_page_token='abc', - ), - pubsub.ListTopicSnapshotsResponse( - snapshots=[], - next_page_token='def', - ), - pubsub.ListTopicSnapshotsResponse( - snapshots=[ - str(), - ], - next_page_token='ghi', - ), - pubsub.ListTopicSnapshotsResponse( - snapshots=[ - str(), - str(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(pubsub.ListTopicSnapshotsResponse.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 = {'topic': 'projects/sample1/topics/sample2'} - - pager = client.list_topic_snapshots(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, str) - for i in results) - - pages = list(client.list_topic_snapshots(request=sample_request).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -@pytest.mark.parametrize("request_type", [ - pubsub.DeleteTopicRequest, - dict, -]) -def test_delete_topic_rest(request_type): - client = PublisherClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'topic': 'projects/sample1/topics/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 = Response() - response_value.status_code = 200 - json_return_value = '' - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.delete_topic(request) - - # Establish that the response is the type that we expect. - assert response is None - -def test_delete_topic_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 = PublisherClient( - 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_topic in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_topic] = mock_rpc - - request = {} - client.delete_topic(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.delete_topic(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_topic_rest_required_fields(request_type=pubsub.DeleteTopicRequest): - transport_class = transports.PublisherRestTransport - - request_init = {} - request_init["topic"] = "" - 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_topic._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["topic"] = 'topic_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_topic._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "topic" in jsonified_request - assert jsonified_request["topic"] == 'topic_value' - - client = PublisherClient( - 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 - - response = client.delete_topic(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_delete_topic_rest_unset_required_fields(): - transport = transports.PublisherRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.delete_topic._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("topic", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_delete_topic_rest_interceptors(null_interceptor): - transport = transports.PublisherRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.PublisherRestInterceptor(), - ) - client = PublisherClient(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.PublisherRestInterceptor, "pre_delete_topic") as pre: - pre.assert_not_called() - pb_message = pubsub.DeleteTopicRequest.pb(pubsub.DeleteTopicRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - - request = pubsub.DeleteTopicRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - - client.delete_topic(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - - -def test_delete_topic_rest_bad_request(transport: str = 'rest', request_type=pubsub.DeleteTopicRequest): - client = PublisherClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'topic': 'projects/sample1/topics/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 = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.delete_topic(request) - - -def test_delete_topic_rest_flattened(): - client = PublisherClient( - 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 = {'topic': 'projects/sample1/topics/sample2'} - - # get truthy value for each flattened field - mock_args = dict( - topic='topic_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 - - client.delete_topic(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1/{topic=projects/*/topics/*}" % client.transport._host, args[1]) - - -def test_delete_topic_rest_flattened_error(transport: str = 'rest'): - client = PublisherClient( - 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_topic( - pubsub.DeleteTopicRequest(), - topic='topic_value', - ) - - -def test_delete_topic_rest_error(): - client = PublisherClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - pubsub.DetachSubscriptionRequest, - dict, -]) -def test_detach_subscription_rest(request_type): - client = PublisherClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'subscription': 'projects/sample1/subscriptions/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 = pubsub.DetachSubscriptionResponse( - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = pubsub.DetachSubscriptionResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.detach_subscription(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pubsub.DetachSubscriptionResponse) - -def test_detach_subscription_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 = PublisherClient( - 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.detach_subscription in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.detach_subscription] = mock_rpc - - request = {} - client.detach_subscription(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.detach_subscription(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_detach_subscription_rest_required_fields(request_type=pubsub.DetachSubscriptionRequest): - transport_class = transports.PublisherRestTransport - - request_init = {} - request_init["subscription"] = "" - 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()).detach_subscription._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["subscription"] = 'subscription_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).detach_subscription._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "subscription" in jsonified_request - assert jsonified_request["subscription"] == 'subscription_value' - - client = PublisherClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = pubsub.DetachSubscriptionResponse() - # 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.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = pubsub.DetachSubscriptionResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.detach_subscription(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_detach_subscription_rest_unset_required_fields(): - transport = transports.PublisherRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.detach_subscription._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("subscription", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_detach_subscription_rest_interceptors(null_interceptor): - transport = transports.PublisherRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.PublisherRestInterceptor(), - ) - client = PublisherClient(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.PublisherRestInterceptor, "post_detach_subscription") as post, \ - mock.patch.object(transports.PublisherRestInterceptor, "pre_detach_subscription") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = pubsub.DetachSubscriptionRequest.pb(pubsub.DetachSubscriptionRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = pubsub.DetachSubscriptionResponse.to_json(pubsub.DetachSubscriptionResponse()) - - request = pubsub.DetachSubscriptionRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = pubsub.DetachSubscriptionResponse() - - client.detach_subscription(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_detach_subscription_rest_bad_request(transport: str = 'rest', request_type=pubsub.DetachSubscriptionRequest): - client = PublisherClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'subscription': 'projects/sample1/subscriptions/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 = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.detach_subscription(request) - - -def test_detach_subscription_rest_error(): - client = PublisherClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.PublisherGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = PublisherClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.PublisherGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = PublisherClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide an api_key and a transport instance. - transport = transports.PublisherGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = PublisherClient( - 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 = PublisherClient( - client_options=options, - credentials=ga_credentials.AnonymousCredentials() - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.PublisherGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = PublisherClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.PublisherGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = PublisherClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.PublisherGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.PublisherGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.PublisherGrpcTransport, - transports.PublisherGrpcAsyncIOTransport, - transports.PublisherRestTransport, -]) -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() - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "rest", -]) -def test_transport_kind(transport_name): - transport = PublisherClient.get_transport_class(transport_name)( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert transport.kind == transport_name - -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. - client = PublisherClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.PublisherGrpcTransport, - ) - -def test_publisher_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.PublisherTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_publisher_base_transport(): - # Instantiate the base transport. - with mock.patch('google.pubsub_v1.services.publisher.transports.PublisherTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.PublisherTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'create_topic', - 'update_topic', - 'publish', - 'get_topic', - 'list_topics', - 'list_topic_subscriptions', - 'list_topic_snapshots', - 'delete_topic', - 'detach_subscription', - 'set_iam_policy', - 'get_iam_policy', - 'test_iam_permissions', - ) - 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_publisher_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.pubsub_v1.services.publisher.transports.PublisherTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.PublisherTransport( - credentials_file="credentials.json", - quota_project_id="octopus", - ) - load_creds.assert_called_once_with("credentials.json", - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/pubsub', -), - quota_project_id="octopus", - ) - - -def test_publisher_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.pubsub_v1.services.publisher.transports.PublisherTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.PublisherTransport() - adc.assert_called_once() - - -def test_publisher_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) - PublisherClient() - adc.assert_called_once_with( - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/pubsub', -), - quota_project_id=None, - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.PublisherGrpcTransport, - transports.PublisherGrpcAsyncIOTransport, - ], -) -def test_publisher_transport_auth_adc(transport_class): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class(quota_project_id="octopus", scopes=["1", "2"]) - adc.assert_called_once_with( - scopes=["1", "2"], - default_scopes=( 'https://www.googleapis.com/auth/cloud-platform', 'https://www.googleapis.com/auth/pubsub',), - quota_project_id="octopus", - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.PublisherGrpcTransport, - transports.PublisherGrpcAsyncIOTransport, - transports.PublisherRestTransport, - ], -) -def test_publisher_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.PublisherGrpcTransport, grpc_helpers), - (transports.PublisherGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -def test_publisher_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( - "pubsub.googleapis.com:443", - credentials=creds, - credentials_file=None, - quota_project_id="octopus", - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/pubsub', -), - scopes=["1", "2"], - default_host="pubsub.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("transport_class", [transports.PublisherGrpcTransport, transports.PublisherGrpcAsyncIOTransport]) -def test_publisher_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_publisher_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.PublisherRestTransport ( - 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_publisher_host_no_port(transport_name): - client = PublisherClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='pubsub.googleapis.com'), - transport=transport_name, - ) - assert client.transport._host == ( - 'pubsub.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://pubsub.googleapis.com' - ) - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", - "rest", -]) -def test_publisher_host_with_port(transport_name): - client = PublisherClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='pubsub.googleapis.com:8000'), - transport=transport_name, - ) - assert client.transport._host == ( - 'pubsub.googleapis.com:8000' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://pubsub.googleapis.com:8000' - ) - -@pytest.mark.parametrize("transport_name", [ - "rest", -]) -def test_publisher_client_transport_session_collision(transport_name): - creds1 = ga_credentials.AnonymousCredentials() - creds2 = ga_credentials.AnonymousCredentials() - client1 = PublisherClient( - credentials=creds1, - transport=transport_name, - ) - client2 = PublisherClient( - credentials=creds2, - transport=transport_name, - ) - session1 = client1.transport.create_topic._session - session2 = client2.transport.create_topic._session - assert session1 != session2 - session1 = client1.transport.update_topic._session - session2 = client2.transport.update_topic._session - assert session1 != session2 - session1 = client1.transport.publish._session - session2 = client2.transport.publish._session - assert session1 != session2 - session1 = client1.transport.get_topic._session - session2 = client2.transport.get_topic._session - assert session1 != session2 - session1 = client1.transport.list_topics._session - session2 = client2.transport.list_topics._session - assert session1 != session2 - session1 = client1.transport.list_topic_subscriptions._session - session2 = client2.transport.list_topic_subscriptions._session - assert session1 != session2 - session1 = client1.transport.list_topic_snapshots._session - session2 = client2.transport.list_topic_snapshots._session - assert session1 != session2 - session1 = client1.transport.delete_topic._session - session2 = client2.transport.delete_topic._session - assert session1 != session2 - session1 = client1.transport.detach_subscription._session - session2 = client2.transport.detach_subscription._session - assert session1 != session2 -def test_publisher_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.PublisherGrpcTransport( - 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_publisher_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.PublisherGrpcAsyncIOTransport( - host="squid.clam.whelk", - channel=channel, - ) - assert transport.grpc_channel == channel - assert transport._host == "squid.clam.whelk:443" - assert transport._ssl_channel_credentials == None - - -# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are -# removed from grpc/grpc_asyncio transport constructor. -@pytest.mark.parametrize("transport_class", [transports.PublisherGrpcTransport, transports.PublisherGrpcAsyncIOTransport]) -def test_publisher_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.PublisherGrpcTransport, transports.PublisherGrpcAsyncIOTransport]) -def test_publisher_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_schema_path(): - project = "squid" - schema = "clam" - expected = "projects/{project}/schemas/{schema}".format(project=project, schema=schema, ) - actual = PublisherClient.schema_path(project, schema) - assert expected == actual - - -def test_parse_schema_path(): - expected = { - "project": "whelk", - "schema": "octopus", - } - path = PublisherClient.schema_path(**expected) - - # Check that the path construction is reversible. - actual = PublisherClient.parse_schema_path(path) - assert expected == actual - -def test_subscription_path(): - project = "oyster" - subscription = "nudibranch" - expected = "projects/{project}/subscriptions/{subscription}".format(project=project, subscription=subscription, ) - actual = PublisherClient.subscription_path(project, subscription) - assert expected == actual - - -def test_parse_subscription_path(): - expected = { - "project": "cuttlefish", - "subscription": "mussel", - } - path = PublisherClient.subscription_path(**expected) - - # Check that the path construction is reversible. - actual = PublisherClient.parse_subscription_path(path) - assert expected == actual - -def test_topic_path(): - project = "winkle" - topic = "nautilus" - expected = "projects/{project}/topics/{topic}".format(project=project, topic=topic, ) - actual = PublisherClient.topic_path(project, topic) - assert expected == actual - - -def test_parse_topic_path(): - expected = { - "project": "scallop", - "topic": "abalone", - } - path = PublisherClient.topic_path(**expected) - - # Check that the path construction is reversible. - actual = PublisherClient.parse_topic_path(path) - assert expected == actual - -def test_common_billing_account_path(): - billing_account = "squid" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = PublisherClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "clam", - } - path = PublisherClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = PublisherClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "whelk" - expected = "folders/{folder}".format(folder=folder, ) - actual = PublisherClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "octopus", - } - path = PublisherClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = PublisherClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "oyster" - expected = "organizations/{organization}".format(organization=organization, ) - actual = PublisherClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "nudibranch", - } - path = PublisherClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = PublisherClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "cuttlefish" - expected = "projects/{project}".format(project=project, ) - actual = PublisherClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "mussel", - } - path = PublisherClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = PublisherClient.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 = PublisherClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "scallop", - "location": "abalone", - } - path = PublisherClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = PublisherClient.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.PublisherTransport, '_prep_wrapped_messages') as prep: - client = PublisherClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.PublisherTransport, '_prep_wrapped_messages') as prep: - transport_class = PublisherClient.get_transport_class() - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - -@pytest.mark.asyncio -async def test_transport_close_async(): - client = PublisherAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - 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_get_iam_policy_rest_bad_request(transport: str = 'rest', request_type=iam_policy_pb2.GetIamPolicyRequest): - client = PublisherClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'resource': 'projects/sample1/topics/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() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_iam_policy(request) - -@pytest.mark.parametrize("request_type", [ - iam_policy_pb2.GetIamPolicyRequest, - dict, -]) -def test_get_iam_policy_rest(request_type): - client = PublisherClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'resource': 'projects/sample1/topics/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 = policy_pb2.Policy() - - # 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 - - response = client.get_iam_policy(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, policy_pb2.Policy) - -def test_set_iam_policy_rest_bad_request(transport: str = 'rest', request_type=iam_policy_pb2.SetIamPolicyRequest): - client = PublisherClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'resource': 'projects/sample1/topics/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() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.set_iam_policy(request) - -@pytest.mark.parametrize("request_type", [ - iam_policy_pb2.SetIamPolicyRequest, - dict, -]) -def test_set_iam_policy_rest(request_type): - client = PublisherClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'resource': 'projects/sample1/topics/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 = policy_pb2.Policy() - - # 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 - - response = client.set_iam_policy(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, policy_pb2.Policy) - -def test_test_iam_permissions_rest_bad_request(transport: str = 'rest', request_type=iam_policy_pb2.TestIamPermissionsRequest): - client = PublisherClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'resource': 'projects/sample1/subscriptions/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() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.test_iam_permissions(request) - -@pytest.mark.parametrize("request_type", [ - iam_policy_pb2.TestIamPermissionsRequest, - dict, -]) -def test_test_iam_permissions_rest(request_type): - client = PublisherClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'resource': 'projects/sample1/subscriptions/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 = iam_policy_pb2.TestIamPermissionsResponse() - - # 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 - - 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_set_iam_policy(transport: str = "grpc"): - client = PublisherClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional 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 = PublisherAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional 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 = PublisherClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = PublisherAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = PublisherClient( - 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 = PublisherAsyncClient( - 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 = grpc_helpers_async.FakeUnaryUnaryCall( - policy_pb2.Policy() - ) - - response = await client.set_iam_policy( - request={ - "resource": "resource_value", - "policy": policy_pb2.Policy(version=774), - } - ) - call.assert_called() - - -def test_get_iam_policy(transport: str = "grpc"): - client = PublisherClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional 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 = PublisherAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional 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 = PublisherClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = PublisherAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = PublisherClient( - 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 = PublisherAsyncClient( - 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 = grpc_helpers_async.FakeUnaryUnaryCall( - policy_pb2.Policy() - ) - - response = await client.get_iam_policy( - request={ - "resource": "resource_value", - "options": options_pb2.GetPolicyOptions(requested_policy_version=2598), - } - ) - call.assert_called() - - -def test_test_iam_permissions(transport: str = "grpc"): - client = PublisherClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional 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 = PublisherAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional 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 = PublisherClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = PublisherAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = PublisherClient( - 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 = PublisherAsyncClient( - 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 = grpc_helpers_async.FakeUnaryUnaryCall( - iam_policy_pb2.TestIamPermissionsResponse() - ) - - response = await client.test_iam_permissions( - request={ - "resource": "resource_value", - "permissions": ["permissions_value"], - } - ) - call.assert_called() - - -def test_transport_close(): - transports = { - "rest": "_session", - "grpc": "_grpc_channel", - } - - for transport, close_name in transports.items(): - client = PublisherClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport - ) - with mock.patch.object(type(getattr(client.transport, close_name)), "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 = PublisherClient( - 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", [ - (PublisherClient, transports.PublisherGrpcTransport), - (PublisherAsyncClient, transports.PublisherGrpcAsyncIOTransport), -]) -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/owl-bot-staging/v1/tests/unit/gapic/pubsub_v1/test_schema_service.py b/owl-bot-staging/v1/tests/unit/gapic/pubsub_v1/test_schema_service.py deleted file mode 100644 index 21144feec..000000000 --- a/owl-bot-staging/v1/tests/unit/gapic/pubsub_v1/test_schema_service.py +++ /dev/null @@ -1,8888 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import os -# try/except added for compatibility with python < 3.8 -try: - from unittest import mock - from unittest.mock import AsyncMock # pragma: NO COVER -except ImportError: # pragma: NO COVER - import mock - -import grpc -from grpc.experimental import aio -from collections.abc import Iterable -from google.protobuf import json_format -import json -import math -import pytest -from google.api_core import api_core_version -from proto.marshal.rules.dates import DurationRule, TimestampRule -from proto.marshal.rules import wrappers -from requests import Response -from requests import Request, PreparedRequest -from requests.sessions import Session -from google.protobuf import json_format - -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.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.oauth2 import service_account -from google.protobuf import timestamp_pb2 # type: ignore -from google.pubsub_v1.services.schema_service import SchemaServiceAsyncClient -from google.pubsub_v1.services.schema_service import SchemaServiceClient -from google.pubsub_v1.services.schema_service import pagers -from google.pubsub_v1.services.schema_service import transports -from google.pubsub_v1.types import schema -from google.pubsub_v1.types import schema as gp_schema -import google.auth - - -def client_cert_source_callback(): - return b"cert bytes", b"key bytes" - -# If default endpoint is localhost, then default mtls endpoint will be the same. -# This method modifies the default endpoint so the client can produce a different -# mtls endpoint for endpoint testing purposes. -def modify_default_endpoint(client): - return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT - -# If default endpoint template is localhost, then default mtls endpoint will be the same. -# This method modifies the default endpoint template so the client can produce a different -# mtls endpoint for endpoint testing purposes. -def modify_default_endpoint_template(client): - return "test.{UNIVERSE_DOMAIN}" if ("localhost" in client._DEFAULT_ENDPOINT_TEMPLATE) else client._DEFAULT_ENDPOINT_TEMPLATE - - -def test__get_default_mtls_endpoint(): - api_endpoint = "example.googleapis.com" - api_mtls_endpoint = "example.mtls.googleapis.com" - sandbox_endpoint = "example.sandbox.googleapis.com" - sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" - non_googleapi = "api.example.com" - - assert SchemaServiceClient._get_default_mtls_endpoint(None) is None - assert SchemaServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert SchemaServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert SchemaServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert SchemaServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert SchemaServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - -def test__read_environment_variables(): - assert SchemaServiceClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - assert SchemaServiceClient._read_environment_variables() == (True, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - assert SchemaServiceClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError) as excinfo: - SchemaServiceClient._read_environment_variables() - assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - assert SchemaServiceClient._read_environment_variables() == (False, "never", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - assert SchemaServiceClient._read_environment_variables() == (False, "always", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): - assert SchemaServiceClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError) as excinfo: - SchemaServiceClient._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 SchemaServiceClient._read_environment_variables() == (False, "auto", "foo.com") - -def test__get_client_cert_source(): - mock_provided_cert_source = mock.Mock() - mock_default_cert_source = mock.Mock() - - assert SchemaServiceClient._get_client_cert_source(None, False) is None - assert SchemaServiceClient._get_client_cert_source(mock_provided_cert_source, False) is None - assert SchemaServiceClient._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 SchemaServiceClient._get_client_cert_source(None, True) is mock_default_cert_source - assert SchemaServiceClient._get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source - -@mock.patch.object(SchemaServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(SchemaServiceClient)) -@mock.patch.object(SchemaServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(SchemaServiceAsyncClient)) -def test__get_api_endpoint(): - api_override = "foo.com" - mock_client_cert_source = mock.Mock() - default_universe = SchemaServiceClient._DEFAULT_UNIVERSE - default_endpoint = SchemaServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) - mock_universe = "bar.com" - mock_endpoint = SchemaServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) - - assert SchemaServiceClient._get_api_endpoint(api_override, mock_client_cert_source, default_universe, "always") == api_override - assert SchemaServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "auto") == SchemaServiceClient.DEFAULT_MTLS_ENDPOINT - assert SchemaServiceClient._get_api_endpoint(None, None, default_universe, "auto") == default_endpoint - assert SchemaServiceClient._get_api_endpoint(None, None, default_universe, "always") == SchemaServiceClient.DEFAULT_MTLS_ENDPOINT - assert SchemaServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "always") == SchemaServiceClient.DEFAULT_MTLS_ENDPOINT - assert SchemaServiceClient._get_api_endpoint(None, None, mock_universe, "never") == mock_endpoint - assert SchemaServiceClient._get_api_endpoint(None, None, default_universe, "never") == default_endpoint - - with pytest.raises(MutualTLSChannelError) as excinfo: - SchemaServiceClient._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 SchemaServiceClient._get_universe_domain(client_universe_domain, universe_domain_env) == client_universe_domain - assert SchemaServiceClient._get_universe_domain(None, universe_domain_env) == universe_domain_env - assert SchemaServiceClient._get_universe_domain(None, None) == SchemaServiceClient._DEFAULT_UNIVERSE - - with pytest.raises(ValueError) as excinfo: - SchemaServiceClient._get_universe_domain("", None) - assert str(excinfo.value) == "Universe Domain cannot be an empty string." - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (SchemaServiceClient, transports.SchemaServiceGrpcTransport, "grpc"), - (SchemaServiceClient, transports.SchemaServiceRestTransport, "rest"), -]) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials() - ) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - transport=transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [int(part) for part in google.auth.__version__.split(".")[0:2]] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class( - transport=transport_class(credentials=credentials) - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert str(excinfo.value) == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.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 >= 15): - client = client_class(client_options={"universe_domain": "bar.com"}, transport=transport_class(credentials=ga_credentials.AnonymousCredentials(),)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert str(excinfo.value) == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - -@pytest.mark.parametrize("client_class,transport_name", [ - (SchemaServiceClient, "grpc"), - (SchemaServiceAsyncClient, "grpc_asyncio"), - (SchemaServiceClient, "rest"), -]) -def test_schema_service_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 == ( - 'pubsub.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://pubsub.googleapis.com' - ) - - -@pytest.mark.parametrize("transport_class,transport_name", [ - (transports.SchemaServiceGrpcTransport, "grpc"), - (transports.SchemaServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (transports.SchemaServiceRestTransport, "rest"), -]) -def test_schema_service_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", [ - (SchemaServiceClient, "grpc"), - (SchemaServiceAsyncClient, "grpc_asyncio"), - (SchemaServiceClient, "rest"), -]) -def test_schema_service_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 == ( - 'pubsub.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://pubsub.googleapis.com' - ) - - -def test_schema_service_client_get_transport_class(): - transport = SchemaServiceClient.get_transport_class() - available_transports = [ - transports.SchemaServiceGrpcTransport, - transports.SchemaServiceRestTransport, - ] - assert transport in available_transports - - transport = SchemaServiceClient.get_transport_class("grpc") - assert transport == transports.SchemaServiceGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (SchemaServiceClient, transports.SchemaServiceGrpcTransport, "grpc"), - (SchemaServiceAsyncClient, transports.SchemaServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (SchemaServiceClient, transports.SchemaServiceRestTransport, "rest"), -]) -@mock.patch.object(SchemaServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(SchemaServiceClient)) -@mock.patch.object(SchemaServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(SchemaServiceAsyncClient)) -def test_schema_service_client_client_options(client_class, transport_class, transport_name): - # Check that if channel is provided we won't create a new one. - with mock.patch.object(SchemaServiceClient, '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(SchemaServiceClient, 'get_transport_class') as gtc: - client = client_class(transport=transport_name) - gtc.assert_called() - - # Check the case api_endpoint is provided. - options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name, client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_MTLS_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has - # unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError) as excinfo: - client = client_class(transport=transport_name) - assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" - - # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError) as excinfo: - client = client_class(transport=transport_name) - assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - - # Check the case quota_project_id is provided - options = client_options.ClientOptions(quota_project_id="octopus") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id="octopus", - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - # Check the case api_endpoint is provided - options = client_options.ClientOptions(api_audience="https://language.googleapis.com") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience="https://language.googleapis.com" - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ - (SchemaServiceClient, transports.SchemaServiceGrpcTransport, "grpc", "true"), - (SchemaServiceAsyncClient, transports.SchemaServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (SchemaServiceClient, transports.SchemaServiceGrpcTransport, "grpc", "false"), - (SchemaServiceAsyncClient, transports.SchemaServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), - (SchemaServiceClient, transports.SchemaServiceRestTransport, "rest", "true"), - (SchemaServiceClient, transports.SchemaServiceRestTransport, "rest", "false"), -]) -@mock.patch.object(SchemaServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(SchemaServiceClient)) -@mock.patch.object(SchemaServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(SchemaServiceAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_schema_service_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): - # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default - # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. - - # Check the case client_cert_source is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, 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", [ - SchemaServiceClient, SchemaServiceAsyncClient -]) -@mock.patch.object(SchemaServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SchemaServiceClient)) -@mock.patch.object(SchemaServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SchemaServiceAsyncClient)) -def test_schema_service_client_get_mtls_endpoint_and_cert_source(client_class): - mock_client_cert_source = mock.Mock() - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source == mock_client_cert_source - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - mock_client_cert_source = mock.Mock() - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source == mock_client_cert_source - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has - # unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError) as excinfo: - client_class.get_mtls_endpoint_and_cert_source() - - assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" - - # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError) as excinfo: - client_class.get_mtls_endpoint_and_cert_source() - - assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - -@pytest.mark.parametrize("client_class", [ - SchemaServiceClient, SchemaServiceAsyncClient -]) -@mock.patch.object(SchemaServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(SchemaServiceClient)) -@mock.patch.object(SchemaServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(SchemaServiceAsyncClient)) -def test_schema_service_client_client_api_endpoint(client_class): - mock_client_cert_source = client_cert_source_callback - api_override = "foo.com" - default_universe = SchemaServiceClient._DEFAULT_UNIVERSE - default_endpoint = SchemaServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) - mock_universe = "bar.com" - mock_endpoint = SchemaServiceClient._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", [ - (SchemaServiceClient, transports.SchemaServiceGrpcTransport, "grpc"), - (SchemaServiceAsyncClient, transports.SchemaServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (SchemaServiceClient, transports.SchemaServiceRestTransport, "rest"), -]) -def test_schema_service_client_client_options_scopes(client_class, transport_class, transport_name): - # Check the case scopes are provided. - options = client_options.ClientOptions( - scopes=["1", "2"], - ) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, 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", [ - (SchemaServiceClient, transports.SchemaServiceGrpcTransport, "grpc", grpc_helpers), - (SchemaServiceAsyncClient, transports.SchemaServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), - (SchemaServiceClient, transports.SchemaServiceRestTransport, "rest", None), -]) -def test_schema_service_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_schema_service_client_client_options_from_dict(): - with mock.patch('google.pubsub_v1.services.schema_service.transports.SchemaServiceGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = SchemaServiceClient( - 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", [ - (SchemaServiceClient, transports.SchemaServiceGrpcTransport, "grpc", grpc_helpers), - (SchemaServiceAsyncClient, transports.SchemaServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_schema_service_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( - "pubsub.googleapis.com:443", - credentials=file_creds, - credentials_file=None, - quota_project_id=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/pubsub', -), - scopes=None, - default_host="pubsub.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("request_type", [ - gp_schema.CreateSchemaRequest, - dict, -]) -def test_create_schema(request_type, transport: str = 'grpc'): - client = SchemaServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_schema), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gp_schema.Schema( - name='name_value', - type_=gp_schema.Schema.Type.PROTOCOL_BUFFER, - definition='definition_value', - revision_id='revision_id_value', - ) - response = client.create_schema(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = gp_schema.CreateSchemaRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, gp_schema.Schema) - assert response.name == 'name_value' - assert response.type_ == gp_schema.Schema.Type.PROTOCOL_BUFFER - assert response.definition == 'definition_value' - assert response.revision_id == 'revision_id_value' - - -def test_create_schema_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SchemaServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_schema), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.create_schema() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == gp_schema.CreateSchemaRequest() - - -def test_create_schema_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 = SchemaServiceClient( - 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 = gp_schema.CreateSchemaRequest( - parent='parent_value', - schema_id='schema_id_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_schema), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.create_schema(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == gp_schema.CreateSchemaRequest( - parent='parent_value', - schema_id='schema_id_value', - ) - -def test_create_schema_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = SchemaServiceClient( - 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_schema in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_schema] = mock_rpc - request = {} - client.create_schema(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.create_schema(request) - - # Establish that a new wrapper 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_schema_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SchemaServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_schema), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gp_schema.Schema( - name='name_value', - type_=gp_schema.Schema.Type.PROTOCOL_BUFFER, - definition='definition_value', - revision_id='revision_id_value', - )) - response = await client.create_schema() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == gp_schema.CreateSchemaRequest() - -@pytest.mark.asyncio -async def test_create_schema_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 = SchemaServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - 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_schema 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_schema] = mock_rpc - - request = {} - await client.create_schema(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.create_schema(request) - - # Establish that a new wrapper 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_schema_async(transport: str = 'grpc_asyncio', request_type=gp_schema.CreateSchemaRequest): - client = SchemaServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_schema), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gp_schema.Schema( - name='name_value', - type_=gp_schema.Schema.Type.PROTOCOL_BUFFER, - definition='definition_value', - revision_id='revision_id_value', - )) - response = await client.create_schema(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = gp_schema.CreateSchemaRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, gp_schema.Schema) - assert response.name == 'name_value' - assert response.type_ == gp_schema.Schema.Type.PROTOCOL_BUFFER - assert response.definition == 'definition_value' - assert response.revision_id == 'revision_id_value' - - -@pytest.mark.asyncio -async def test_create_schema_async_from_dict(): - await test_create_schema_async(request_type=dict) - - -def test_create_schema_field_headers(): - client = SchemaServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = gp_schema.CreateSchemaRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_schema), - '__call__') as call: - call.return_value = gp_schema.Schema() - client.create_schema(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header 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_schema_field_headers_async(): - client = SchemaServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = gp_schema.CreateSchemaRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_schema), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gp_schema.Schema()) - await client.create_schema(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish 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_schema_flattened(): - client = SchemaServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_schema), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gp_schema.Schema() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.create_schema( - parent='parent_value', - schema=gp_schema.Schema(name='name_value'), - schema_id='schema_id_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - arg = args[0].schema - mock_val = gp_schema.Schema(name='name_value') - assert arg == mock_val - arg = args[0].schema_id - mock_val = 'schema_id_value' - assert arg == mock_val - - -def test_create_schema_flattened_error(): - client = SchemaServiceClient( - credentials=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_schema( - gp_schema.CreateSchemaRequest(), - parent='parent_value', - schema=gp_schema.Schema(name='name_value'), - schema_id='schema_id_value', - ) - -@pytest.mark.asyncio -async def test_create_schema_flattened_async(): - client = SchemaServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_schema), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gp_schema.Schema() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gp_schema.Schema()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.create_schema( - parent='parent_value', - schema=gp_schema.Schema(name='name_value'), - schema_id='schema_id_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - arg = args[0].schema - mock_val = gp_schema.Schema(name='name_value') - assert arg == mock_val - arg = args[0].schema_id - mock_val = 'schema_id_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_create_schema_flattened_error_async(): - client = SchemaServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.create_schema( - gp_schema.CreateSchemaRequest(), - parent='parent_value', - schema=gp_schema.Schema(name='name_value'), - schema_id='schema_id_value', - ) - - -@pytest.mark.parametrize("request_type", [ - schema.GetSchemaRequest, - dict, -]) -def test_get_schema(request_type, transport: str = 'grpc'): - client = SchemaServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_schema), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = schema.Schema( - name='name_value', - type_=schema.Schema.Type.PROTOCOL_BUFFER, - definition='definition_value', - revision_id='revision_id_value', - ) - response = client.get_schema(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = schema.GetSchemaRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, schema.Schema) - assert response.name == 'name_value' - assert response.type_ == schema.Schema.Type.PROTOCOL_BUFFER - assert response.definition == 'definition_value' - assert response.revision_id == 'revision_id_value' - - -def test_get_schema_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SchemaServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_schema), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.get_schema() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == schema.GetSchemaRequest() - - -def test_get_schema_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 = SchemaServiceClient( - 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 = schema.GetSchemaRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_schema), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.get_schema(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == schema.GetSchemaRequest( - name='name_value', - ) - -def test_get_schema_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = SchemaServiceClient( - 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_schema in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_schema] = mock_rpc - request = {} - client.get_schema(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_schema(request) - - # Establish that a new wrapper 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_schema_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SchemaServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_schema), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(schema.Schema( - name='name_value', - type_=schema.Schema.Type.PROTOCOL_BUFFER, - definition='definition_value', - revision_id='revision_id_value', - )) - response = await client.get_schema() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == schema.GetSchemaRequest() - -@pytest.mark.asyncio -async def test_get_schema_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 = SchemaServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - 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_schema 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_schema] = mock_rpc - - request = {} - await client.get_schema(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.get_schema(request) - - # Establish that a new wrapper 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_schema_async(transport: str = 'grpc_asyncio', request_type=schema.GetSchemaRequest): - client = SchemaServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_schema), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(schema.Schema( - name='name_value', - type_=schema.Schema.Type.PROTOCOL_BUFFER, - definition='definition_value', - revision_id='revision_id_value', - )) - response = await client.get_schema(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = schema.GetSchemaRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, schema.Schema) - assert response.name == 'name_value' - assert response.type_ == schema.Schema.Type.PROTOCOL_BUFFER - assert response.definition == 'definition_value' - assert response.revision_id == 'revision_id_value' - - -@pytest.mark.asyncio -async def test_get_schema_async_from_dict(): - await test_get_schema_async(request_type=dict) - - -def test_get_schema_field_headers(): - client = SchemaServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = schema.GetSchemaRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_schema), - '__call__') as call: - call.return_value = schema.Schema() - client.get_schema(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header 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_schema_field_headers_async(): - client = SchemaServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = schema.GetSchemaRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_schema), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(schema.Schema()) - await client.get_schema(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish 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_schema_flattened(): - client = SchemaServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_schema), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = schema.Schema() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_schema( - name='name_value', - ) - - # 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_schema_flattened_error(): - client = SchemaServiceClient( - credentials=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_schema( - schema.GetSchemaRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_get_schema_flattened_async(): - client = SchemaServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_schema), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = schema.Schema() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(schema.Schema()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_schema( - name='name_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_schema_flattened_error_async(): - client = SchemaServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.get_schema( - schema.GetSchemaRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - schema.ListSchemasRequest, - dict, -]) -def test_list_schemas(request_type, transport: str = 'grpc'): - client = SchemaServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_schemas), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = schema.ListSchemasResponse( - next_page_token='next_page_token_value', - ) - response = client.list_schemas(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = schema.ListSchemasRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListSchemasPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_schemas_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SchemaServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_schemas), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.list_schemas() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == schema.ListSchemasRequest() - - -def test_list_schemas_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 = SchemaServiceClient( - 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 = schema.ListSchemasRequest( - 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_schemas), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.list_schemas(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == schema.ListSchemasRequest( - parent='parent_value', - page_token='page_token_value', - ) - -def test_list_schemas_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = SchemaServiceClient( - 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_schemas in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_schemas] = mock_rpc - request = {} - client.list_schemas(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_schemas(request) - - # Establish that a new wrapper 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_schemas_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SchemaServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_schemas), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(schema.ListSchemasResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_schemas() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == schema.ListSchemasRequest() - -@pytest.mark.asyncio -async def test_list_schemas_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 = SchemaServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - 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_schemas 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_schemas] = mock_rpc - - request = {} - await client.list_schemas(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.list_schemas(request) - - # Establish that a new wrapper 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_schemas_async(transport: str = 'grpc_asyncio', request_type=schema.ListSchemasRequest): - client = SchemaServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_schemas), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(schema.ListSchemasResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_schemas(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = schema.ListSchemasRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListSchemasAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_schemas_async_from_dict(): - await test_list_schemas_async(request_type=dict) - - -def test_list_schemas_field_headers(): - client = SchemaServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = schema.ListSchemasRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_schemas), - '__call__') as call: - call.return_value = schema.ListSchemasResponse() - client.list_schemas(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header 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_schemas_field_headers_async(): - client = SchemaServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = schema.ListSchemasRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_schemas), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(schema.ListSchemasResponse()) - await client.list_schemas(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish 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_schemas_flattened(): - client = SchemaServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_schemas), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = schema.ListSchemasResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_schemas( - 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_schemas_flattened_error(): - client = SchemaServiceClient( - credentials=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_schemas( - schema.ListSchemasRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_list_schemas_flattened_async(): - client = SchemaServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_schemas), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = schema.ListSchemasResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(schema.ListSchemasResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_schemas( - 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_schemas_flattened_error_async(): - client = SchemaServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.list_schemas( - schema.ListSchemasRequest(), - parent='parent_value', - ) - - -def test_list_schemas_pager(transport_name: str = "grpc"): - client = SchemaServiceClient( - 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_schemas), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - schema.ListSchemasResponse( - schemas=[ - schema.Schema(), - schema.Schema(), - schema.Schema(), - ], - next_page_token='abc', - ), - schema.ListSchemasResponse( - schemas=[], - next_page_token='def', - ), - schema.ListSchemasResponse( - schemas=[ - schema.Schema(), - ], - next_page_token='ghi', - ), - schema.ListSchemasResponse( - schemas=[ - schema.Schema(), - schema.Schema(), - ], - ), - RuntimeError, - ) - - expected_metadata = () - retry = retries.Retry() - timeout = 5 - expected_metadata = tuple(expected_metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_schemas(request={}, retry=retry, timeout=timeout) - - assert pager._metadata == expected_metadata - assert pager._retry == retry - assert pager._timeout == timeout - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, schema.Schema) - for i in results) -def test_list_schemas_pages(transport_name: str = "grpc"): - client = SchemaServiceClient( - 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_schemas), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - schema.ListSchemasResponse( - schemas=[ - schema.Schema(), - schema.Schema(), - schema.Schema(), - ], - next_page_token='abc', - ), - schema.ListSchemasResponse( - schemas=[], - next_page_token='def', - ), - schema.ListSchemasResponse( - schemas=[ - schema.Schema(), - ], - next_page_token='ghi', - ), - schema.ListSchemasResponse( - schemas=[ - schema.Schema(), - schema.Schema(), - ], - ), - RuntimeError, - ) - pages = list(client.list_schemas(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_schemas_async_pager(): - client = SchemaServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_schemas), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - schema.ListSchemasResponse( - schemas=[ - schema.Schema(), - schema.Schema(), - schema.Schema(), - ], - next_page_token='abc', - ), - schema.ListSchemasResponse( - schemas=[], - next_page_token='def', - ), - schema.ListSchemasResponse( - schemas=[ - schema.Schema(), - ], - next_page_token='ghi', - ), - schema.ListSchemasResponse( - schemas=[ - schema.Schema(), - schema.Schema(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_schemas(request={},) - assert async_pager.next_page_token == 'abc' - responses = [] - async for response in async_pager: # pragma: no branch - responses.append(response) - - assert len(responses) == 6 - assert all(isinstance(i, schema.Schema) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_schemas_async_pages(): - client = SchemaServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_schemas), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - schema.ListSchemasResponse( - schemas=[ - schema.Schema(), - schema.Schema(), - schema.Schema(), - ], - next_page_token='abc', - ), - schema.ListSchemasResponse( - schemas=[], - next_page_token='def', - ), - schema.ListSchemasResponse( - schemas=[ - schema.Schema(), - ], - next_page_token='ghi', - ), - schema.ListSchemasResponse( - schemas=[ - schema.Schema(), - schema.Schema(), - ], - ), - RuntimeError, - ) - pages = [] - # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` - # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 - async for page_ in ( # pragma: no branch - await client.list_schemas(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", [ - schema.ListSchemaRevisionsRequest, - dict, -]) -def test_list_schema_revisions(request_type, transport: str = 'grpc'): - client = SchemaServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_schema_revisions), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = schema.ListSchemaRevisionsResponse( - next_page_token='next_page_token_value', - ) - response = client.list_schema_revisions(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = schema.ListSchemaRevisionsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListSchemaRevisionsPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_schema_revisions_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SchemaServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_schema_revisions), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.list_schema_revisions() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == schema.ListSchemaRevisionsRequest() - - -def test_list_schema_revisions_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 = SchemaServiceClient( - 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 = schema.ListSchemaRevisionsRequest( - name='name_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_schema_revisions), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.list_schema_revisions(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == schema.ListSchemaRevisionsRequest( - name='name_value', - page_token='page_token_value', - ) - -def test_list_schema_revisions_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = SchemaServiceClient( - 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_schema_revisions in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_schema_revisions] = mock_rpc - request = {} - client.list_schema_revisions(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_schema_revisions(request) - - # Establish that a new wrapper 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_schema_revisions_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SchemaServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_schema_revisions), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(schema.ListSchemaRevisionsResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_schema_revisions() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == schema.ListSchemaRevisionsRequest() - -@pytest.mark.asyncio -async def test_list_schema_revisions_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 = SchemaServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - 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_schema_revisions 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_schema_revisions] = mock_rpc - - request = {} - await client.list_schema_revisions(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.list_schema_revisions(request) - - # Establish that a new wrapper 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_schema_revisions_async(transport: str = 'grpc_asyncio', request_type=schema.ListSchemaRevisionsRequest): - client = SchemaServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_schema_revisions), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(schema.ListSchemaRevisionsResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_schema_revisions(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = schema.ListSchemaRevisionsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListSchemaRevisionsAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_schema_revisions_async_from_dict(): - await test_list_schema_revisions_async(request_type=dict) - - -def test_list_schema_revisions_field_headers(): - client = SchemaServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = schema.ListSchemaRevisionsRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_schema_revisions), - '__call__') as call: - call.return_value = schema.ListSchemaRevisionsResponse() - client.list_schema_revisions(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_list_schema_revisions_field_headers_async(): - client = SchemaServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = schema.ListSchemaRevisionsRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_schema_revisions), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(schema.ListSchemaRevisionsResponse()) - await client.list_schema_revisions(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name_value', - ) in kw['metadata'] - - -def test_list_schema_revisions_flattened(): - client = SchemaServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_schema_revisions), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = schema.ListSchemaRevisionsResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_schema_revisions( - name='name_value', - ) - - # 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_list_schema_revisions_flattened_error(): - client = SchemaServiceClient( - credentials=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_schema_revisions( - schema.ListSchemaRevisionsRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_list_schema_revisions_flattened_async(): - client = SchemaServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_schema_revisions), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = schema.ListSchemaRevisionsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(schema.ListSchemaRevisionsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_schema_revisions( - name='name_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_list_schema_revisions_flattened_error_async(): - client = SchemaServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.list_schema_revisions( - schema.ListSchemaRevisionsRequest(), - name='name_value', - ) - - -def test_list_schema_revisions_pager(transport_name: str = "grpc"): - client = SchemaServiceClient( - 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_schema_revisions), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - schema.ListSchemaRevisionsResponse( - schemas=[ - schema.Schema(), - schema.Schema(), - schema.Schema(), - ], - next_page_token='abc', - ), - schema.ListSchemaRevisionsResponse( - schemas=[], - next_page_token='def', - ), - schema.ListSchemaRevisionsResponse( - schemas=[ - schema.Schema(), - ], - next_page_token='ghi', - ), - schema.ListSchemaRevisionsResponse( - schemas=[ - schema.Schema(), - schema.Schema(), - ], - ), - RuntimeError, - ) - - expected_metadata = () - retry = retries.Retry() - timeout = 5 - expected_metadata = tuple(expected_metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('name', ''), - )), - ) - pager = client.list_schema_revisions(request={}, retry=retry, timeout=timeout) - - assert pager._metadata == expected_metadata - assert pager._retry == retry - assert pager._timeout == timeout - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, schema.Schema) - for i in results) -def test_list_schema_revisions_pages(transport_name: str = "grpc"): - client = SchemaServiceClient( - 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_schema_revisions), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - schema.ListSchemaRevisionsResponse( - schemas=[ - schema.Schema(), - schema.Schema(), - schema.Schema(), - ], - next_page_token='abc', - ), - schema.ListSchemaRevisionsResponse( - schemas=[], - next_page_token='def', - ), - schema.ListSchemaRevisionsResponse( - schemas=[ - schema.Schema(), - ], - next_page_token='ghi', - ), - schema.ListSchemaRevisionsResponse( - schemas=[ - schema.Schema(), - schema.Schema(), - ], - ), - RuntimeError, - ) - pages = list(client.list_schema_revisions(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_schema_revisions_async_pager(): - client = SchemaServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_schema_revisions), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - schema.ListSchemaRevisionsResponse( - schemas=[ - schema.Schema(), - schema.Schema(), - schema.Schema(), - ], - next_page_token='abc', - ), - schema.ListSchemaRevisionsResponse( - schemas=[], - next_page_token='def', - ), - schema.ListSchemaRevisionsResponse( - schemas=[ - schema.Schema(), - ], - next_page_token='ghi', - ), - schema.ListSchemaRevisionsResponse( - schemas=[ - schema.Schema(), - schema.Schema(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_schema_revisions(request={},) - assert async_pager.next_page_token == 'abc' - responses = [] - async for response in async_pager: # pragma: no branch - responses.append(response) - - assert len(responses) == 6 - assert all(isinstance(i, schema.Schema) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_schema_revisions_async_pages(): - client = SchemaServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_schema_revisions), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - schema.ListSchemaRevisionsResponse( - schemas=[ - schema.Schema(), - schema.Schema(), - schema.Schema(), - ], - next_page_token='abc', - ), - schema.ListSchemaRevisionsResponse( - schemas=[], - next_page_token='def', - ), - schema.ListSchemaRevisionsResponse( - schemas=[ - schema.Schema(), - ], - next_page_token='ghi', - ), - schema.ListSchemaRevisionsResponse( - schemas=[ - schema.Schema(), - schema.Schema(), - ], - ), - RuntimeError, - ) - pages = [] - # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` - # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 - async for page_ in ( # pragma: no branch - await client.list_schema_revisions(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", [ - gp_schema.CommitSchemaRequest, - dict, -]) -def test_commit_schema(request_type, transport: str = 'grpc'): - client = SchemaServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.commit_schema), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gp_schema.Schema( - name='name_value', - type_=gp_schema.Schema.Type.PROTOCOL_BUFFER, - definition='definition_value', - revision_id='revision_id_value', - ) - response = client.commit_schema(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = gp_schema.CommitSchemaRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, gp_schema.Schema) - assert response.name == 'name_value' - assert response.type_ == gp_schema.Schema.Type.PROTOCOL_BUFFER - assert response.definition == 'definition_value' - assert response.revision_id == 'revision_id_value' - - -def test_commit_schema_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SchemaServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.commit_schema), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.commit_schema() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == gp_schema.CommitSchemaRequest() - - -def test_commit_schema_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 = SchemaServiceClient( - 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 = gp_schema.CommitSchemaRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.commit_schema), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.commit_schema(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == gp_schema.CommitSchemaRequest( - name='name_value', - ) - -def test_commit_schema_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = SchemaServiceClient( - 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.commit_schema in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.commit_schema] = mock_rpc - request = {} - client.commit_schema(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.commit_schema(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_commit_schema_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SchemaServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.commit_schema), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gp_schema.Schema( - name='name_value', - type_=gp_schema.Schema.Type.PROTOCOL_BUFFER, - definition='definition_value', - revision_id='revision_id_value', - )) - response = await client.commit_schema() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == gp_schema.CommitSchemaRequest() - -@pytest.mark.asyncio -async def test_commit_schema_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 = SchemaServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - 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.commit_schema 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.commit_schema] = mock_rpc - - request = {} - await client.commit_schema(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.commit_schema(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_commit_schema_async(transport: str = 'grpc_asyncio', request_type=gp_schema.CommitSchemaRequest): - client = SchemaServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.commit_schema), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gp_schema.Schema( - name='name_value', - type_=gp_schema.Schema.Type.PROTOCOL_BUFFER, - definition='definition_value', - revision_id='revision_id_value', - )) - response = await client.commit_schema(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = gp_schema.CommitSchemaRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, gp_schema.Schema) - assert response.name == 'name_value' - assert response.type_ == gp_schema.Schema.Type.PROTOCOL_BUFFER - assert response.definition == 'definition_value' - assert response.revision_id == 'revision_id_value' - - -@pytest.mark.asyncio -async def test_commit_schema_async_from_dict(): - await test_commit_schema_async(request_type=dict) - - -def test_commit_schema_field_headers(): - client = SchemaServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = gp_schema.CommitSchemaRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.commit_schema), - '__call__') as call: - call.return_value = gp_schema.Schema() - client.commit_schema(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_commit_schema_field_headers_async(): - client = SchemaServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = gp_schema.CommitSchemaRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.commit_schema), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gp_schema.Schema()) - await client.commit_schema(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name_value', - ) in kw['metadata'] - - -def test_commit_schema_flattened(): - client = SchemaServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.commit_schema), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gp_schema.Schema() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.commit_schema( - name='name_value', - schema=gp_schema.Schema(name='name_value'), - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - arg = args[0].schema - mock_val = gp_schema.Schema(name='name_value') - assert arg == mock_val - - -def test_commit_schema_flattened_error(): - client = SchemaServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.commit_schema( - gp_schema.CommitSchemaRequest(), - name='name_value', - schema=gp_schema.Schema(name='name_value'), - ) - -@pytest.mark.asyncio -async def test_commit_schema_flattened_async(): - client = SchemaServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.commit_schema), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gp_schema.Schema() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gp_schema.Schema()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.commit_schema( - name='name_value', - schema=gp_schema.Schema(name='name_value'), - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - arg = args[0].schema - mock_val = gp_schema.Schema(name='name_value') - assert arg == mock_val - -@pytest.mark.asyncio -async def test_commit_schema_flattened_error_async(): - client = SchemaServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.commit_schema( - gp_schema.CommitSchemaRequest(), - name='name_value', - schema=gp_schema.Schema(name='name_value'), - ) - - -@pytest.mark.parametrize("request_type", [ - schema.RollbackSchemaRequest, - dict, -]) -def test_rollback_schema(request_type, transport: str = 'grpc'): - client = SchemaServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.rollback_schema), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = schema.Schema( - name='name_value', - type_=schema.Schema.Type.PROTOCOL_BUFFER, - definition='definition_value', - revision_id='revision_id_value', - ) - response = client.rollback_schema(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = schema.RollbackSchemaRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, schema.Schema) - assert response.name == 'name_value' - assert response.type_ == schema.Schema.Type.PROTOCOL_BUFFER - assert response.definition == 'definition_value' - assert response.revision_id == 'revision_id_value' - - -def test_rollback_schema_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SchemaServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.rollback_schema), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.rollback_schema() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == schema.RollbackSchemaRequest() - - -def test_rollback_schema_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 = SchemaServiceClient( - 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 = schema.RollbackSchemaRequest( - name='name_value', - revision_id='revision_id_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.rollback_schema), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.rollback_schema(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == schema.RollbackSchemaRequest( - name='name_value', - revision_id='revision_id_value', - ) - -def test_rollback_schema_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = SchemaServiceClient( - 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.rollback_schema in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.rollback_schema] = mock_rpc - request = {} - client.rollback_schema(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.rollback_schema(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_rollback_schema_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SchemaServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.rollback_schema), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(schema.Schema( - name='name_value', - type_=schema.Schema.Type.PROTOCOL_BUFFER, - definition='definition_value', - revision_id='revision_id_value', - )) - response = await client.rollback_schema() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == schema.RollbackSchemaRequest() - -@pytest.mark.asyncio -async def test_rollback_schema_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 = SchemaServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - 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.rollback_schema 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.rollback_schema] = mock_rpc - - request = {} - await client.rollback_schema(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.rollback_schema(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_rollback_schema_async(transport: str = 'grpc_asyncio', request_type=schema.RollbackSchemaRequest): - client = SchemaServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.rollback_schema), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(schema.Schema( - name='name_value', - type_=schema.Schema.Type.PROTOCOL_BUFFER, - definition='definition_value', - revision_id='revision_id_value', - )) - response = await client.rollback_schema(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = schema.RollbackSchemaRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, schema.Schema) - assert response.name == 'name_value' - assert response.type_ == schema.Schema.Type.PROTOCOL_BUFFER - assert response.definition == 'definition_value' - assert response.revision_id == 'revision_id_value' - - -@pytest.mark.asyncio -async def test_rollback_schema_async_from_dict(): - await test_rollback_schema_async(request_type=dict) - - -def test_rollback_schema_field_headers(): - client = SchemaServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = schema.RollbackSchemaRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.rollback_schema), - '__call__') as call: - call.return_value = schema.Schema() - client.rollback_schema(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_rollback_schema_field_headers_async(): - client = SchemaServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = schema.RollbackSchemaRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.rollback_schema), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(schema.Schema()) - await client.rollback_schema(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name_value', - ) in kw['metadata'] - - -def test_rollback_schema_flattened(): - client = SchemaServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.rollback_schema), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = schema.Schema() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.rollback_schema( - name='name_value', - revision_id='revision_id_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - arg = args[0].revision_id - mock_val = 'revision_id_value' - assert arg == mock_val - - -def test_rollback_schema_flattened_error(): - client = SchemaServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.rollback_schema( - schema.RollbackSchemaRequest(), - name='name_value', - revision_id='revision_id_value', - ) - -@pytest.mark.asyncio -async def test_rollback_schema_flattened_async(): - client = SchemaServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.rollback_schema), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = schema.Schema() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(schema.Schema()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.rollback_schema( - name='name_value', - revision_id='revision_id_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - arg = args[0].revision_id - mock_val = 'revision_id_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_rollback_schema_flattened_error_async(): - client = SchemaServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.rollback_schema( - schema.RollbackSchemaRequest(), - name='name_value', - revision_id='revision_id_value', - ) - - -@pytest.mark.parametrize("request_type", [ - schema.DeleteSchemaRevisionRequest, - dict, -]) -def test_delete_schema_revision(request_type, transport: str = 'grpc'): - client = SchemaServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_schema_revision), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = schema.Schema( - name='name_value', - type_=schema.Schema.Type.PROTOCOL_BUFFER, - definition='definition_value', - revision_id='revision_id_value', - ) - response = client.delete_schema_revision(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = schema.DeleteSchemaRevisionRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, schema.Schema) - assert response.name == 'name_value' - assert response.type_ == schema.Schema.Type.PROTOCOL_BUFFER - assert response.definition == 'definition_value' - assert response.revision_id == 'revision_id_value' - - -def test_delete_schema_revision_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SchemaServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_schema_revision), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.delete_schema_revision() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == schema.DeleteSchemaRevisionRequest() - - -def test_delete_schema_revision_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 = SchemaServiceClient( - 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 = schema.DeleteSchemaRevisionRequest( - name='name_value', - revision_id='revision_id_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_schema_revision), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.delete_schema_revision(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == schema.DeleteSchemaRevisionRequest( - name='name_value', - revision_id='revision_id_value', - ) - -def test_delete_schema_revision_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = SchemaServiceClient( - 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_schema_revision in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_schema_revision] = mock_rpc - request = {} - client.delete_schema_revision(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.delete_schema_revision(request) - - # Establish that a new wrapper 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_schema_revision_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SchemaServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_schema_revision), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(schema.Schema( - name='name_value', - type_=schema.Schema.Type.PROTOCOL_BUFFER, - definition='definition_value', - revision_id='revision_id_value', - )) - response = await client.delete_schema_revision() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == schema.DeleteSchemaRevisionRequest() - -@pytest.mark.asyncio -async def test_delete_schema_revision_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 = SchemaServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - 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_schema_revision 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_schema_revision] = mock_rpc - - request = {} - await client.delete_schema_revision(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.delete_schema_revision(request) - - # Establish that a new wrapper 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_schema_revision_async(transport: str = 'grpc_asyncio', request_type=schema.DeleteSchemaRevisionRequest): - client = SchemaServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_schema_revision), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(schema.Schema( - name='name_value', - type_=schema.Schema.Type.PROTOCOL_BUFFER, - definition='definition_value', - revision_id='revision_id_value', - )) - response = await client.delete_schema_revision(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = schema.DeleteSchemaRevisionRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, schema.Schema) - assert response.name == 'name_value' - assert response.type_ == schema.Schema.Type.PROTOCOL_BUFFER - assert response.definition == 'definition_value' - assert response.revision_id == 'revision_id_value' - - -@pytest.mark.asyncio -async def test_delete_schema_revision_async_from_dict(): - await test_delete_schema_revision_async(request_type=dict) - - -def test_delete_schema_revision_field_headers(): - client = SchemaServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = schema.DeleteSchemaRevisionRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_schema_revision), - '__call__') as call: - call.return_value = schema.Schema() - client.delete_schema_revision(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header 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_schema_revision_field_headers_async(): - client = SchemaServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = schema.DeleteSchemaRevisionRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_schema_revision), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(schema.Schema()) - await client.delete_schema_revision(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish 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_schema_revision_flattened(): - client = SchemaServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_schema_revision), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = schema.Schema() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.delete_schema_revision( - name='name_value', - revision_id='revision_id_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - arg = args[0].revision_id - mock_val = 'revision_id_value' - assert arg == mock_val - - -def test_delete_schema_revision_flattened_error(): - client = SchemaServiceClient( - credentials=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_schema_revision( - schema.DeleteSchemaRevisionRequest(), - name='name_value', - revision_id='revision_id_value', - ) - -@pytest.mark.asyncio -async def test_delete_schema_revision_flattened_async(): - client = SchemaServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_schema_revision), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = schema.Schema() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(schema.Schema()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.delete_schema_revision( - name='name_value', - revision_id='revision_id_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - arg = args[0].revision_id - mock_val = 'revision_id_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_delete_schema_revision_flattened_error_async(): - client = SchemaServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.delete_schema_revision( - schema.DeleteSchemaRevisionRequest(), - name='name_value', - revision_id='revision_id_value', - ) - - -@pytest.mark.parametrize("request_type", [ - schema.DeleteSchemaRequest, - dict, -]) -def test_delete_schema(request_type, transport: str = 'grpc'): - client = SchemaServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_schema), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = None - response = client.delete_schema(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = schema.DeleteSchemaRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert response is None - - -def test_delete_schema_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SchemaServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_schema), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.delete_schema() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == schema.DeleteSchemaRequest() - - -def test_delete_schema_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 = SchemaServiceClient( - 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 = schema.DeleteSchemaRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_schema), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.delete_schema(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == schema.DeleteSchemaRequest( - name='name_value', - ) - -def test_delete_schema_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = SchemaServiceClient( - 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_schema in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_schema] = mock_rpc - request = {} - client.delete_schema(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.delete_schema(request) - - # Establish that a new wrapper 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_schema_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SchemaServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_schema), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_schema() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == schema.DeleteSchemaRequest() - -@pytest.mark.asyncio -async def test_delete_schema_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 = SchemaServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - 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_schema 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_schema] = mock_rpc - - request = {} - await client.delete_schema(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.delete_schema(request) - - # Establish that a new wrapper 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_schema_async(transport: str = 'grpc_asyncio', request_type=schema.DeleteSchemaRequest): - client = SchemaServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_schema), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_schema(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = schema.DeleteSchemaRequest() - 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_schema_async_from_dict(): - await test_delete_schema_async(request_type=dict) - - -def test_delete_schema_field_headers(): - client = SchemaServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = schema.DeleteSchemaRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_schema), - '__call__') as call: - call.return_value = None - client.delete_schema(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header 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_schema_field_headers_async(): - client = SchemaServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = schema.DeleteSchemaRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_schema), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_schema(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish 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_schema_flattened(): - client = SchemaServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_schema), - '__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_schema( - name='name_value', - ) - - # 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_schema_flattened_error(): - client = SchemaServiceClient( - credentials=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_schema( - schema.DeleteSchemaRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_delete_schema_flattened_async(): - client = SchemaServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_schema), - '__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_schema( - name='name_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_schema_flattened_error_async(): - client = SchemaServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.delete_schema( - schema.DeleteSchemaRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - gp_schema.ValidateSchemaRequest, - dict, -]) -def test_validate_schema(request_type, transport: str = 'grpc'): - client = SchemaServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.validate_schema), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gp_schema.ValidateSchemaResponse( - ) - response = client.validate_schema(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = gp_schema.ValidateSchemaRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, gp_schema.ValidateSchemaResponse) - - -def test_validate_schema_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SchemaServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.validate_schema), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.validate_schema() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == gp_schema.ValidateSchemaRequest() - - -def test_validate_schema_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 = SchemaServiceClient( - 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 = gp_schema.ValidateSchemaRequest( - parent='parent_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.validate_schema), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.validate_schema(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == gp_schema.ValidateSchemaRequest( - parent='parent_value', - ) - -def test_validate_schema_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = SchemaServiceClient( - 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.validate_schema in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.validate_schema] = mock_rpc - request = {} - client.validate_schema(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.validate_schema(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_validate_schema_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SchemaServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.validate_schema), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gp_schema.ValidateSchemaResponse( - )) - response = await client.validate_schema() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == gp_schema.ValidateSchemaRequest() - -@pytest.mark.asyncio -async def test_validate_schema_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 = SchemaServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - 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.validate_schema 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.validate_schema] = mock_rpc - - request = {} - await client.validate_schema(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.validate_schema(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_validate_schema_async(transport: str = 'grpc_asyncio', request_type=gp_schema.ValidateSchemaRequest): - client = SchemaServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.validate_schema), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gp_schema.ValidateSchemaResponse( - )) - response = await client.validate_schema(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = gp_schema.ValidateSchemaRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, gp_schema.ValidateSchemaResponse) - - -@pytest.mark.asyncio -async def test_validate_schema_async_from_dict(): - await test_validate_schema_async(request_type=dict) - - -def test_validate_schema_field_headers(): - client = SchemaServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = gp_schema.ValidateSchemaRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.validate_schema), - '__call__') as call: - call.return_value = gp_schema.ValidateSchemaResponse() - client.validate_schema(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_validate_schema_field_headers_async(): - client = SchemaServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = gp_schema.ValidateSchemaRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.validate_schema), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gp_schema.ValidateSchemaResponse()) - await client.validate_schema(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -def test_validate_schema_flattened(): - client = SchemaServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.validate_schema), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gp_schema.ValidateSchemaResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.validate_schema( - parent='parent_value', - schema=gp_schema.Schema(name='name_value'), - ) - - # 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].schema - mock_val = gp_schema.Schema(name='name_value') - assert arg == mock_val - - -def test_validate_schema_flattened_error(): - client = SchemaServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.validate_schema( - gp_schema.ValidateSchemaRequest(), - parent='parent_value', - schema=gp_schema.Schema(name='name_value'), - ) - -@pytest.mark.asyncio -async def test_validate_schema_flattened_async(): - client = SchemaServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.validate_schema), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gp_schema.ValidateSchemaResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gp_schema.ValidateSchemaResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.validate_schema( - parent='parent_value', - schema=gp_schema.Schema(name='name_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].schema - mock_val = gp_schema.Schema(name='name_value') - assert arg == mock_val - -@pytest.mark.asyncio -async def test_validate_schema_flattened_error_async(): - client = SchemaServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.validate_schema( - gp_schema.ValidateSchemaRequest(), - parent='parent_value', - schema=gp_schema.Schema(name='name_value'), - ) - - -@pytest.mark.parametrize("request_type", [ - schema.ValidateMessageRequest, - dict, -]) -def test_validate_message(request_type, transport: str = 'grpc'): - client = SchemaServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.validate_message), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = schema.ValidateMessageResponse( - ) - response = client.validate_message(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = schema.ValidateMessageRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, schema.ValidateMessageResponse) - - -def test_validate_message_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SchemaServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.validate_message), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.validate_message() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == schema.ValidateMessageRequest() - - -def test_validate_message_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 = SchemaServiceClient( - 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 = schema.ValidateMessageRequest( - parent='parent_value', - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.validate_message), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.validate_message(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == schema.ValidateMessageRequest( - parent='parent_value', - name='name_value', - ) - -def test_validate_message_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = SchemaServiceClient( - 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.validate_message in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.validate_message] = mock_rpc - request = {} - client.validate_message(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.validate_message(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_validate_message_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SchemaServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.validate_message), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(schema.ValidateMessageResponse( - )) - response = await client.validate_message() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == schema.ValidateMessageRequest() - -@pytest.mark.asyncio -async def test_validate_message_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 = SchemaServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - 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.validate_message 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.validate_message] = mock_rpc - - request = {} - await client.validate_message(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.validate_message(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_validate_message_async(transport: str = 'grpc_asyncio', request_type=schema.ValidateMessageRequest): - client = SchemaServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.validate_message), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(schema.ValidateMessageResponse( - )) - response = await client.validate_message(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = schema.ValidateMessageRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, schema.ValidateMessageResponse) - - -@pytest.mark.asyncio -async def test_validate_message_async_from_dict(): - await test_validate_message_async(request_type=dict) - - -def test_validate_message_field_headers(): - client = SchemaServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = schema.ValidateMessageRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.validate_message), - '__call__') as call: - call.return_value = schema.ValidateMessageResponse() - client.validate_message(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_validate_message_field_headers_async(): - client = SchemaServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = schema.ValidateMessageRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.validate_message), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(schema.ValidateMessageResponse()) - await client.validate_message(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -@pytest.mark.parametrize("request_type", [ - gp_schema.CreateSchemaRequest, - dict, -]) -def test_create_schema_rest(request_type): - client = SchemaServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1'} - request_init["schema"] = {'name': 'name_value', 'type_': 1, 'definition': 'definition_value', 'revision_id': 'revision_id_value', 'revision_create_time': {'seconds': 751, 'nanos': 543}} - # 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 = gp_schema.CreateSchemaRequest.meta.fields["schema"] - - 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["schema"].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["schema"][field])): - del request_init["schema"][field][i][subfield] - else: - del request_init["schema"][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 = gp_schema.Schema( - name='name_value', - type_=gp_schema.Schema.Type.PROTOCOL_BUFFER, - definition='definition_value', - revision_id='revision_id_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = gp_schema.Schema.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.create_schema(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, gp_schema.Schema) - assert response.name == 'name_value' - assert response.type_ == gp_schema.Schema.Type.PROTOCOL_BUFFER - assert response.definition == 'definition_value' - assert response.revision_id == 'revision_id_value' - -def test_create_schema_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 = SchemaServiceClient( - 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_schema in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_schema] = mock_rpc - - request = {} - client.create_schema(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.create_schema(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_schema_rest_required_fields(request_type=gp_schema.CreateSchemaRequest): - transport_class = transports.SchemaServiceRestTransport - - 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_schema._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_schema._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("schema_id", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - - client = SchemaServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = gp_schema.Schema() - # 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 = gp_schema.Schema.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.create_schema(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_create_schema_rest_unset_required_fields(): - transport = transports.SchemaServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.create_schema._get_unset_required_fields({}) - assert set(unset_fields) == (set(("schemaId", )) & set(("parent", "schema", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_create_schema_rest_interceptors(null_interceptor): - transport = transports.SchemaServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SchemaServiceRestInterceptor(), - ) - client = SchemaServiceClient(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.SchemaServiceRestInterceptor, "post_create_schema") as post, \ - mock.patch.object(transports.SchemaServiceRestInterceptor, "pre_create_schema") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = gp_schema.CreateSchemaRequest.pb(gp_schema.CreateSchemaRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = gp_schema.Schema.to_json(gp_schema.Schema()) - - request = gp_schema.CreateSchemaRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = gp_schema.Schema() - - client.create_schema(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_create_schema_rest_bad_request(transport: str = 'rest', request_type=gp_schema.CreateSchemaRequest): - client = SchemaServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/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 = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.create_schema(request) - - -def test_create_schema_rest_flattened(): - client = SchemaServiceClient( - 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 = gp_schema.Schema() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'projects/sample1'} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - schema=gp_schema.Schema(name='name_value'), - schema_id='schema_id_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 = gp_schema.Schema.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.create_schema(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1/{parent=projects/*}/schemas" % client.transport._host, args[1]) - - -def test_create_schema_rest_flattened_error(transport: str = 'rest'): - client = SchemaServiceClient( - 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_schema( - gp_schema.CreateSchemaRequest(), - parent='parent_value', - schema=gp_schema.Schema(name='name_value'), - schema_id='schema_id_value', - ) - - -def test_create_schema_rest_error(): - client = SchemaServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - schema.GetSchemaRequest, - dict, -]) -def test_get_schema_rest(request_type): - client = SchemaServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/schemas/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 = schema.Schema( - name='name_value', - type_=schema.Schema.Type.PROTOCOL_BUFFER, - definition='definition_value', - revision_id='revision_id_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = schema.Schema.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.get_schema(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, schema.Schema) - assert response.name == 'name_value' - assert response.type_ == schema.Schema.Type.PROTOCOL_BUFFER - assert response.definition == 'definition_value' - assert response.revision_id == 'revision_id_value' - -def test_get_schema_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 = SchemaServiceClient( - 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_schema in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_schema] = mock_rpc - - request = {} - client.get_schema(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_schema(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_schema_rest_required_fields(request_type=schema.GetSchemaRequest): - transport_class = transports.SchemaServiceRestTransport - - 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_schema._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_schema._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("view", )) - 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 = SchemaServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = schema.Schema() - # 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 = schema.Schema.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.get_schema(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_get_schema_rest_unset_required_fields(): - transport = transports.SchemaServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.get_schema._get_unset_required_fields({}) - assert set(unset_fields) == (set(("view", )) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_schema_rest_interceptors(null_interceptor): - transport = transports.SchemaServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SchemaServiceRestInterceptor(), - ) - client = SchemaServiceClient(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.SchemaServiceRestInterceptor, "post_get_schema") as post, \ - mock.patch.object(transports.SchemaServiceRestInterceptor, "pre_get_schema") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = schema.GetSchemaRequest.pb(schema.GetSchemaRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = schema.Schema.to_json(schema.Schema()) - - request = schema.GetSchemaRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = schema.Schema() - - client.get_schema(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_schema_rest_bad_request(transport: str = 'rest', request_type=schema.GetSchemaRequest): - client = SchemaServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/schemas/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 = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_schema(request) - - -def test_get_schema_rest_flattened(): - client = SchemaServiceClient( - 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 = schema.Schema() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/schemas/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 = schema.Schema.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.get_schema(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1/{name=projects/*/schemas/*}" % client.transport._host, args[1]) - - -def test_get_schema_rest_flattened_error(transport: str = 'rest'): - client = SchemaServiceClient( - 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_schema( - schema.GetSchemaRequest(), - name='name_value', - ) - - -def test_get_schema_rest_error(): - client = SchemaServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - schema.ListSchemasRequest, - dict, -]) -def test_list_schemas_rest(request_type): - client = SchemaServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/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 = schema.ListSchemasResponse( - next_page_token='next_page_token_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = schema.ListSchemasResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.list_schemas(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListSchemasPager) - assert response.next_page_token == 'next_page_token_value' - -def test_list_schemas_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 = SchemaServiceClient( - 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_schemas in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_schemas] = mock_rpc - - request = {} - client.list_schemas(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_schemas(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_schemas_rest_required_fields(request_type=schema.ListSchemasRequest): - transport_class = transports.SchemaServiceRestTransport - - 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_schemas._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_schemas._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", "view", )) - 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 = SchemaServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = schema.ListSchemasResponse() - # 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 = schema.ListSchemasResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.list_schemas(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_list_schemas_rest_unset_required_fields(): - transport = transports.SchemaServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.list_schemas._get_unset_required_fields({}) - assert set(unset_fields) == (set(("pageSize", "pageToken", "view", )) & set(("parent", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_schemas_rest_interceptors(null_interceptor): - transport = transports.SchemaServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SchemaServiceRestInterceptor(), - ) - client = SchemaServiceClient(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.SchemaServiceRestInterceptor, "post_list_schemas") as post, \ - mock.patch.object(transports.SchemaServiceRestInterceptor, "pre_list_schemas") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = schema.ListSchemasRequest.pb(schema.ListSchemasRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = schema.ListSchemasResponse.to_json(schema.ListSchemasResponse()) - - request = schema.ListSchemasRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = schema.ListSchemasResponse() - - client.list_schemas(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_schemas_rest_bad_request(transport: str = 'rest', request_type=schema.ListSchemasRequest): - client = SchemaServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/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 = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_schemas(request) - - -def test_list_schemas_rest_flattened(): - client = SchemaServiceClient( - 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 = schema.ListSchemasResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'projects/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 = schema.ListSchemasResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.list_schemas(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1/{parent=projects/*}/schemas" % client.transport._host, args[1]) - - -def test_list_schemas_rest_flattened_error(transport: str = 'rest'): - client = SchemaServiceClient( - 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_schemas( - schema.ListSchemasRequest(), - parent='parent_value', - ) - - -def test_list_schemas_rest_pager(transport: str = 'rest'): - client = SchemaServiceClient( - 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 = ( - schema.ListSchemasResponse( - schemas=[ - schema.Schema(), - schema.Schema(), - schema.Schema(), - ], - next_page_token='abc', - ), - schema.ListSchemasResponse( - schemas=[], - next_page_token='def', - ), - schema.ListSchemasResponse( - schemas=[ - schema.Schema(), - ], - next_page_token='ghi', - ), - schema.ListSchemasResponse( - schemas=[ - schema.Schema(), - schema.Schema(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(schema.ListSchemasResponse.to_json(x) for x in response) - return_values = tuple(Response() for i in response) - for return_val, response_val in zip(return_values, response): - return_val._content = response_val.encode('UTF-8') - return_val.status_code = 200 - req.side_effect = return_values - - sample_request = {'parent': 'projects/sample1'} - - pager = client.list_schemas(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, schema.Schema) - for i in results) - - pages = list(client.list_schemas(request=sample_request).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -@pytest.mark.parametrize("request_type", [ - schema.ListSchemaRevisionsRequest, - dict, -]) -def test_list_schema_revisions_rest(request_type): - client = SchemaServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/schemas/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 = schema.ListSchemaRevisionsResponse( - next_page_token='next_page_token_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = schema.ListSchemaRevisionsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.list_schema_revisions(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListSchemaRevisionsPager) - assert response.next_page_token == 'next_page_token_value' - -def test_list_schema_revisions_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 = SchemaServiceClient( - 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_schema_revisions in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_schema_revisions] = mock_rpc - - request = {} - client.list_schema_revisions(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_schema_revisions(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_schema_revisions_rest_required_fields(request_type=schema.ListSchemaRevisionsRequest): - transport_class = transports.SchemaServiceRestTransport - - 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()).list_schema_revisions._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()).list_schema_revisions._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", "view", )) - 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 = SchemaServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = schema.ListSchemaRevisionsResponse() - # 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 = schema.ListSchemaRevisionsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.list_schema_revisions(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_list_schema_revisions_rest_unset_required_fields(): - transport = transports.SchemaServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.list_schema_revisions._get_unset_required_fields({}) - assert set(unset_fields) == (set(("pageSize", "pageToken", "view", )) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_schema_revisions_rest_interceptors(null_interceptor): - transport = transports.SchemaServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SchemaServiceRestInterceptor(), - ) - client = SchemaServiceClient(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.SchemaServiceRestInterceptor, "post_list_schema_revisions") as post, \ - mock.patch.object(transports.SchemaServiceRestInterceptor, "pre_list_schema_revisions") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = schema.ListSchemaRevisionsRequest.pb(schema.ListSchemaRevisionsRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = schema.ListSchemaRevisionsResponse.to_json(schema.ListSchemaRevisionsResponse()) - - request = schema.ListSchemaRevisionsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = schema.ListSchemaRevisionsResponse() - - client.list_schema_revisions(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_schema_revisions_rest_bad_request(transport: str = 'rest', request_type=schema.ListSchemaRevisionsRequest): - client = SchemaServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/schemas/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 = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_schema_revisions(request) - - -def test_list_schema_revisions_rest_flattened(): - client = SchemaServiceClient( - 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 = schema.ListSchemaRevisionsResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/schemas/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 = schema.ListSchemaRevisionsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.list_schema_revisions(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1/{name=projects/*/schemas/*}:listRevisions" % client.transport._host, args[1]) - - -def test_list_schema_revisions_rest_flattened_error(transport: str = 'rest'): - client = SchemaServiceClient( - 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_schema_revisions( - schema.ListSchemaRevisionsRequest(), - name='name_value', - ) - - -def test_list_schema_revisions_rest_pager(transport: str = 'rest'): - client = SchemaServiceClient( - 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 = ( - schema.ListSchemaRevisionsResponse( - schemas=[ - schema.Schema(), - schema.Schema(), - schema.Schema(), - ], - next_page_token='abc', - ), - schema.ListSchemaRevisionsResponse( - schemas=[], - next_page_token='def', - ), - schema.ListSchemaRevisionsResponse( - schemas=[ - schema.Schema(), - ], - next_page_token='ghi', - ), - schema.ListSchemaRevisionsResponse( - schemas=[ - schema.Schema(), - schema.Schema(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(schema.ListSchemaRevisionsResponse.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 = {'name': 'projects/sample1/schemas/sample2'} - - pager = client.list_schema_revisions(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, schema.Schema) - for i in results) - - pages = list(client.list_schema_revisions(request=sample_request).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -@pytest.mark.parametrize("request_type", [ - gp_schema.CommitSchemaRequest, - dict, -]) -def test_commit_schema_rest(request_type): - client = SchemaServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/schemas/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 = gp_schema.Schema( - name='name_value', - type_=gp_schema.Schema.Type.PROTOCOL_BUFFER, - definition='definition_value', - revision_id='revision_id_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = gp_schema.Schema.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.commit_schema(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, gp_schema.Schema) - assert response.name == 'name_value' - assert response.type_ == gp_schema.Schema.Type.PROTOCOL_BUFFER - assert response.definition == 'definition_value' - assert response.revision_id == 'revision_id_value' - -def test_commit_schema_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 = SchemaServiceClient( - 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.commit_schema in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.commit_schema] = mock_rpc - - request = {} - client.commit_schema(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.commit_schema(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_commit_schema_rest_required_fields(request_type=gp_schema.CommitSchemaRequest): - transport_class = transports.SchemaServiceRestTransport - - 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()).commit_schema._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()).commit_schema._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 = SchemaServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = gp_schema.Schema() - # 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 = gp_schema.Schema.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.commit_schema(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_commit_schema_rest_unset_required_fields(): - transport = transports.SchemaServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.commit_schema._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", "schema", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_commit_schema_rest_interceptors(null_interceptor): - transport = transports.SchemaServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SchemaServiceRestInterceptor(), - ) - client = SchemaServiceClient(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.SchemaServiceRestInterceptor, "post_commit_schema") as post, \ - mock.patch.object(transports.SchemaServiceRestInterceptor, "pre_commit_schema") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = gp_schema.CommitSchemaRequest.pb(gp_schema.CommitSchemaRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = gp_schema.Schema.to_json(gp_schema.Schema()) - - request = gp_schema.CommitSchemaRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = gp_schema.Schema() - - client.commit_schema(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_commit_schema_rest_bad_request(transport: str = 'rest', request_type=gp_schema.CommitSchemaRequest): - client = SchemaServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/schemas/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 = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.commit_schema(request) - - -def test_commit_schema_rest_flattened(): - client = SchemaServiceClient( - 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 = gp_schema.Schema() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/schemas/sample2'} - - # get truthy value for each flattened field - mock_args = dict( - name='name_value', - schema=gp_schema.Schema(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 = gp_schema.Schema.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.commit_schema(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1/{name=projects/*/schemas/*}:commit" % client.transport._host, args[1]) - - -def test_commit_schema_rest_flattened_error(transport: str = 'rest'): - client = SchemaServiceClient( - 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.commit_schema( - gp_schema.CommitSchemaRequest(), - name='name_value', - schema=gp_schema.Schema(name='name_value'), - ) - - -def test_commit_schema_rest_error(): - client = SchemaServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - schema.RollbackSchemaRequest, - dict, -]) -def test_rollback_schema_rest(request_type): - client = SchemaServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/schemas/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 = schema.Schema( - name='name_value', - type_=schema.Schema.Type.PROTOCOL_BUFFER, - definition='definition_value', - revision_id='revision_id_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = schema.Schema.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.rollback_schema(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, schema.Schema) - assert response.name == 'name_value' - assert response.type_ == schema.Schema.Type.PROTOCOL_BUFFER - assert response.definition == 'definition_value' - assert response.revision_id == 'revision_id_value' - -def test_rollback_schema_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 = SchemaServiceClient( - 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.rollback_schema in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.rollback_schema] = mock_rpc - - request = {} - client.rollback_schema(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.rollback_schema(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_rollback_schema_rest_required_fields(request_type=schema.RollbackSchemaRequest): - transport_class = transports.SchemaServiceRestTransport - - request_init = {} - request_init["name"] = "" - request_init["revision_id"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).rollback_schema._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' - jsonified_request["revisionId"] = 'revision_id_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).rollback_schema._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' - assert "revisionId" in jsonified_request - assert jsonified_request["revisionId"] == 'revision_id_value' - - client = SchemaServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = schema.Schema() - # 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 = schema.Schema.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.rollback_schema(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_rollback_schema_rest_unset_required_fields(): - transport = transports.SchemaServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.rollback_schema._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", "revisionId", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_rollback_schema_rest_interceptors(null_interceptor): - transport = transports.SchemaServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SchemaServiceRestInterceptor(), - ) - client = SchemaServiceClient(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.SchemaServiceRestInterceptor, "post_rollback_schema") as post, \ - mock.patch.object(transports.SchemaServiceRestInterceptor, "pre_rollback_schema") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = schema.RollbackSchemaRequest.pb(schema.RollbackSchemaRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = schema.Schema.to_json(schema.Schema()) - - request = schema.RollbackSchemaRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = schema.Schema() - - client.rollback_schema(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_rollback_schema_rest_bad_request(transport: str = 'rest', request_type=schema.RollbackSchemaRequest): - client = SchemaServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/schemas/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 = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.rollback_schema(request) - - -def test_rollback_schema_rest_flattened(): - client = SchemaServiceClient( - 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 = schema.Schema() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/schemas/sample2'} - - # get truthy value for each flattened field - mock_args = dict( - name='name_value', - revision_id='revision_id_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 = schema.Schema.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.rollback_schema(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1/{name=projects/*/schemas/*}:rollback" % client.transport._host, args[1]) - - -def test_rollback_schema_rest_flattened_error(transport: str = 'rest'): - client = SchemaServiceClient( - 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.rollback_schema( - schema.RollbackSchemaRequest(), - name='name_value', - revision_id='revision_id_value', - ) - - -def test_rollback_schema_rest_error(): - client = SchemaServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - schema.DeleteSchemaRevisionRequest, - dict, -]) -def test_delete_schema_revision_rest(request_type): - client = SchemaServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/schemas/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 = schema.Schema( - name='name_value', - type_=schema.Schema.Type.PROTOCOL_BUFFER, - definition='definition_value', - revision_id='revision_id_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = schema.Schema.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.delete_schema_revision(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, schema.Schema) - assert response.name == 'name_value' - assert response.type_ == schema.Schema.Type.PROTOCOL_BUFFER - assert response.definition == 'definition_value' - assert response.revision_id == 'revision_id_value' - -def test_delete_schema_revision_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 = SchemaServiceClient( - 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_schema_revision in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_schema_revision] = mock_rpc - - request = {} - client.delete_schema_revision(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.delete_schema_revision(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_schema_revision_rest_required_fields(request_type=schema.DeleteSchemaRevisionRequest): - transport_class = transports.SchemaServiceRestTransport - - 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_schema_revision._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_schema_revision._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("revision_id", )) - 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 = SchemaServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = schema.Schema() - # 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 - - # Convert return value to protobuf type - return_value = schema.Schema.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.delete_schema_revision(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_delete_schema_revision_rest_unset_required_fields(): - transport = transports.SchemaServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.delete_schema_revision._get_unset_required_fields({}) - assert set(unset_fields) == (set(("revisionId", )) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_delete_schema_revision_rest_interceptors(null_interceptor): - transport = transports.SchemaServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SchemaServiceRestInterceptor(), - ) - client = SchemaServiceClient(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.SchemaServiceRestInterceptor, "post_delete_schema_revision") as post, \ - mock.patch.object(transports.SchemaServiceRestInterceptor, "pre_delete_schema_revision") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = schema.DeleteSchemaRevisionRequest.pb(schema.DeleteSchemaRevisionRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = schema.Schema.to_json(schema.Schema()) - - request = schema.DeleteSchemaRevisionRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = schema.Schema() - - client.delete_schema_revision(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_delete_schema_revision_rest_bad_request(transport: str = 'rest', request_type=schema.DeleteSchemaRevisionRequest): - client = SchemaServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/schemas/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 = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.delete_schema_revision(request) - - -def test_delete_schema_revision_rest_flattened(): - client = SchemaServiceClient( - 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 = schema.Schema() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/schemas/sample2'} - - # get truthy value for each flattened field - mock_args = dict( - name='name_value', - revision_id='revision_id_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 = schema.Schema.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.delete_schema_revision(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1/{name=projects/*/schemas/*}:deleteRevision" % client.transport._host, args[1]) - - -def test_delete_schema_revision_rest_flattened_error(transport: str = 'rest'): - client = SchemaServiceClient( - 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_schema_revision( - schema.DeleteSchemaRevisionRequest(), - name='name_value', - revision_id='revision_id_value', - ) - - -def test_delete_schema_revision_rest_error(): - client = SchemaServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - schema.DeleteSchemaRequest, - dict, -]) -def test_delete_schema_rest(request_type): - client = SchemaServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/schemas/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 = Response() - response_value.status_code = 200 - json_return_value = '' - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.delete_schema(request) - - # Establish that the response is the type that we expect. - assert response is None - -def test_delete_schema_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 = SchemaServiceClient( - 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_schema in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_schema] = mock_rpc - - request = {} - client.delete_schema(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.delete_schema(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_schema_rest_required_fields(request_type=schema.DeleteSchemaRequest): - transport_class = transports.SchemaServiceRestTransport - - 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_schema._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_schema._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 = SchemaServiceClient( - 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 - - response = client.delete_schema(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_delete_schema_rest_unset_required_fields(): - transport = transports.SchemaServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.delete_schema._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_delete_schema_rest_interceptors(null_interceptor): - transport = transports.SchemaServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SchemaServiceRestInterceptor(), - ) - client = SchemaServiceClient(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.SchemaServiceRestInterceptor, "pre_delete_schema") as pre: - pre.assert_not_called() - pb_message = schema.DeleteSchemaRequest.pb(schema.DeleteSchemaRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - - request = schema.DeleteSchemaRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - - client.delete_schema(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - - -def test_delete_schema_rest_bad_request(transport: str = 'rest', request_type=schema.DeleteSchemaRequest): - client = SchemaServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/schemas/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 = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.delete_schema(request) - - -def test_delete_schema_rest_flattened(): - client = SchemaServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = None - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/schemas/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 - - client.delete_schema(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1/{name=projects/*/schemas/*}" % client.transport._host, args[1]) - - -def test_delete_schema_rest_flattened_error(transport: str = 'rest'): - client = SchemaServiceClient( - 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_schema( - schema.DeleteSchemaRequest(), - name='name_value', - ) - - -def test_delete_schema_rest_error(): - client = SchemaServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - gp_schema.ValidateSchemaRequest, - dict, -]) -def test_validate_schema_rest(request_type): - client = SchemaServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/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 = gp_schema.ValidateSchemaResponse( - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = gp_schema.ValidateSchemaResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.validate_schema(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, gp_schema.ValidateSchemaResponse) - -def test_validate_schema_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 = SchemaServiceClient( - 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.validate_schema in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.validate_schema] = mock_rpc - - request = {} - client.validate_schema(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.validate_schema(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_validate_schema_rest_required_fields(request_type=gp_schema.ValidateSchemaRequest): - transport_class = transports.SchemaServiceRestTransport - - 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()).validate_schema._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()).validate_schema._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 = SchemaServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = gp_schema.ValidateSchemaResponse() - # 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 = gp_schema.ValidateSchemaResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.validate_schema(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_validate_schema_rest_unset_required_fields(): - transport = transports.SchemaServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.validate_schema._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("parent", "schema", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_validate_schema_rest_interceptors(null_interceptor): - transport = transports.SchemaServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SchemaServiceRestInterceptor(), - ) - client = SchemaServiceClient(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.SchemaServiceRestInterceptor, "post_validate_schema") as post, \ - mock.patch.object(transports.SchemaServiceRestInterceptor, "pre_validate_schema") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = gp_schema.ValidateSchemaRequest.pb(gp_schema.ValidateSchemaRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = gp_schema.ValidateSchemaResponse.to_json(gp_schema.ValidateSchemaResponse()) - - request = gp_schema.ValidateSchemaRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = gp_schema.ValidateSchemaResponse() - - client.validate_schema(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_validate_schema_rest_bad_request(transport: str = 'rest', request_type=gp_schema.ValidateSchemaRequest): - client = SchemaServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/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 = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.validate_schema(request) - - -def test_validate_schema_rest_flattened(): - client = SchemaServiceClient( - 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 = gp_schema.ValidateSchemaResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'projects/sample1'} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - schema=gp_schema.Schema(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 = gp_schema.ValidateSchemaResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.validate_schema(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1/{parent=projects/*}/schemas:validate" % client.transport._host, args[1]) - - -def test_validate_schema_rest_flattened_error(transport: str = 'rest'): - client = SchemaServiceClient( - 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.validate_schema( - gp_schema.ValidateSchemaRequest(), - parent='parent_value', - schema=gp_schema.Schema(name='name_value'), - ) - - -def test_validate_schema_rest_error(): - client = SchemaServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - schema.ValidateMessageRequest, - dict, -]) -def test_validate_message_rest(request_type): - client = SchemaServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/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 = schema.ValidateMessageResponse( - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = schema.ValidateMessageResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.validate_message(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, schema.ValidateMessageResponse) - -def test_validate_message_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 = SchemaServiceClient( - 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.validate_message in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.validate_message] = mock_rpc - - request = {} - client.validate_message(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.validate_message(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_validate_message_rest_required_fields(request_type=schema.ValidateMessageRequest): - transport_class = transports.SchemaServiceRestTransport - - 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()).validate_message._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()).validate_message._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 = SchemaServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = schema.ValidateMessageResponse() - # 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 = schema.ValidateMessageResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.validate_message(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_validate_message_rest_unset_required_fields(): - transport = transports.SchemaServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.validate_message._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("parent", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_validate_message_rest_interceptors(null_interceptor): - transport = transports.SchemaServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SchemaServiceRestInterceptor(), - ) - client = SchemaServiceClient(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.SchemaServiceRestInterceptor, "post_validate_message") as post, \ - mock.patch.object(transports.SchemaServiceRestInterceptor, "pre_validate_message") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = schema.ValidateMessageRequest.pb(schema.ValidateMessageRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = schema.ValidateMessageResponse.to_json(schema.ValidateMessageResponse()) - - request = schema.ValidateMessageRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = schema.ValidateMessageResponse() - - client.validate_message(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_validate_message_rest_bad_request(transport: str = 'rest', request_type=schema.ValidateMessageRequest): - client = SchemaServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/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 = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.validate_message(request) - - -def test_validate_message_rest_error(): - client = SchemaServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.SchemaServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = SchemaServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.SchemaServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = SchemaServiceClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide an api_key and a transport instance. - transport = transports.SchemaServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = SchemaServiceClient( - 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 = SchemaServiceClient( - client_options=options, - credentials=ga_credentials.AnonymousCredentials() - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.SchemaServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = SchemaServiceClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.SchemaServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = SchemaServiceClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.SchemaServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.SchemaServiceGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.SchemaServiceGrpcTransport, - transports.SchemaServiceGrpcAsyncIOTransport, - transports.SchemaServiceRestTransport, -]) -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() - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "rest", -]) -def test_transport_kind(transport_name): - transport = SchemaServiceClient.get_transport_class(transport_name)( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert transport.kind == transport_name - -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. - client = SchemaServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.SchemaServiceGrpcTransport, - ) - -def test_schema_service_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.SchemaServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_schema_service_base_transport(): - # Instantiate the base transport. - with mock.patch('google.pubsub_v1.services.schema_service.transports.SchemaServiceTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.SchemaServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'create_schema', - 'get_schema', - 'list_schemas', - 'list_schema_revisions', - 'commit_schema', - 'rollback_schema', - 'delete_schema_revision', - 'delete_schema', - 'validate_schema', - 'validate_message', - 'set_iam_policy', - 'get_iam_policy', - 'test_iam_permissions', - ) - 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_schema_service_base_transport_with_credentials_file(): - # Instantiate the base transport with a credentials file - with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.pubsub_v1.services.schema_service.transports.SchemaServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.SchemaServiceTransport( - credentials_file="credentials.json", - quota_project_id="octopus", - ) - load_creds.assert_called_once_with("credentials.json", - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/pubsub', -), - quota_project_id="octopus", - ) - - -def test_schema_service_base_transport_with_adc(): - # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(google.auth, 'default', autospec=True) as adc, mock.patch('google.pubsub_v1.services.schema_service.transports.SchemaServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.SchemaServiceTransport() - adc.assert_called_once() - - -def test_schema_service_auth_adc(): - # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - SchemaServiceClient() - adc.assert_called_once_with( - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/pubsub', -), - quota_project_id=None, - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.SchemaServiceGrpcTransport, - transports.SchemaServiceGrpcAsyncIOTransport, - ], -) -def test_schema_service_transport_auth_adc(transport_class): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class(quota_project_id="octopus", scopes=["1", "2"]) - adc.assert_called_once_with( - scopes=["1", "2"], - default_scopes=( 'https://www.googleapis.com/auth/cloud-platform', 'https://www.googleapis.com/auth/pubsub',), - quota_project_id="octopus", - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.SchemaServiceGrpcTransport, - transports.SchemaServiceGrpcAsyncIOTransport, - transports.SchemaServiceRestTransport, - ], -) -def test_schema_service_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.SchemaServiceGrpcTransport, grpc_helpers), - (transports.SchemaServiceGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -def test_schema_service_transport_create_channel(transport_class, grpc_helpers): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( - grpc_helpers, "create_channel", autospec=True - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - adc.return_value = (creds, None) - transport_class( - quota_project_id="octopus", - scopes=["1", "2"] - ) - - create_channel.assert_called_with( - "pubsub.googleapis.com:443", - credentials=creds, - credentials_file=None, - quota_project_id="octopus", - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/pubsub', -), - scopes=["1", "2"], - default_host="pubsub.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("transport_class", [transports.SchemaServiceGrpcTransport, transports.SchemaServiceGrpcAsyncIOTransport]) -def test_schema_service_grpc_transport_client_cert_source_for_mtls( - transport_class -): - cred = ga_credentials.AnonymousCredentials() - - # Check ssl_channel_credentials is used if provided. - with mock.patch.object(transport_class, "create_channel") as mock_create_channel: - mock_ssl_channel_creds = mock.Mock() - transport_class( - host="squid.clam.whelk", - credentials=cred, - ssl_channel_credentials=mock_ssl_channel_creds - ) - mock_create_channel.assert_called_once_with( - "squid.clam.whelk:443", - credentials=cred, - credentials_file=None, - scopes=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_schema_service_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.SchemaServiceRestTransport ( - 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_schema_service_host_no_port(transport_name): - client = SchemaServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='pubsub.googleapis.com'), - transport=transport_name, - ) - assert client.transport._host == ( - 'pubsub.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://pubsub.googleapis.com' - ) - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", - "rest", -]) -def test_schema_service_host_with_port(transport_name): - client = SchemaServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='pubsub.googleapis.com:8000'), - transport=transport_name, - ) - assert client.transport._host == ( - 'pubsub.googleapis.com:8000' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://pubsub.googleapis.com:8000' - ) - -@pytest.mark.parametrize("transport_name", [ - "rest", -]) -def test_schema_service_client_transport_session_collision(transport_name): - creds1 = ga_credentials.AnonymousCredentials() - creds2 = ga_credentials.AnonymousCredentials() - client1 = SchemaServiceClient( - credentials=creds1, - transport=transport_name, - ) - client2 = SchemaServiceClient( - credentials=creds2, - transport=transport_name, - ) - session1 = client1.transport.create_schema._session - session2 = client2.transport.create_schema._session - assert session1 != session2 - session1 = client1.transport.get_schema._session - session2 = client2.transport.get_schema._session - assert session1 != session2 - session1 = client1.transport.list_schemas._session - session2 = client2.transport.list_schemas._session - assert session1 != session2 - session1 = client1.transport.list_schema_revisions._session - session2 = client2.transport.list_schema_revisions._session - assert session1 != session2 - session1 = client1.transport.commit_schema._session - session2 = client2.transport.commit_schema._session - assert session1 != session2 - session1 = client1.transport.rollback_schema._session - session2 = client2.transport.rollback_schema._session - assert session1 != session2 - session1 = client1.transport.delete_schema_revision._session - session2 = client2.transport.delete_schema_revision._session - assert session1 != session2 - session1 = client1.transport.delete_schema._session - session2 = client2.transport.delete_schema._session - assert session1 != session2 - session1 = client1.transport.validate_schema._session - session2 = client2.transport.validate_schema._session - assert session1 != session2 - session1 = client1.transport.validate_message._session - session2 = client2.transport.validate_message._session - assert session1 != session2 -def test_schema_service_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.SchemaServiceGrpcTransport( - 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_schema_service_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.SchemaServiceGrpcAsyncIOTransport( - host="squid.clam.whelk", - channel=channel, - ) - assert transport.grpc_channel == channel - assert transport._host == "squid.clam.whelk:443" - assert transport._ssl_channel_credentials == None - - -# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are -# removed from grpc/grpc_asyncio transport constructor. -@pytest.mark.parametrize("transport_class", [transports.SchemaServiceGrpcTransport, transports.SchemaServiceGrpcAsyncIOTransport]) -def test_schema_service_transport_channel_mtls_with_client_cert_source( - transport_class -): - with mock.patch("grpc.ssl_channel_credentials", autospec=True) as grpc_ssl_channel_cred: - with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: - mock_ssl_cred = mock.Mock() - grpc_ssl_channel_cred.return_value = mock_ssl_cred - - mock_grpc_channel = mock.Mock() - grpc_create_channel.return_value = mock_grpc_channel - - cred = ga_credentials.AnonymousCredentials() - with pytest.warns(DeprecationWarning): - with mock.patch.object(google.auth, 'default') as adc: - adc.return_value = (cred, None) - transport = transport_class( - host="squid.clam.whelk", - api_mtls_endpoint="mtls.squid.clam.whelk", - client_cert_source=client_cert_source_callback, - ) - adc.assert_called_once() - - grpc_ssl_channel_cred.assert_called_once_with( - certificate_chain=b"cert bytes", private_key=b"key bytes" - ) - grpc_create_channel.assert_called_once_with( - "mtls.squid.clam.whelk:443", - credentials=cred, - credentials_file=None, - scopes=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.SchemaServiceGrpcTransport, transports.SchemaServiceGrpcAsyncIOTransport]) -def test_schema_service_transport_channel_mtls_with_adc( - transport_class -): - mock_ssl_cred = mock.Mock() - with mock.patch.multiple( - "google.auth.transport.grpc.SslCredentials", - __init__=mock.Mock(return_value=None), - ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), - ): - with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: - mock_grpc_channel = mock.Mock() - grpc_create_channel.return_value = mock_grpc_channel - mock_cred = mock.Mock() - - with pytest.warns(DeprecationWarning): - transport = transport_class( - host="squid.clam.whelk", - credentials=mock_cred, - api_mtls_endpoint="mtls.squid.clam.whelk", - client_cert_source=None, - ) - - grpc_create_channel.assert_called_once_with( - "mtls.squid.clam.whelk:443", - credentials=mock_cred, - credentials_file=None, - scopes=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_schema_path(): - project = "squid" - schema = "clam" - expected = "projects/{project}/schemas/{schema}".format(project=project, schema=schema, ) - actual = SchemaServiceClient.schema_path(project, schema) - assert expected == actual - - -def test_parse_schema_path(): - expected = { - "project": "whelk", - "schema": "octopus", - } - path = SchemaServiceClient.schema_path(**expected) - - # Check that the path construction is reversible. - actual = SchemaServiceClient.parse_schema_path(path) - assert expected == actual - -def test_common_billing_account_path(): - billing_account = "oyster" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = SchemaServiceClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "nudibranch", - } - path = SchemaServiceClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = SchemaServiceClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "cuttlefish" - expected = "folders/{folder}".format(folder=folder, ) - actual = SchemaServiceClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "mussel", - } - path = SchemaServiceClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = SchemaServiceClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "winkle" - expected = "organizations/{organization}".format(organization=organization, ) - actual = SchemaServiceClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "nautilus", - } - path = SchemaServiceClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = SchemaServiceClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "scallop" - expected = "projects/{project}".format(project=project, ) - actual = SchemaServiceClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "abalone", - } - path = SchemaServiceClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = SchemaServiceClient.parse_common_project_path(path) - assert expected == actual - -def test_common_location_path(): - project = "squid" - location = "clam" - expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) - actual = SchemaServiceClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "whelk", - "location": "octopus", - } - path = SchemaServiceClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = SchemaServiceClient.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.SchemaServiceTransport, '_prep_wrapped_messages') as prep: - client = SchemaServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.SchemaServiceTransport, '_prep_wrapped_messages') as prep: - transport_class = SchemaServiceClient.get_transport_class() - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - -@pytest.mark.asyncio -async def test_transport_close_async(): - client = SchemaServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - 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_get_iam_policy_rest_bad_request(transport: str = 'rest', request_type=iam_policy_pb2.GetIamPolicyRequest): - client = SchemaServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'resource': 'projects/sample1/topics/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() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_iam_policy(request) - -@pytest.mark.parametrize("request_type", [ - iam_policy_pb2.GetIamPolicyRequest, - dict, -]) -def test_get_iam_policy_rest(request_type): - client = SchemaServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'resource': 'projects/sample1/topics/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 = policy_pb2.Policy() - - # 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 - - response = client.get_iam_policy(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, policy_pb2.Policy) - -def test_set_iam_policy_rest_bad_request(transport: str = 'rest', request_type=iam_policy_pb2.SetIamPolicyRequest): - client = SchemaServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'resource': 'projects/sample1/topics/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() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.set_iam_policy(request) - -@pytest.mark.parametrize("request_type", [ - iam_policy_pb2.SetIamPolicyRequest, - dict, -]) -def test_set_iam_policy_rest(request_type): - client = SchemaServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'resource': 'projects/sample1/topics/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 = policy_pb2.Policy() - - # 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 - - response = client.set_iam_policy(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, policy_pb2.Policy) - -def test_test_iam_permissions_rest_bad_request(transport: str = 'rest', request_type=iam_policy_pb2.TestIamPermissionsRequest): - client = SchemaServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'resource': 'projects/sample1/subscriptions/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() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.test_iam_permissions(request) - -@pytest.mark.parametrize("request_type", [ - iam_policy_pb2.TestIamPermissionsRequest, - dict, -]) -def test_test_iam_permissions_rest(request_type): - client = SchemaServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'resource': 'projects/sample1/subscriptions/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 = iam_policy_pb2.TestIamPermissionsResponse() - - # 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 - - 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_set_iam_policy(transport: str = "grpc"): - client = SchemaServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional 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 = SchemaServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional 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 = SchemaServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = SchemaServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = SchemaServiceClient( - 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 = SchemaServiceAsyncClient( - 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 = grpc_helpers_async.FakeUnaryUnaryCall( - policy_pb2.Policy() - ) - - response = await client.set_iam_policy( - request={ - "resource": "resource_value", - "policy": policy_pb2.Policy(version=774), - } - ) - call.assert_called() - - -def test_get_iam_policy(transport: str = "grpc"): - client = SchemaServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional 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 = SchemaServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional 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 = SchemaServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = SchemaServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = SchemaServiceClient( - 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 = SchemaServiceAsyncClient( - 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 = grpc_helpers_async.FakeUnaryUnaryCall( - policy_pb2.Policy() - ) - - response = await client.get_iam_policy( - request={ - "resource": "resource_value", - "options": options_pb2.GetPolicyOptions(requested_policy_version=2598), - } - ) - call.assert_called() - - -def test_test_iam_permissions(transport: str = "grpc"): - client = SchemaServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional 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 = SchemaServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional 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 = SchemaServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = SchemaServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = SchemaServiceClient( - 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 = SchemaServiceAsyncClient( - 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 = grpc_helpers_async.FakeUnaryUnaryCall( - iam_policy_pb2.TestIamPermissionsResponse() - ) - - response = await client.test_iam_permissions( - request={ - "resource": "resource_value", - "permissions": ["permissions_value"], - } - ) - call.assert_called() - - -def test_transport_close(): - transports = { - "rest": "_session", - "grpc": "_grpc_channel", - } - - for transport, close_name in transports.items(): - client = SchemaServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport - ) - with mock.patch.object(type(getattr(client.transport, close_name)), "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 = SchemaServiceClient( - 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", [ - (SchemaServiceClient, transports.SchemaServiceGrpcTransport), - (SchemaServiceAsyncClient, transports.SchemaServiceGrpcAsyncIOTransport), -]) -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/owl-bot-staging/v1/tests/unit/gapic/pubsub_v1/test_subscriber.py b/owl-bot-staging/v1/tests/unit/gapic/pubsub_v1/test_subscriber.py deleted file mode 100644 index a9c47534a..000000000 --- a/owl-bot-staging/v1/tests/unit/gapic/pubsub_v1/test_subscriber.py +++ /dev/null @@ -1,12212 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import os -# try/except added for compatibility with python < 3.8 -try: - from unittest import mock - from unittest.mock import AsyncMock # pragma: NO COVER -except ImportError: # pragma: NO COVER - import mock - -import grpc -from grpc.experimental import aio -from collections.abc import Iterable -from google.protobuf import json_format -import json -import math -import pytest -from google.api_core import api_core_version -from proto.marshal.rules.dates import DurationRule, TimestampRule -from proto.marshal.rules import wrappers -from requests import Response -from requests import Request, PreparedRequest -from requests.sessions import Session -from google.protobuf import json_format - -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.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.oauth2 import service_account -from google.protobuf import duration_pb2 # type: ignore -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from google.pubsub_v1.services.subscriber import SubscriberAsyncClient -from google.pubsub_v1.services.subscriber import SubscriberClient -from google.pubsub_v1.services.subscriber import pagers -from google.pubsub_v1.services.subscriber import transports -from google.pubsub_v1.types import pubsub -import google.auth - - -def client_cert_source_callback(): - return b"cert bytes", b"key bytes" - -# If default endpoint is localhost, then default mtls endpoint will be the same. -# This method modifies the default endpoint so the client can produce a different -# mtls endpoint for endpoint testing purposes. -def modify_default_endpoint(client): - return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT - -# If default endpoint template is localhost, then default mtls endpoint will be the same. -# This method modifies the default endpoint template so the client can produce a different -# mtls endpoint for endpoint testing purposes. -def modify_default_endpoint_template(client): - return "test.{UNIVERSE_DOMAIN}" if ("localhost" in client._DEFAULT_ENDPOINT_TEMPLATE) else client._DEFAULT_ENDPOINT_TEMPLATE - - -def test__get_default_mtls_endpoint(): - api_endpoint = "example.googleapis.com" - api_mtls_endpoint = "example.mtls.googleapis.com" - sandbox_endpoint = "example.sandbox.googleapis.com" - sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" - non_googleapi = "api.example.com" - - assert SubscriberClient._get_default_mtls_endpoint(None) is None - assert SubscriberClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert SubscriberClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert SubscriberClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert SubscriberClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert SubscriberClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - -def test__read_environment_variables(): - assert SubscriberClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - assert SubscriberClient._read_environment_variables() == (True, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - assert SubscriberClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError) as excinfo: - SubscriberClient._read_environment_variables() - assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - assert SubscriberClient._read_environment_variables() == (False, "never", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - assert SubscriberClient._read_environment_variables() == (False, "always", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): - assert SubscriberClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError) as excinfo: - SubscriberClient._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 SubscriberClient._read_environment_variables() == (False, "auto", "foo.com") - -def test__get_client_cert_source(): - mock_provided_cert_source = mock.Mock() - mock_default_cert_source = mock.Mock() - - assert SubscriberClient._get_client_cert_source(None, False) is None - assert SubscriberClient._get_client_cert_source(mock_provided_cert_source, False) is None - assert SubscriberClient._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 SubscriberClient._get_client_cert_source(None, True) is mock_default_cert_source - assert SubscriberClient._get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source - -@mock.patch.object(SubscriberClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(SubscriberClient)) -@mock.patch.object(SubscriberAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(SubscriberAsyncClient)) -def test__get_api_endpoint(): - api_override = "foo.com" - mock_client_cert_source = mock.Mock() - default_universe = SubscriberClient._DEFAULT_UNIVERSE - default_endpoint = SubscriberClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) - mock_universe = "bar.com" - mock_endpoint = SubscriberClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) - - assert SubscriberClient._get_api_endpoint(api_override, mock_client_cert_source, default_universe, "always") == api_override - assert SubscriberClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "auto") == SubscriberClient.DEFAULT_MTLS_ENDPOINT - assert SubscriberClient._get_api_endpoint(None, None, default_universe, "auto") == default_endpoint - assert SubscriberClient._get_api_endpoint(None, None, default_universe, "always") == SubscriberClient.DEFAULT_MTLS_ENDPOINT - assert SubscriberClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "always") == SubscriberClient.DEFAULT_MTLS_ENDPOINT - assert SubscriberClient._get_api_endpoint(None, None, mock_universe, "never") == mock_endpoint - assert SubscriberClient._get_api_endpoint(None, None, default_universe, "never") == default_endpoint - - with pytest.raises(MutualTLSChannelError) as excinfo: - SubscriberClient._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 SubscriberClient._get_universe_domain(client_universe_domain, universe_domain_env) == client_universe_domain - assert SubscriberClient._get_universe_domain(None, universe_domain_env) == universe_domain_env - assert SubscriberClient._get_universe_domain(None, None) == SubscriberClient._DEFAULT_UNIVERSE - - with pytest.raises(ValueError) as excinfo: - SubscriberClient._get_universe_domain("", None) - assert str(excinfo.value) == "Universe Domain cannot be an empty string." - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (SubscriberClient, transports.SubscriberGrpcTransport, "grpc"), - (SubscriberClient, transports.SubscriberRestTransport, "rest"), -]) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials() - ) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - transport=transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [int(part) for part in google.auth.__version__.split(".")[0:2]] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class( - transport=transport_class(credentials=credentials) - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert str(excinfo.value) == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.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 >= 15): - client = client_class(client_options={"universe_domain": "bar.com"}, transport=transport_class(credentials=ga_credentials.AnonymousCredentials(),)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert str(excinfo.value) == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - -@pytest.mark.parametrize("client_class,transport_name", [ - (SubscriberClient, "grpc"), - (SubscriberAsyncClient, "grpc_asyncio"), - (SubscriberClient, "rest"), -]) -def test_subscriber_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 == ( - 'pubsub.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://pubsub.googleapis.com' - ) - - -@pytest.mark.parametrize("transport_class,transport_name", [ - (transports.SubscriberGrpcTransport, "grpc"), - (transports.SubscriberGrpcAsyncIOTransport, "grpc_asyncio"), - (transports.SubscriberRestTransport, "rest"), -]) -def test_subscriber_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", [ - (SubscriberClient, "grpc"), - (SubscriberAsyncClient, "grpc_asyncio"), - (SubscriberClient, "rest"), -]) -def test_subscriber_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 == ( - 'pubsub.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://pubsub.googleapis.com' - ) - - -def test_subscriber_client_get_transport_class(): - transport = SubscriberClient.get_transport_class() - available_transports = [ - transports.SubscriberGrpcTransport, - transports.SubscriberRestTransport, - ] - assert transport in available_transports - - transport = SubscriberClient.get_transport_class("grpc") - assert transport == transports.SubscriberGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (SubscriberClient, transports.SubscriberGrpcTransport, "grpc"), - (SubscriberAsyncClient, transports.SubscriberGrpcAsyncIOTransport, "grpc_asyncio"), - (SubscriberClient, transports.SubscriberRestTransport, "rest"), -]) -@mock.patch.object(SubscriberClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(SubscriberClient)) -@mock.patch.object(SubscriberAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(SubscriberAsyncClient)) -def test_subscriber_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(SubscriberClient, '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(SubscriberClient, 'get_transport_class') as gtc: - client = client_class(transport=transport_name) - gtc.assert_called() - - # Check the case api_endpoint is provided. - options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name, client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_MTLS_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has - # unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError) as excinfo: - client = client_class(transport=transport_name) - assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" - - # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError) as excinfo: - client = client_class(transport=transport_name) - assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - - # Check the case quota_project_id is provided - options = client_options.ClientOptions(quota_project_id="octopus") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id="octopus", - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - # Check the case api_endpoint is provided - options = client_options.ClientOptions(api_audience="https://language.googleapis.com") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience="https://language.googleapis.com" - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ - (SubscriberClient, transports.SubscriberGrpcTransport, "grpc", "true"), - (SubscriberAsyncClient, transports.SubscriberGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (SubscriberClient, transports.SubscriberGrpcTransport, "grpc", "false"), - (SubscriberAsyncClient, transports.SubscriberGrpcAsyncIOTransport, "grpc_asyncio", "false"), - (SubscriberClient, transports.SubscriberRestTransport, "rest", "true"), - (SubscriberClient, transports.SubscriberRestTransport, "rest", "false"), -]) -@mock.patch.object(SubscriberClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(SubscriberClient)) -@mock.patch.object(SubscriberAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(SubscriberAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_subscriber_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", [ - SubscriberClient, SubscriberAsyncClient -]) -@mock.patch.object(SubscriberClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SubscriberClient)) -@mock.patch.object(SubscriberAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SubscriberAsyncClient)) -def test_subscriber_client_get_mtls_endpoint_and_cert_source(client_class): - mock_client_cert_source = mock.Mock() - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source == mock_client_cert_source - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - mock_client_cert_source = mock.Mock() - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source == mock_client_cert_source - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has - # unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError) as excinfo: - client_class.get_mtls_endpoint_and_cert_source() - - assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" - - # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError) as excinfo: - client_class.get_mtls_endpoint_and_cert_source() - - assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - -@pytest.mark.parametrize("client_class", [ - SubscriberClient, SubscriberAsyncClient -]) -@mock.patch.object(SubscriberClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(SubscriberClient)) -@mock.patch.object(SubscriberAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(SubscriberAsyncClient)) -def test_subscriber_client_client_api_endpoint(client_class): - mock_client_cert_source = client_cert_source_callback - api_override = "foo.com" - default_universe = SubscriberClient._DEFAULT_UNIVERSE - default_endpoint = SubscriberClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) - mock_universe = "bar.com" - mock_endpoint = SubscriberClient._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", [ - (SubscriberClient, transports.SubscriberGrpcTransport, "grpc"), - (SubscriberAsyncClient, transports.SubscriberGrpcAsyncIOTransport, "grpc_asyncio"), - (SubscriberClient, transports.SubscriberRestTransport, "rest"), -]) -def test_subscriber_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", [ - (SubscriberClient, transports.SubscriberGrpcTransport, "grpc", grpc_helpers), - (SubscriberAsyncClient, transports.SubscriberGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), - (SubscriberClient, transports.SubscriberRestTransport, "rest", None), -]) -def test_subscriber_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_subscriber_client_client_options_from_dict(): - with mock.patch('google.pubsub_v1.services.subscriber.transports.SubscriberGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = SubscriberClient( - 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", [ - (SubscriberClient, transports.SubscriberGrpcTransport, "grpc", grpc_helpers), - (SubscriberAsyncClient, transports.SubscriberGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_subscriber_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( - "pubsub.googleapis.com:443", - credentials=file_creds, - credentials_file=None, - quota_project_id=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/pubsub', -), - scopes=None, - default_host="pubsub.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("request_type", [ - pubsub.Subscription, - dict, -]) -def test_create_subscription(request_type, transport: str = 'grpc'): - client = SubscriberClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_subscription), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = pubsub.Subscription( - name='name_value', - topic='topic_value', - ack_deadline_seconds=2066, - retain_acked_messages=True, - enable_message_ordering=True, - filter='filter_value', - detached=True, - enable_exactly_once_delivery=True, - state=pubsub.Subscription.State.ACTIVE, - ) - response = client.create_subscription(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = pubsub.Subscription() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pubsub.Subscription) - assert response.name == 'name_value' - assert response.topic == 'topic_value' - assert response.ack_deadline_seconds == 2066 - assert response.retain_acked_messages is True - assert response.enable_message_ordering is True - assert response.filter == 'filter_value' - assert response.detached is True - assert response.enable_exactly_once_delivery is True - assert response.state == pubsub.Subscription.State.ACTIVE - - -def test_create_subscription_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SubscriberClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_subscription), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.create_subscription() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == pubsub.Subscription() - - -def test_create_subscription_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 = SubscriberClient( - 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 = pubsub.Subscription( - name='name_value', - topic='topic_value', - filter='filter_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_subscription), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.create_subscription(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == pubsub.Subscription( - name='name_value', - topic='topic_value', - filter='filter_value', - ) - -def test_create_subscription_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = SubscriberClient( - 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_subscription in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_subscription] = mock_rpc - request = {} - client.create_subscription(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.create_subscription(request) - - # Establish that a new wrapper 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_subscription_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SubscriberAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_subscription), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(pubsub.Subscription( - name='name_value', - topic='topic_value', - ack_deadline_seconds=2066, - retain_acked_messages=True, - enable_message_ordering=True, - filter='filter_value', - detached=True, - enable_exactly_once_delivery=True, - state=pubsub.Subscription.State.ACTIVE, - )) - response = await client.create_subscription() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == pubsub.Subscription() - -@pytest.mark.asyncio -async def test_create_subscription_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 = SubscriberAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - 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_subscription 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_subscription] = mock_rpc - - request = {} - await client.create_subscription(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.create_subscription(request) - - # Establish that a new wrapper 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_subscription_async(transport: str = 'grpc_asyncio', request_type=pubsub.Subscription): - client = SubscriberAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_subscription), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(pubsub.Subscription( - name='name_value', - topic='topic_value', - ack_deadline_seconds=2066, - retain_acked_messages=True, - enable_message_ordering=True, - filter='filter_value', - detached=True, - enable_exactly_once_delivery=True, - state=pubsub.Subscription.State.ACTIVE, - )) - response = await client.create_subscription(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = pubsub.Subscription() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pubsub.Subscription) - assert response.name == 'name_value' - assert response.topic == 'topic_value' - assert response.ack_deadline_seconds == 2066 - assert response.retain_acked_messages is True - assert response.enable_message_ordering is True - assert response.filter == 'filter_value' - assert response.detached is True - assert response.enable_exactly_once_delivery is True - assert response.state == pubsub.Subscription.State.ACTIVE - - -@pytest.mark.asyncio -async def test_create_subscription_async_from_dict(): - await test_create_subscription_async(request_type=dict) - - -def test_create_subscription_field_headers(): - client = SubscriberClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = pubsub.Subscription() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_subscription), - '__call__') as call: - call.return_value = pubsub.Subscription() - client.create_subscription(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_create_subscription_field_headers_async(): - client = SubscriberAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = pubsub.Subscription() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_subscription), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(pubsub.Subscription()) - await client.create_subscription(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name_value', - ) in kw['metadata'] - - -def test_create_subscription_flattened(): - client = SubscriberClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_subscription), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = pubsub.Subscription() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.create_subscription( - name='name_value', - topic='topic_value', - push_config=pubsub.PushConfig(push_endpoint='push_endpoint_value'), - ack_deadline_seconds=2066, - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - arg = args[0].topic - mock_val = 'topic_value' - assert arg == mock_val - arg = args[0].push_config - mock_val = pubsub.PushConfig(push_endpoint='push_endpoint_value') - assert arg == mock_val - arg = args[0].ack_deadline_seconds - mock_val = 2066 - assert arg == mock_val - - -def test_create_subscription_flattened_error(): - client = SubscriberClient( - credentials=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_subscription( - pubsub.Subscription(), - name='name_value', - topic='topic_value', - push_config=pubsub.PushConfig(push_endpoint='push_endpoint_value'), - ack_deadline_seconds=2066, - ) - -@pytest.mark.asyncio -async def test_create_subscription_flattened_async(): - client = SubscriberAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_subscription), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = pubsub.Subscription() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(pubsub.Subscription()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.create_subscription( - name='name_value', - topic='topic_value', - push_config=pubsub.PushConfig(push_endpoint='push_endpoint_value'), - ack_deadline_seconds=2066, - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - arg = args[0].topic - mock_val = 'topic_value' - assert arg == mock_val - arg = args[0].push_config - mock_val = pubsub.PushConfig(push_endpoint='push_endpoint_value') - assert arg == mock_val - arg = args[0].ack_deadline_seconds - mock_val = 2066 - assert arg == mock_val - -@pytest.mark.asyncio -async def test_create_subscription_flattened_error_async(): - client = SubscriberAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.create_subscription( - pubsub.Subscription(), - name='name_value', - topic='topic_value', - push_config=pubsub.PushConfig(push_endpoint='push_endpoint_value'), - ack_deadline_seconds=2066, - ) - - -@pytest.mark.parametrize("request_type", [ - pubsub.GetSubscriptionRequest, - dict, -]) -def test_get_subscription(request_type, transport: str = 'grpc'): - client = SubscriberClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_subscription), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = pubsub.Subscription( - name='name_value', - topic='topic_value', - ack_deadline_seconds=2066, - retain_acked_messages=True, - enable_message_ordering=True, - filter='filter_value', - detached=True, - enable_exactly_once_delivery=True, - state=pubsub.Subscription.State.ACTIVE, - ) - response = client.get_subscription(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = pubsub.GetSubscriptionRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pubsub.Subscription) - assert response.name == 'name_value' - assert response.topic == 'topic_value' - assert response.ack_deadline_seconds == 2066 - assert response.retain_acked_messages is True - assert response.enable_message_ordering is True - assert response.filter == 'filter_value' - assert response.detached is True - assert response.enable_exactly_once_delivery is True - assert response.state == pubsub.Subscription.State.ACTIVE - - -def test_get_subscription_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SubscriberClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_subscription), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.get_subscription() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == pubsub.GetSubscriptionRequest() - - -def test_get_subscription_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 = SubscriberClient( - 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 = pubsub.GetSubscriptionRequest( - subscription='subscription_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_subscription), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.get_subscription(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == pubsub.GetSubscriptionRequest( - subscription='subscription_value', - ) - -def test_get_subscription_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = SubscriberClient( - 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_subscription in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_subscription] = mock_rpc - request = {} - client.get_subscription(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_subscription(request) - - # Establish that a new wrapper 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_subscription_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SubscriberAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_subscription), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(pubsub.Subscription( - name='name_value', - topic='topic_value', - ack_deadline_seconds=2066, - retain_acked_messages=True, - enable_message_ordering=True, - filter='filter_value', - detached=True, - enable_exactly_once_delivery=True, - state=pubsub.Subscription.State.ACTIVE, - )) - response = await client.get_subscription() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == pubsub.GetSubscriptionRequest() - -@pytest.mark.asyncio -async def test_get_subscription_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 = SubscriberAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - 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_subscription 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_subscription] = mock_rpc - - request = {} - await client.get_subscription(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.get_subscription(request) - - # Establish that a new wrapper 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_subscription_async(transport: str = 'grpc_asyncio', request_type=pubsub.GetSubscriptionRequest): - client = SubscriberAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_subscription), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(pubsub.Subscription( - name='name_value', - topic='topic_value', - ack_deadline_seconds=2066, - retain_acked_messages=True, - enable_message_ordering=True, - filter='filter_value', - detached=True, - enable_exactly_once_delivery=True, - state=pubsub.Subscription.State.ACTIVE, - )) - response = await client.get_subscription(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = pubsub.GetSubscriptionRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pubsub.Subscription) - assert response.name == 'name_value' - assert response.topic == 'topic_value' - assert response.ack_deadline_seconds == 2066 - assert response.retain_acked_messages is True - assert response.enable_message_ordering is True - assert response.filter == 'filter_value' - assert response.detached is True - assert response.enable_exactly_once_delivery is True - assert response.state == pubsub.Subscription.State.ACTIVE - - -@pytest.mark.asyncio -async def test_get_subscription_async_from_dict(): - await test_get_subscription_async(request_type=dict) - - -def test_get_subscription_field_headers(): - client = SubscriberClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = pubsub.GetSubscriptionRequest() - - request.subscription = 'subscription_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_subscription), - '__call__') as call: - call.return_value = pubsub.Subscription() - client.get_subscription(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'subscription=subscription_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_get_subscription_field_headers_async(): - client = SubscriberAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = pubsub.GetSubscriptionRequest() - - request.subscription = 'subscription_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_subscription), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(pubsub.Subscription()) - await client.get_subscription(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'subscription=subscription_value', - ) in kw['metadata'] - - -def test_get_subscription_flattened(): - client = SubscriberClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_subscription), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = pubsub.Subscription() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_subscription( - subscription='subscription_value', - ) - - # 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].subscription - mock_val = 'subscription_value' - assert arg == mock_val - - -def test_get_subscription_flattened_error(): - client = SubscriberClient( - credentials=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_subscription( - pubsub.GetSubscriptionRequest(), - subscription='subscription_value', - ) - -@pytest.mark.asyncio -async def test_get_subscription_flattened_async(): - client = SubscriberAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_subscription), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = pubsub.Subscription() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(pubsub.Subscription()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_subscription( - subscription='subscription_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].subscription - mock_val = 'subscription_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_get_subscription_flattened_error_async(): - client = SubscriberAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.get_subscription( - pubsub.GetSubscriptionRequest(), - subscription='subscription_value', - ) - - -@pytest.mark.parametrize("request_type", [ - pubsub.UpdateSubscriptionRequest, - dict, -]) -def test_update_subscription(request_type, transport: str = 'grpc'): - client = SubscriberClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_subscription), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = pubsub.Subscription( - name='name_value', - topic='topic_value', - ack_deadline_seconds=2066, - retain_acked_messages=True, - enable_message_ordering=True, - filter='filter_value', - detached=True, - enable_exactly_once_delivery=True, - state=pubsub.Subscription.State.ACTIVE, - ) - response = client.update_subscription(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = pubsub.UpdateSubscriptionRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pubsub.Subscription) - assert response.name == 'name_value' - assert response.topic == 'topic_value' - assert response.ack_deadline_seconds == 2066 - assert response.retain_acked_messages is True - assert response.enable_message_ordering is True - assert response.filter == 'filter_value' - assert response.detached is True - assert response.enable_exactly_once_delivery is True - assert response.state == pubsub.Subscription.State.ACTIVE - - -def test_update_subscription_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SubscriberClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_subscription), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.update_subscription() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == pubsub.UpdateSubscriptionRequest() - - -def test_update_subscription_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 = SubscriberClient( - 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 = pubsub.UpdateSubscriptionRequest( - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_subscription), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.update_subscription(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == pubsub.UpdateSubscriptionRequest( - ) - -def test_update_subscription_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = SubscriberClient( - 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_subscription in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_subscription] = mock_rpc - request = {} - client.update_subscription(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.update_subscription(request) - - # Establish that a new wrapper 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_subscription_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SubscriberAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_subscription), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(pubsub.Subscription( - name='name_value', - topic='topic_value', - ack_deadline_seconds=2066, - retain_acked_messages=True, - enable_message_ordering=True, - filter='filter_value', - detached=True, - enable_exactly_once_delivery=True, - state=pubsub.Subscription.State.ACTIVE, - )) - response = await client.update_subscription() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == pubsub.UpdateSubscriptionRequest() - -@pytest.mark.asyncio -async def test_update_subscription_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 = SubscriberAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - 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_subscription 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_subscription] = mock_rpc - - request = {} - await client.update_subscription(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.update_subscription(request) - - # Establish that a new wrapper 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_subscription_async(transport: str = 'grpc_asyncio', request_type=pubsub.UpdateSubscriptionRequest): - client = SubscriberAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_subscription), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(pubsub.Subscription( - name='name_value', - topic='topic_value', - ack_deadline_seconds=2066, - retain_acked_messages=True, - enable_message_ordering=True, - filter='filter_value', - detached=True, - enable_exactly_once_delivery=True, - state=pubsub.Subscription.State.ACTIVE, - )) - response = await client.update_subscription(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = pubsub.UpdateSubscriptionRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pubsub.Subscription) - assert response.name == 'name_value' - assert response.topic == 'topic_value' - assert response.ack_deadline_seconds == 2066 - assert response.retain_acked_messages is True - assert response.enable_message_ordering is True - assert response.filter == 'filter_value' - assert response.detached is True - assert response.enable_exactly_once_delivery is True - assert response.state == pubsub.Subscription.State.ACTIVE - - -@pytest.mark.asyncio -async def test_update_subscription_async_from_dict(): - await test_update_subscription_async(request_type=dict) - - -def test_update_subscription_field_headers(): - client = SubscriberClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = pubsub.UpdateSubscriptionRequest() - - request.subscription.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_subscription), - '__call__') as call: - call.return_value = pubsub.Subscription() - client.update_subscription(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'subscription.name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_subscription_field_headers_async(): - client = SubscriberAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = pubsub.UpdateSubscriptionRequest() - - request.subscription.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_subscription), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(pubsub.Subscription()) - await client.update_subscription(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'subscription.name=name_value', - ) in kw['metadata'] - - -def test_update_subscription_flattened(): - client = SubscriberClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_subscription), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = pubsub.Subscription() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.update_subscription( - subscription=pubsub.Subscription(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].subscription - mock_val = pubsub.Subscription(name='name_value') - assert arg == mock_val - arg = args[0].update_mask - mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) - assert arg == mock_val - - -def test_update_subscription_flattened_error(): - client = SubscriberClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.update_subscription( - pubsub.UpdateSubscriptionRequest(), - subscription=pubsub.Subscription(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - -@pytest.mark.asyncio -async def test_update_subscription_flattened_async(): - client = SubscriberAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_subscription), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = pubsub.Subscription() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(pubsub.Subscription()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.update_subscription( - subscription=pubsub.Subscription(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].subscription - mock_val = pubsub.Subscription(name='name_value') - assert arg == mock_val - arg = args[0].update_mask - mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) - assert arg == mock_val - -@pytest.mark.asyncio -async def test_update_subscription_flattened_error_async(): - client = SubscriberAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.update_subscription( - pubsub.UpdateSubscriptionRequest(), - subscription=pubsub.Subscription(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -@pytest.mark.parametrize("request_type", [ - pubsub.ListSubscriptionsRequest, - dict, -]) -def test_list_subscriptions(request_type, transport: str = 'grpc'): - client = SubscriberClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_subscriptions), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = pubsub.ListSubscriptionsResponse( - next_page_token='next_page_token_value', - ) - response = client.list_subscriptions(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = pubsub.ListSubscriptionsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListSubscriptionsPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_subscriptions_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SubscriberClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_subscriptions), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.list_subscriptions() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == pubsub.ListSubscriptionsRequest() - - -def test_list_subscriptions_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 = SubscriberClient( - 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 = pubsub.ListSubscriptionsRequest( - project='project_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_subscriptions), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.list_subscriptions(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == pubsub.ListSubscriptionsRequest( - project='project_value', - page_token='page_token_value', - ) - -def test_list_subscriptions_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = SubscriberClient( - 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_subscriptions in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_subscriptions] = mock_rpc - request = {} - client.list_subscriptions(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_subscriptions(request) - - # Establish that a new wrapper 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_subscriptions_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SubscriberAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_subscriptions), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(pubsub.ListSubscriptionsResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_subscriptions() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == pubsub.ListSubscriptionsRequest() - -@pytest.mark.asyncio -async def test_list_subscriptions_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 = SubscriberAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - 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_subscriptions 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_subscriptions] = mock_rpc - - request = {} - await client.list_subscriptions(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.list_subscriptions(request) - - # Establish that a new wrapper 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_subscriptions_async(transport: str = 'grpc_asyncio', request_type=pubsub.ListSubscriptionsRequest): - client = SubscriberAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_subscriptions), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(pubsub.ListSubscriptionsResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_subscriptions(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = pubsub.ListSubscriptionsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListSubscriptionsAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_subscriptions_async_from_dict(): - await test_list_subscriptions_async(request_type=dict) - - -def test_list_subscriptions_field_headers(): - client = SubscriberClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = pubsub.ListSubscriptionsRequest() - - request.project = 'project_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_subscriptions), - '__call__') as call: - call.return_value = pubsub.ListSubscriptionsResponse() - client.list_subscriptions(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'project=project_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_list_subscriptions_field_headers_async(): - client = SubscriberAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = pubsub.ListSubscriptionsRequest() - - request.project = 'project_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_subscriptions), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(pubsub.ListSubscriptionsResponse()) - await client.list_subscriptions(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'project=project_value', - ) in kw['metadata'] - - -def test_list_subscriptions_flattened(): - client = SubscriberClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_subscriptions), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = pubsub.ListSubscriptionsResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_subscriptions( - project='project_value', - ) - - # 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].project - mock_val = 'project_value' - assert arg == mock_val - - -def test_list_subscriptions_flattened_error(): - client = SubscriberClient( - credentials=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_subscriptions( - pubsub.ListSubscriptionsRequest(), - project='project_value', - ) - -@pytest.mark.asyncio -async def test_list_subscriptions_flattened_async(): - client = SubscriberAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_subscriptions), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = pubsub.ListSubscriptionsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(pubsub.ListSubscriptionsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_subscriptions( - project='project_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].project - mock_val = 'project_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_list_subscriptions_flattened_error_async(): - client = SubscriberAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.list_subscriptions( - pubsub.ListSubscriptionsRequest(), - project='project_value', - ) - - -def test_list_subscriptions_pager(transport_name: str = "grpc"): - client = SubscriberClient( - 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_subscriptions), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - pubsub.ListSubscriptionsResponse( - subscriptions=[ - pubsub.Subscription(), - pubsub.Subscription(), - pubsub.Subscription(), - ], - next_page_token='abc', - ), - pubsub.ListSubscriptionsResponse( - subscriptions=[], - next_page_token='def', - ), - pubsub.ListSubscriptionsResponse( - subscriptions=[ - pubsub.Subscription(), - ], - next_page_token='ghi', - ), - pubsub.ListSubscriptionsResponse( - subscriptions=[ - pubsub.Subscription(), - pubsub.Subscription(), - ], - ), - RuntimeError, - ) - - expected_metadata = () - retry = retries.Retry() - timeout = 5 - expected_metadata = tuple(expected_metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('project', ''), - )), - ) - pager = client.list_subscriptions(request={}, retry=retry, timeout=timeout) - - assert pager._metadata == expected_metadata - assert pager._retry == retry - assert pager._timeout == timeout - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, pubsub.Subscription) - for i in results) -def test_list_subscriptions_pages(transport_name: str = "grpc"): - client = SubscriberClient( - 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_subscriptions), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - pubsub.ListSubscriptionsResponse( - subscriptions=[ - pubsub.Subscription(), - pubsub.Subscription(), - pubsub.Subscription(), - ], - next_page_token='abc', - ), - pubsub.ListSubscriptionsResponse( - subscriptions=[], - next_page_token='def', - ), - pubsub.ListSubscriptionsResponse( - subscriptions=[ - pubsub.Subscription(), - ], - next_page_token='ghi', - ), - pubsub.ListSubscriptionsResponse( - subscriptions=[ - pubsub.Subscription(), - pubsub.Subscription(), - ], - ), - RuntimeError, - ) - pages = list(client.list_subscriptions(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_subscriptions_async_pager(): - client = SubscriberAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_subscriptions), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - pubsub.ListSubscriptionsResponse( - subscriptions=[ - pubsub.Subscription(), - pubsub.Subscription(), - pubsub.Subscription(), - ], - next_page_token='abc', - ), - pubsub.ListSubscriptionsResponse( - subscriptions=[], - next_page_token='def', - ), - pubsub.ListSubscriptionsResponse( - subscriptions=[ - pubsub.Subscription(), - ], - next_page_token='ghi', - ), - pubsub.ListSubscriptionsResponse( - subscriptions=[ - pubsub.Subscription(), - pubsub.Subscription(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_subscriptions(request={},) - assert async_pager.next_page_token == 'abc' - responses = [] - async for response in async_pager: # pragma: no branch - responses.append(response) - - assert len(responses) == 6 - assert all(isinstance(i, pubsub.Subscription) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_subscriptions_async_pages(): - client = SubscriberAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_subscriptions), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - pubsub.ListSubscriptionsResponse( - subscriptions=[ - pubsub.Subscription(), - pubsub.Subscription(), - pubsub.Subscription(), - ], - next_page_token='abc', - ), - pubsub.ListSubscriptionsResponse( - subscriptions=[], - next_page_token='def', - ), - pubsub.ListSubscriptionsResponse( - subscriptions=[ - pubsub.Subscription(), - ], - next_page_token='ghi', - ), - pubsub.ListSubscriptionsResponse( - subscriptions=[ - pubsub.Subscription(), - pubsub.Subscription(), - ], - ), - RuntimeError, - ) - pages = [] - # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` - # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 - async for page_ in ( # pragma: no branch - await client.list_subscriptions(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", [ - pubsub.DeleteSubscriptionRequest, - dict, -]) -def test_delete_subscription(request_type, transport: str = 'grpc'): - client = SubscriberClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_subscription), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = None - response = client.delete_subscription(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = pubsub.DeleteSubscriptionRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert response is None - - -def test_delete_subscription_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SubscriberClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_subscription), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.delete_subscription() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == pubsub.DeleteSubscriptionRequest() - - -def test_delete_subscription_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 = SubscriberClient( - 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 = pubsub.DeleteSubscriptionRequest( - subscription='subscription_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_subscription), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.delete_subscription(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == pubsub.DeleteSubscriptionRequest( - subscription='subscription_value', - ) - -def test_delete_subscription_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = SubscriberClient( - 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_subscription in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_subscription] = mock_rpc - request = {} - client.delete_subscription(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.delete_subscription(request) - - # Establish that a new wrapper 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_subscription_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SubscriberAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_subscription), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_subscription() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == pubsub.DeleteSubscriptionRequest() - -@pytest.mark.asyncio -async def test_delete_subscription_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 = SubscriberAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - 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_subscription 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_subscription] = mock_rpc - - request = {} - await client.delete_subscription(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.delete_subscription(request) - - # Establish that a new wrapper 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_subscription_async(transport: str = 'grpc_asyncio', request_type=pubsub.DeleteSubscriptionRequest): - client = SubscriberAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_subscription), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_subscription(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = pubsub.DeleteSubscriptionRequest() - 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_subscription_async_from_dict(): - await test_delete_subscription_async(request_type=dict) - - -def test_delete_subscription_field_headers(): - client = SubscriberClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = pubsub.DeleteSubscriptionRequest() - - request.subscription = 'subscription_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_subscription), - '__call__') as call: - call.return_value = None - client.delete_subscription(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'subscription=subscription_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_delete_subscription_field_headers_async(): - client = SubscriberAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = pubsub.DeleteSubscriptionRequest() - - request.subscription = 'subscription_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_subscription), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_subscription(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'subscription=subscription_value', - ) in kw['metadata'] - - -def test_delete_subscription_flattened(): - client = SubscriberClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_subscription), - '__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_subscription( - subscription='subscription_value', - ) - - # 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].subscription - mock_val = 'subscription_value' - assert arg == mock_val - - -def test_delete_subscription_flattened_error(): - client = SubscriberClient( - credentials=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_subscription( - pubsub.DeleteSubscriptionRequest(), - subscription='subscription_value', - ) - -@pytest.mark.asyncio -async def test_delete_subscription_flattened_async(): - client = SubscriberAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_subscription), - '__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_subscription( - subscription='subscription_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].subscription - mock_val = 'subscription_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_delete_subscription_flattened_error_async(): - client = SubscriberAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.delete_subscription( - pubsub.DeleteSubscriptionRequest(), - subscription='subscription_value', - ) - - -@pytest.mark.parametrize("request_type", [ - pubsub.ModifyAckDeadlineRequest, - dict, -]) -def test_modify_ack_deadline(request_type, transport: str = 'grpc'): - client = SubscriberClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.modify_ack_deadline), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = None - response = client.modify_ack_deadline(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = pubsub.ModifyAckDeadlineRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert response is None - - -def test_modify_ack_deadline_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SubscriberClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.modify_ack_deadline), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.modify_ack_deadline() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == pubsub.ModifyAckDeadlineRequest() - - -def test_modify_ack_deadline_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 = SubscriberClient( - 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 = pubsub.ModifyAckDeadlineRequest( - subscription='subscription_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.modify_ack_deadline), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.modify_ack_deadline(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == pubsub.ModifyAckDeadlineRequest( - subscription='subscription_value', - ) - -def test_modify_ack_deadline_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = SubscriberClient( - 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.modify_ack_deadline in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.modify_ack_deadline] = mock_rpc - request = {} - client.modify_ack_deadline(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.modify_ack_deadline(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_modify_ack_deadline_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SubscriberAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.modify_ack_deadline), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.modify_ack_deadline() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == pubsub.ModifyAckDeadlineRequest() - -@pytest.mark.asyncio -async def test_modify_ack_deadline_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 = SubscriberAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - 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.modify_ack_deadline 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.modify_ack_deadline] = mock_rpc - - request = {} - await client.modify_ack_deadline(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.modify_ack_deadline(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_modify_ack_deadline_async(transport: str = 'grpc_asyncio', request_type=pubsub.ModifyAckDeadlineRequest): - client = SubscriberAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.modify_ack_deadline), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.modify_ack_deadline(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = pubsub.ModifyAckDeadlineRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert response is None - - -@pytest.mark.asyncio -async def test_modify_ack_deadline_async_from_dict(): - await test_modify_ack_deadline_async(request_type=dict) - - -def test_modify_ack_deadline_field_headers(): - client = SubscriberClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = pubsub.ModifyAckDeadlineRequest() - - request.subscription = 'subscription_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.modify_ack_deadline), - '__call__') as call: - call.return_value = None - client.modify_ack_deadline(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'subscription=subscription_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_modify_ack_deadline_field_headers_async(): - client = SubscriberAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = pubsub.ModifyAckDeadlineRequest() - - request.subscription = 'subscription_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.modify_ack_deadline), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.modify_ack_deadline(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'subscription=subscription_value', - ) in kw['metadata'] - - -def test_modify_ack_deadline_flattened(): - client = SubscriberClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.modify_ack_deadline), - '__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.modify_ack_deadline( - subscription='subscription_value', - ack_ids=['ack_ids_value'], - ack_deadline_seconds=2066, - ) - - # 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].subscription - mock_val = 'subscription_value' - assert arg == mock_val - arg = args[0].ack_ids - mock_val = ['ack_ids_value'] - assert arg == mock_val - arg = args[0].ack_deadline_seconds - mock_val = 2066 - assert arg == mock_val - - -def test_modify_ack_deadline_flattened_error(): - client = SubscriberClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.modify_ack_deadline( - pubsub.ModifyAckDeadlineRequest(), - subscription='subscription_value', - ack_ids=['ack_ids_value'], - ack_deadline_seconds=2066, - ) - -@pytest.mark.asyncio -async def test_modify_ack_deadline_flattened_async(): - client = SubscriberAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.modify_ack_deadline), - '__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.modify_ack_deadline( - subscription='subscription_value', - ack_ids=['ack_ids_value'], - ack_deadline_seconds=2066, - ) - - # 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].subscription - mock_val = 'subscription_value' - assert arg == mock_val - arg = args[0].ack_ids - mock_val = ['ack_ids_value'] - assert arg == mock_val - arg = args[0].ack_deadline_seconds - mock_val = 2066 - assert arg == mock_val - -@pytest.mark.asyncio -async def test_modify_ack_deadline_flattened_error_async(): - client = SubscriberAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.modify_ack_deadline( - pubsub.ModifyAckDeadlineRequest(), - subscription='subscription_value', - ack_ids=['ack_ids_value'], - ack_deadline_seconds=2066, - ) - - -@pytest.mark.parametrize("request_type", [ - pubsub.AcknowledgeRequest, - dict, -]) -def test_acknowledge(request_type, transport: str = 'grpc'): - client = SubscriberClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.acknowledge), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = None - response = client.acknowledge(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = pubsub.AcknowledgeRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert response is None - - -def test_acknowledge_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SubscriberClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.acknowledge), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.acknowledge() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == pubsub.AcknowledgeRequest() - - -def test_acknowledge_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 = SubscriberClient( - 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 = pubsub.AcknowledgeRequest( - subscription='subscription_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.acknowledge), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.acknowledge(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == pubsub.AcknowledgeRequest( - subscription='subscription_value', - ) - -def test_acknowledge_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = SubscriberClient( - 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.acknowledge in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.acknowledge] = mock_rpc - request = {} - client.acknowledge(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.acknowledge(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_acknowledge_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SubscriberAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.acknowledge), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.acknowledge() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == pubsub.AcknowledgeRequest() - -@pytest.mark.asyncio -async def test_acknowledge_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 = SubscriberAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - 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.acknowledge 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.acknowledge] = mock_rpc - - request = {} - await client.acknowledge(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.acknowledge(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_acknowledge_async(transport: str = 'grpc_asyncio', request_type=pubsub.AcknowledgeRequest): - client = SubscriberAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.acknowledge), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.acknowledge(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = pubsub.AcknowledgeRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert response is None - - -@pytest.mark.asyncio -async def test_acknowledge_async_from_dict(): - await test_acknowledge_async(request_type=dict) - - -def test_acknowledge_field_headers(): - client = SubscriberClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = pubsub.AcknowledgeRequest() - - request.subscription = 'subscription_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.acknowledge), - '__call__') as call: - call.return_value = None - client.acknowledge(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'subscription=subscription_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_acknowledge_field_headers_async(): - client = SubscriberAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = pubsub.AcknowledgeRequest() - - request.subscription = 'subscription_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.acknowledge), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.acknowledge(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'subscription=subscription_value', - ) in kw['metadata'] - - -def test_acknowledge_flattened(): - client = SubscriberClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.acknowledge), - '__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.acknowledge( - subscription='subscription_value', - ack_ids=['ack_ids_value'], - ) - - # 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].subscription - mock_val = 'subscription_value' - assert arg == mock_val - arg = args[0].ack_ids - mock_val = ['ack_ids_value'] - assert arg == mock_val - - -def test_acknowledge_flattened_error(): - client = SubscriberClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.acknowledge( - pubsub.AcknowledgeRequest(), - subscription='subscription_value', - ack_ids=['ack_ids_value'], - ) - -@pytest.mark.asyncio -async def test_acknowledge_flattened_async(): - client = SubscriberAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.acknowledge), - '__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.acknowledge( - subscription='subscription_value', - ack_ids=['ack_ids_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].subscription - mock_val = 'subscription_value' - assert arg == mock_val - arg = args[0].ack_ids - mock_val = ['ack_ids_value'] - assert arg == mock_val - -@pytest.mark.asyncio -async def test_acknowledge_flattened_error_async(): - client = SubscriberAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.acknowledge( - pubsub.AcknowledgeRequest(), - subscription='subscription_value', - ack_ids=['ack_ids_value'], - ) - - -@pytest.mark.parametrize("request_type", [ - pubsub.PullRequest, - dict, -]) -def test_pull(request_type, transport: str = 'grpc'): - client = SubscriberClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.pull), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = pubsub.PullResponse( - ) - response = client.pull(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = pubsub.PullRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pubsub.PullResponse) - - -def test_pull_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SubscriberClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.pull), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.pull() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == pubsub.PullRequest() - - -def test_pull_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 = SubscriberClient( - 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 = pubsub.PullRequest( - subscription='subscription_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.pull), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.pull(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == pubsub.PullRequest( - subscription='subscription_value', - ) - -def test_pull_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = SubscriberClient( - 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.pull in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.pull] = mock_rpc - request = {} - client.pull(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.pull(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_pull_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SubscriberAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.pull), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(pubsub.PullResponse( - )) - response = await client.pull() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == pubsub.PullRequest() - -@pytest.mark.asyncio -async def test_pull_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 = SubscriberAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - 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.pull 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.pull] = mock_rpc - - request = {} - await client.pull(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.pull(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_pull_async(transport: str = 'grpc_asyncio', request_type=pubsub.PullRequest): - client = SubscriberAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.pull), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(pubsub.PullResponse( - )) - response = await client.pull(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = pubsub.PullRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pubsub.PullResponse) - - -@pytest.mark.asyncio -async def test_pull_async_from_dict(): - await test_pull_async(request_type=dict) - - -def test_pull_field_headers(): - client = SubscriberClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = pubsub.PullRequest() - - request.subscription = 'subscription_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.pull), - '__call__') as call: - call.return_value = pubsub.PullResponse() - client.pull(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'subscription=subscription_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_pull_field_headers_async(): - client = SubscriberAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = pubsub.PullRequest() - - request.subscription = 'subscription_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.pull), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(pubsub.PullResponse()) - await client.pull(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'subscription=subscription_value', - ) in kw['metadata'] - - -def test_pull_flattened(): - client = SubscriberClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.pull), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = pubsub.PullResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.pull( - subscription='subscription_value', - return_immediately=True, - max_messages=1277, - ) - - # 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].subscription - mock_val = 'subscription_value' - assert arg == mock_val - arg = args[0].return_immediately - mock_val = True - assert arg == mock_val - arg = args[0].max_messages - mock_val = 1277 - assert arg == mock_val - - -def test_pull_flattened_error(): - client = SubscriberClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.pull( - pubsub.PullRequest(), - subscription='subscription_value', - return_immediately=True, - max_messages=1277, - ) - -@pytest.mark.asyncio -async def test_pull_flattened_async(): - client = SubscriberAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.pull), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = pubsub.PullResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(pubsub.PullResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.pull( - subscription='subscription_value', - return_immediately=True, - max_messages=1277, - ) - - # 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].subscription - mock_val = 'subscription_value' - assert arg == mock_val - arg = args[0].return_immediately - mock_val = True - assert arg == mock_val - arg = args[0].max_messages - mock_val = 1277 - assert arg == mock_val - -@pytest.mark.asyncio -async def test_pull_flattened_error_async(): - client = SubscriberAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.pull( - pubsub.PullRequest(), - subscription='subscription_value', - return_immediately=True, - max_messages=1277, - ) - - -@pytest.mark.parametrize("request_type", [ - pubsub.StreamingPullRequest, - dict, -]) -def test_streaming_pull(request_type, transport: str = 'grpc'): - client = SubscriberClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - requests = [request] - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.streaming_pull), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = iter([pubsub.StreamingPullResponse()]) - response = client.streaming_pull(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, pubsub.StreamingPullResponse) - - -def test_streaming_pull_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = SubscriberClient( - 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.streaming_pull in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.streaming_pull] = mock_rpc - request = [{}] - client.streaming_pull(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.streaming_pull(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -@pytest.mark.asyncio -async def test_streaming_pull_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 = SubscriberAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - 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.streaming_pull 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.streaming_pull] = mock_rpc - - request = [{}] - await client.streaming_pull(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.streaming_pull(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_streaming_pull_async(transport: str = 'grpc_asyncio', request_type=pubsub.StreamingPullRequest): - client = SubscriberAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - requests = [request] - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.streaming_pull), - '__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=[pubsub.StreamingPullResponse()]) - response = await client.streaming_pull(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, pubsub.StreamingPullResponse) - - -@pytest.mark.asyncio -async def test_streaming_pull_async_from_dict(): - await test_streaming_pull_async(request_type=dict) - - -@pytest.mark.parametrize("request_type", [ - pubsub.ModifyPushConfigRequest, - dict, -]) -def test_modify_push_config(request_type, transport: str = 'grpc'): - client = SubscriberClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.modify_push_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = None - response = client.modify_push_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = pubsub.ModifyPushConfigRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert response is None - - -def test_modify_push_config_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SubscriberClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.modify_push_config), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.modify_push_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == pubsub.ModifyPushConfigRequest() - - -def test_modify_push_config_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = SubscriberClient( - 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 = pubsub.ModifyPushConfigRequest( - subscription='subscription_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.modify_push_config), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.modify_push_config(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == pubsub.ModifyPushConfigRequest( - subscription='subscription_value', - ) - -def test_modify_push_config_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = SubscriberClient( - 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.modify_push_config in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.modify_push_config] = mock_rpc - request = {} - client.modify_push_config(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.modify_push_config(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_modify_push_config_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SubscriberAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.modify_push_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.modify_push_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == pubsub.ModifyPushConfigRequest() - -@pytest.mark.asyncio -async def test_modify_push_config_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = SubscriberAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - 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.modify_push_config in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.AsyncMock() - mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[client._client._transport.modify_push_config] = mock_rpc - - request = {} - await client.modify_push_config(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.modify_push_config(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_modify_push_config_async(transport: str = 'grpc_asyncio', request_type=pubsub.ModifyPushConfigRequest): - client = SubscriberAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.modify_push_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.modify_push_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = pubsub.ModifyPushConfigRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert response is None - - -@pytest.mark.asyncio -async def test_modify_push_config_async_from_dict(): - await test_modify_push_config_async(request_type=dict) - - -def test_modify_push_config_field_headers(): - client = SubscriberClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = pubsub.ModifyPushConfigRequest() - - request.subscription = 'subscription_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.modify_push_config), - '__call__') as call: - call.return_value = None - client.modify_push_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'subscription=subscription_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_modify_push_config_field_headers_async(): - client = SubscriberAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = pubsub.ModifyPushConfigRequest() - - request.subscription = 'subscription_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.modify_push_config), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.modify_push_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'subscription=subscription_value', - ) in kw['metadata'] - - -def test_modify_push_config_flattened(): - client = SubscriberClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.modify_push_config), - '__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.modify_push_config( - subscription='subscription_value', - push_config=pubsub.PushConfig(push_endpoint='push_endpoint_value'), - ) - - # 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].subscription - mock_val = 'subscription_value' - assert arg == mock_val - arg = args[0].push_config - mock_val = pubsub.PushConfig(push_endpoint='push_endpoint_value') - assert arg == mock_val - - -def test_modify_push_config_flattened_error(): - client = SubscriberClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.modify_push_config( - pubsub.ModifyPushConfigRequest(), - subscription='subscription_value', - push_config=pubsub.PushConfig(push_endpoint='push_endpoint_value'), - ) - -@pytest.mark.asyncio -async def test_modify_push_config_flattened_async(): - client = SubscriberAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.modify_push_config), - '__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.modify_push_config( - subscription='subscription_value', - push_config=pubsub.PushConfig(push_endpoint='push_endpoint_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].subscription - mock_val = 'subscription_value' - assert arg == mock_val - arg = args[0].push_config - mock_val = pubsub.PushConfig(push_endpoint='push_endpoint_value') - assert arg == mock_val - -@pytest.mark.asyncio -async def test_modify_push_config_flattened_error_async(): - client = SubscriberAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.modify_push_config( - pubsub.ModifyPushConfigRequest(), - subscription='subscription_value', - push_config=pubsub.PushConfig(push_endpoint='push_endpoint_value'), - ) - - -@pytest.mark.parametrize("request_type", [ - pubsub.GetSnapshotRequest, - dict, -]) -def test_get_snapshot(request_type, transport: str = 'grpc'): - client = SubscriberClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_snapshot), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = pubsub.Snapshot( - name='name_value', - topic='topic_value', - ) - response = client.get_snapshot(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = pubsub.GetSnapshotRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pubsub.Snapshot) - assert response.name == 'name_value' - assert response.topic == 'topic_value' - - -def test_get_snapshot_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SubscriberClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_snapshot), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.get_snapshot() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == pubsub.GetSnapshotRequest() - - -def test_get_snapshot_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 = SubscriberClient( - 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 = pubsub.GetSnapshotRequest( - snapshot='snapshot_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_snapshot), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.get_snapshot(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == pubsub.GetSnapshotRequest( - snapshot='snapshot_value', - ) - -def test_get_snapshot_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = SubscriberClient( - 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_snapshot in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_snapshot] = mock_rpc - request = {} - client.get_snapshot(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_snapshot(request) - - # Establish that a new wrapper 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_snapshot_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SubscriberAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_snapshot), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(pubsub.Snapshot( - name='name_value', - topic='topic_value', - )) - response = await client.get_snapshot() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == pubsub.GetSnapshotRequest() - -@pytest.mark.asyncio -async def test_get_snapshot_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 = SubscriberAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - 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_snapshot 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_snapshot] = mock_rpc - - request = {} - await client.get_snapshot(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.get_snapshot(request) - - # Establish that a new wrapper 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_snapshot_async(transport: str = 'grpc_asyncio', request_type=pubsub.GetSnapshotRequest): - client = SubscriberAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_snapshot), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(pubsub.Snapshot( - name='name_value', - topic='topic_value', - )) - response = await client.get_snapshot(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = pubsub.GetSnapshotRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pubsub.Snapshot) - assert response.name == 'name_value' - assert response.topic == 'topic_value' - - -@pytest.mark.asyncio -async def test_get_snapshot_async_from_dict(): - await test_get_snapshot_async(request_type=dict) - - -def test_get_snapshot_field_headers(): - client = SubscriberClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = pubsub.GetSnapshotRequest() - - request.snapshot = 'snapshot_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_snapshot), - '__call__') as call: - call.return_value = pubsub.Snapshot() - client.get_snapshot(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'snapshot=snapshot_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_get_snapshot_field_headers_async(): - client = SubscriberAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = pubsub.GetSnapshotRequest() - - request.snapshot = 'snapshot_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_snapshot), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(pubsub.Snapshot()) - await client.get_snapshot(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'snapshot=snapshot_value', - ) in kw['metadata'] - - -def test_get_snapshot_flattened(): - client = SubscriberClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_snapshot), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = pubsub.Snapshot() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_snapshot( - snapshot='snapshot_value', - ) - - # 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].snapshot - mock_val = 'snapshot_value' - assert arg == mock_val - - -def test_get_snapshot_flattened_error(): - client = SubscriberClient( - credentials=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_snapshot( - pubsub.GetSnapshotRequest(), - snapshot='snapshot_value', - ) - -@pytest.mark.asyncio -async def test_get_snapshot_flattened_async(): - client = SubscriberAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_snapshot), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = pubsub.Snapshot() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(pubsub.Snapshot()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_snapshot( - snapshot='snapshot_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].snapshot - mock_val = 'snapshot_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_get_snapshot_flattened_error_async(): - client = SubscriberAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.get_snapshot( - pubsub.GetSnapshotRequest(), - snapshot='snapshot_value', - ) - - -@pytest.mark.parametrize("request_type", [ - pubsub.ListSnapshotsRequest, - dict, -]) -def test_list_snapshots(request_type, transport: str = 'grpc'): - client = SubscriberClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_snapshots), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = pubsub.ListSnapshotsResponse( - next_page_token='next_page_token_value', - ) - response = client.list_snapshots(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = pubsub.ListSnapshotsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListSnapshotsPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_snapshots_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SubscriberClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_snapshots), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.list_snapshots() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == pubsub.ListSnapshotsRequest() - - -def test_list_snapshots_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 = SubscriberClient( - 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 = pubsub.ListSnapshotsRequest( - project='project_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_snapshots), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.list_snapshots(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == pubsub.ListSnapshotsRequest( - project='project_value', - page_token='page_token_value', - ) - -def test_list_snapshots_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = SubscriberClient( - 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_snapshots in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_snapshots] = mock_rpc - request = {} - client.list_snapshots(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_snapshots(request) - - # Establish that a new wrapper 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_snapshots_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SubscriberAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_snapshots), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(pubsub.ListSnapshotsResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_snapshots() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == pubsub.ListSnapshotsRequest() - -@pytest.mark.asyncio -async def test_list_snapshots_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 = SubscriberAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - 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_snapshots 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_snapshots] = mock_rpc - - request = {} - await client.list_snapshots(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.list_snapshots(request) - - # Establish that a new wrapper 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_snapshots_async(transport: str = 'grpc_asyncio', request_type=pubsub.ListSnapshotsRequest): - client = SubscriberAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_snapshots), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(pubsub.ListSnapshotsResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_snapshots(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = pubsub.ListSnapshotsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListSnapshotsAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_snapshots_async_from_dict(): - await test_list_snapshots_async(request_type=dict) - - -def test_list_snapshots_field_headers(): - client = SubscriberClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = pubsub.ListSnapshotsRequest() - - request.project = 'project_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_snapshots), - '__call__') as call: - call.return_value = pubsub.ListSnapshotsResponse() - client.list_snapshots(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'project=project_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_list_snapshots_field_headers_async(): - client = SubscriberAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = pubsub.ListSnapshotsRequest() - - request.project = 'project_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_snapshots), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(pubsub.ListSnapshotsResponse()) - await client.list_snapshots(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'project=project_value', - ) in kw['metadata'] - - -def test_list_snapshots_flattened(): - client = SubscriberClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_snapshots), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = pubsub.ListSnapshotsResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_snapshots( - project='project_value', - ) - - # 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].project - mock_val = 'project_value' - assert arg == mock_val - - -def test_list_snapshots_flattened_error(): - client = SubscriberClient( - credentials=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_snapshots( - pubsub.ListSnapshotsRequest(), - project='project_value', - ) - -@pytest.mark.asyncio -async def test_list_snapshots_flattened_async(): - client = SubscriberAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_snapshots), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = pubsub.ListSnapshotsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(pubsub.ListSnapshotsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_snapshots( - project='project_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].project - mock_val = 'project_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_list_snapshots_flattened_error_async(): - client = SubscriberAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.list_snapshots( - pubsub.ListSnapshotsRequest(), - project='project_value', - ) - - -def test_list_snapshots_pager(transport_name: str = "grpc"): - client = SubscriberClient( - 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_snapshots), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - pubsub.ListSnapshotsResponse( - snapshots=[ - pubsub.Snapshot(), - pubsub.Snapshot(), - pubsub.Snapshot(), - ], - next_page_token='abc', - ), - pubsub.ListSnapshotsResponse( - snapshots=[], - next_page_token='def', - ), - pubsub.ListSnapshotsResponse( - snapshots=[ - pubsub.Snapshot(), - ], - next_page_token='ghi', - ), - pubsub.ListSnapshotsResponse( - snapshots=[ - pubsub.Snapshot(), - pubsub.Snapshot(), - ], - ), - RuntimeError, - ) - - expected_metadata = () - retry = retries.Retry() - timeout = 5 - expected_metadata = tuple(expected_metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('project', ''), - )), - ) - pager = client.list_snapshots(request={}, retry=retry, timeout=timeout) - - assert pager._metadata == expected_metadata - assert pager._retry == retry - assert pager._timeout == timeout - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, pubsub.Snapshot) - for i in results) -def test_list_snapshots_pages(transport_name: str = "grpc"): - client = SubscriberClient( - 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_snapshots), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - pubsub.ListSnapshotsResponse( - snapshots=[ - pubsub.Snapshot(), - pubsub.Snapshot(), - pubsub.Snapshot(), - ], - next_page_token='abc', - ), - pubsub.ListSnapshotsResponse( - snapshots=[], - next_page_token='def', - ), - pubsub.ListSnapshotsResponse( - snapshots=[ - pubsub.Snapshot(), - ], - next_page_token='ghi', - ), - pubsub.ListSnapshotsResponse( - snapshots=[ - pubsub.Snapshot(), - pubsub.Snapshot(), - ], - ), - RuntimeError, - ) - pages = list(client.list_snapshots(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_snapshots_async_pager(): - client = SubscriberAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_snapshots), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - pubsub.ListSnapshotsResponse( - snapshots=[ - pubsub.Snapshot(), - pubsub.Snapshot(), - pubsub.Snapshot(), - ], - next_page_token='abc', - ), - pubsub.ListSnapshotsResponse( - snapshots=[], - next_page_token='def', - ), - pubsub.ListSnapshotsResponse( - snapshots=[ - pubsub.Snapshot(), - ], - next_page_token='ghi', - ), - pubsub.ListSnapshotsResponse( - snapshots=[ - pubsub.Snapshot(), - pubsub.Snapshot(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_snapshots(request={},) - assert async_pager.next_page_token == 'abc' - responses = [] - async for response in async_pager: # pragma: no branch - responses.append(response) - - assert len(responses) == 6 - assert all(isinstance(i, pubsub.Snapshot) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_snapshots_async_pages(): - client = SubscriberAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_snapshots), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - pubsub.ListSnapshotsResponse( - snapshots=[ - pubsub.Snapshot(), - pubsub.Snapshot(), - pubsub.Snapshot(), - ], - next_page_token='abc', - ), - pubsub.ListSnapshotsResponse( - snapshots=[], - next_page_token='def', - ), - pubsub.ListSnapshotsResponse( - snapshots=[ - pubsub.Snapshot(), - ], - next_page_token='ghi', - ), - pubsub.ListSnapshotsResponse( - snapshots=[ - pubsub.Snapshot(), - pubsub.Snapshot(), - ], - ), - RuntimeError, - ) - pages = [] - # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` - # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 - async for page_ in ( # pragma: no branch - await client.list_snapshots(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", [ - pubsub.CreateSnapshotRequest, - dict, -]) -def test_create_snapshot(request_type, transport: str = 'grpc'): - client = SubscriberClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_snapshot), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = pubsub.Snapshot( - name='name_value', - topic='topic_value', - ) - response = client.create_snapshot(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = pubsub.CreateSnapshotRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pubsub.Snapshot) - assert response.name == 'name_value' - assert response.topic == 'topic_value' - - -def test_create_snapshot_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SubscriberClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_snapshot), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.create_snapshot() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == pubsub.CreateSnapshotRequest() - - -def test_create_snapshot_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 = SubscriberClient( - 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 = pubsub.CreateSnapshotRequest( - name='name_value', - subscription='subscription_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_snapshot), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.create_snapshot(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == pubsub.CreateSnapshotRequest( - name='name_value', - subscription='subscription_value', - ) - -def test_create_snapshot_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = SubscriberClient( - 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_snapshot in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_snapshot] = mock_rpc - request = {} - client.create_snapshot(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.create_snapshot(request) - - # Establish that a new wrapper 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_snapshot_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SubscriberAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_snapshot), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(pubsub.Snapshot( - name='name_value', - topic='topic_value', - )) - response = await client.create_snapshot() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == pubsub.CreateSnapshotRequest() - -@pytest.mark.asyncio -async def test_create_snapshot_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 = SubscriberAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - 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_snapshot 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_snapshot] = mock_rpc - - request = {} - await client.create_snapshot(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.create_snapshot(request) - - # Establish that a new wrapper 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_snapshot_async(transport: str = 'grpc_asyncio', request_type=pubsub.CreateSnapshotRequest): - client = SubscriberAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_snapshot), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(pubsub.Snapshot( - name='name_value', - topic='topic_value', - )) - response = await client.create_snapshot(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = pubsub.CreateSnapshotRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pubsub.Snapshot) - assert response.name == 'name_value' - assert response.topic == 'topic_value' - - -@pytest.mark.asyncio -async def test_create_snapshot_async_from_dict(): - await test_create_snapshot_async(request_type=dict) - - -def test_create_snapshot_field_headers(): - client = SubscriberClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = pubsub.CreateSnapshotRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_snapshot), - '__call__') as call: - call.return_value = pubsub.Snapshot() - client.create_snapshot(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_create_snapshot_field_headers_async(): - client = SubscriberAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = pubsub.CreateSnapshotRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_snapshot), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(pubsub.Snapshot()) - await client.create_snapshot(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name_value', - ) in kw['metadata'] - - -def test_create_snapshot_flattened(): - client = SubscriberClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_snapshot), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = pubsub.Snapshot() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.create_snapshot( - name='name_value', - subscription='subscription_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - arg = args[0].subscription - mock_val = 'subscription_value' - assert arg == mock_val - - -def test_create_snapshot_flattened_error(): - client = SubscriberClient( - credentials=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_snapshot( - pubsub.CreateSnapshotRequest(), - name='name_value', - subscription='subscription_value', - ) - -@pytest.mark.asyncio -async def test_create_snapshot_flattened_async(): - client = SubscriberAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_snapshot), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = pubsub.Snapshot() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(pubsub.Snapshot()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.create_snapshot( - name='name_value', - subscription='subscription_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - arg = args[0].subscription - mock_val = 'subscription_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_create_snapshot_flattened_error_async(): - client = SubscriberAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.create_snapshot( - pubsub.CreateSnapshotRequest(), - name='name_value', - subscription='subscription_value', - ) - - -@pytest.mark.parametrize("request_type", [ - pubsub.UpdateSnapshotRequest, - dict, -]) -def test_update_snapshot(request_type, transport: str = 'grpc'): - client = SubscriberClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_snapshot), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = pubsub.Snapshot( - name='name_value', - topic='topic_value', - ) - response = client.update_snapshot(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = pubsub.UpdateSnapshotRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pubsub.Snapshot) - assert response.name == 'name_value' - assert response.topic == 'topic_value' - - -def test_update_snapshot_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SubscriberClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_snapshot), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.update_snapshot() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == pubsub.UpdateSnapshotRequest() - - -def test_update_snapshot_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 = SubscriberClient( - 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 = pubsub.UpdateSnapshotRequest( - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_snapshot), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.update_snapshot(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == pubsub.UpdateSnapshotRequest( - ) - -def test_update_snapshot_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = SubscriberClient( - 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_snapshot in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_snapshot] = mock_rpc - request = {} - client.update_snapshot(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.update_snapshot(request) - - # Establish that a new wrapper 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_snapshot_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SubscriberAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_snapshot), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(pubsub.Snapshot( - name='name_value', - topic='topic_value', - )) - response = await client.update_snapshot() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == pubsub.UpdateSnapshotRequest() - -@pytest.mark.asyncio -async def test_update_snapshot_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 = SubscriberAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - 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_snapshot 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_snapshot] = mock_rpc - - request = {} - await client.update_snapshot(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.update_snapshot(request) - - # Establish that a new wrapper 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_snapshot_async(transport: str = 'grpc_asyncio', request_type=pubsub.UpdateSnapshotRequest): - client = SubscriberAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_snapshot), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(pubsub.Snapshot( - name='name_value', - topic='topic_value', - )) - response = await client.update_snapshot(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = pubsub.UpdateSnapshotRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pubsub.Snapshot) - assert response.name == 'name_value' - assert response.topic == 'topic_value' - - -@pytest.mark.asyncio -async def test_update_snapshot_async_from_dict(): - await test_update_snapshot_async(request_type=dict) - - -def test_update_snapshot_field_headers(): - client = SubscriberClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = pubsub.UpdateSnapshotRequest() - - request.snapshot.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_snapshot), - '__call__') as call: - call.return_value = pubsub.Snapshot() - client.update_snapshot(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'snapshot.name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_snapshot_field_headers_async(): - client = SubscriberAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = pubsub.UpdateSnapshotRequest() - - request.snapshot.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_snapshot), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(pubsub.Snapshot()) - await client.update_snapshot(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'snapshot.name=name_value', - ) in kw['metadata'] - - -def test_update_snapshot_flattened(): - client = SubscriberClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_snapshot), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = pubsub.Snapshot() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.update_snapshot( - snapshot=pubsub.Snapshot(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].snapshot - mock_val = pubsub.Snapshot(name='name_value') - assert arg == mock_val - arg = args[0].update_mask - mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) - assert arg == mock_val - - -def test_update_snapshot_flattened_error(): - client = SubscriberClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.update_snapshot( - pubsub.UpdateSnapshotRequest(), - snapshot=pubsub.Snapshot(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - -@pytest.mark.asyncio -async def test_update_snapshot_flattened_async(): - client = SubscriberAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_snapshot), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = pubsub.Snapshot() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(pubsub.Snapshot()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.update_snapshot( - snapshot=pubsub.Snapshot(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].snapshot - mock_val = pubsub.Snapshot(name='name_value') - assert arg == mock_val - arg = args[0].update_mask - mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) - assert arg == mock_val - -@pytest.mark.asyncio -async def test_update_snapshot_flattened_error_async(): - client = SubscriberAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.update_snapshot( - pubsub.UpdateSnapshotRequest(), - snapshot=pubsub.Snapshot(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -@pytest.mark.parametrize("request_type", [ - pubsub.DeleteSnapshotRequest, - dict, -]) -def test_delete_snapshot(request_type, transport: str = 'grpc'): - client = SubscriberClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_snapshot), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = None - response = client.delete_snapshot(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = pubsub.DeleteSnapshotRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert response is None - - -def test_delete_snapshot_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SubscriberClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_snapshot), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.delete_snapshot() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == pubsub.DeleteSnapshotRequest() - - -def test_delete_snapshot_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 = SubscriberClient( - 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 = pubsub.DeleteSnapshotRequest( - snapshot='snapshot_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_snapshot), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.delete_snapshot(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == pubsub.DeleteSnapshotRequest( - snapshot='snapshot_value', - ) - -def test_delete_snapshot_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = SubscriberClient( - 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_snapshot in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_snapshot] = mock_rpc - request = {} - client.delete_snapshot(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.delete_snapshot(request) - - # Establish that a new wrapper 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_snapshot_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SubscriberAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_snapshot), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_snapshot() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == pubsub.DeleteSnapshotRequest() - -@pytest.mark.asyncio -async def test_delete_snapshot_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 = SubscriberAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - 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_snapshot 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_snapshot] = mock_rpc - - request = {} - await client.delete_snapshot(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.delete_snapshot(request) - - # Establish that a new wrapper 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_snapshot_async(transport: str = 'grpc_asyncio', request_type=pubsub.DeleteSnapshotRequest): - client = SubscriberAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_snapshot), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_snapshot(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = pubsub.DeleteSnapshotRequest() - 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_snapshot_async_from_dict(): - await test_delete_snapshot_async(request_type=dict) - - -def test_delete_snapshot_field_headers(): - client = SubscriberClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = pubsub.DeleteSnapshotRequest() - - request.snapshot = 'snapshot_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_snapshot), - '__call__') as call: - call.return_value = None - client.delete_snapshot(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'snapshot=snapshot_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_delete_snapshot_field_headers_async(): - client = SubscriberAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = pubsub.DeleteSnapshotRequest() - - request.snapshot = 'snapshot_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_snapshot), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_snapshot(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'snapshot=snapshot_value', - ) in kw['metadata'] - - -def test_delete_snapshot_flattened(): - client = SubscriberClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_snapshot), - '__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_snapshot( - snapshot='snapshot_value', - ) - - # 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].snapshot - mock_val = 'snapshot_value' - assert arg == mock_val - - -def test_delete_snapshot_flattened_error(): - client = SubscriberClient( - credentials=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_snapshot( - pubsub.DeleteSnapshotRequest(), - snapshot='snapshot_value', - ) - -@pytest.mark.asyncio -async def test_delete_snapshot_flattened_async(): - client = SubscriberAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_snapshot), - '__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_snapshot( - snapshot='snapshot_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].snapshot - mock_val = 'snapshot_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_delete_snapshot_flattened_error_async(): - client = SubscriberAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.delete_snapshot( - pubsub.DeleteSnapshotRequest(), - snapshot='snapshot_value', - ) - - -@pytest.mark.parametrize("request_type", [ - pubsub.SeekRequest, - dict, -]) -def test_seek(request_type, transport: str = 'grpc'): - client = SubscriberClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.seek), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = pubsub.SeekResponse( - ) - response = client.seek(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = pubsub.SeekRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pubsub.SeekResponse) - - -def test_seek_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SubscriberClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.seek), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.seek() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == pubsub.SeekRequest() - - -def test_seek_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 = SubscriberClient( - 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 = pubsub.SeekRequest( - subscription='subscription_value', - snapshot='snapshot_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.seek), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.seek(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == pubsub.SeekRequest( - subscription='subscription_value', - snapshot='snapshot_value', - ) - -def test_seek_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = SubscriberClient( - 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.seek in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.seek] = mock_rpc - request = {} - client.seek(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.seek(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_seek_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SubscriberAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.seek), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(pubsub.SeekResponse( - )) - response = await client.seek() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == pubsub.SeekRequest() - -@pytest.mark.asyncio -async def test_seek_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 = SubscriberAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - 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.seek 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.seek] = mock_rpc - - request = {} - await client.seek(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.seek(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_seek_async(transport: str = 'grpc_asyncio', request_type=pubsub.SeekRequest): - client = SubscriberAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.seek), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(pubsub.SeekResponse( - )) - response = await client.seek(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = pubsub.SeekRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pubsub.SeekResponse) - - -@pytest.mark.asyncio -async def test_seek_async_from_dict(): - await test_seek_async(request_type=dict) - - -def test_seek_field_headers(): - client = SubscriberClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = pubsub.SeekRequest() - - request.subscription = 'subscription_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.seek), - '__call__') as call: - call.return_value = pubsub.SeekResponse() - client.seek(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'subscription=subscription_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_seek_field_headers_async(): - client = SubscriberAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = pubsub.SeekRequest() - - request.subscription = 'subscription_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.seek), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(pubsub.SeekResponse()) - await client.seek(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'subscription=subscription_value', - ) in kw['metadata'] - - -@pytest.mark.parametrize("request_type", [ - pubsub.Subscription, - dict, -]) -def test_create_subscription_rest(request_type): - client = SubscriberClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/subscriptions/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 = pubsub.Subscription( - name='name_value', - topic='topic_value', - ack_deadline_seconds=2066, - retain_acked_messages=True, - enable_message_ordering=True, - filter='filter_value', - detached=True, - enable_exactly_once_delivery=True, - state=pubsub.Subscription.State.ACTIVE, - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = pubsub.Subscription.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.create_subscription(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pubsub.Subscription) - assert response.name == 'name_value' - assert response.topic == 'topic_value' - assert response.ack_deadline_seconds == 2066 - assert response.retain_acked_messages is True - assert response.enable_message_ordering is True - assert response.filter == 'filter_value' - assert response.detached is True - assert response.enable_exactly_once_delivery is True - assert response.state == pubsub.Subscription.State.ACTIVE - -def test_create_subscription_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 = SubscriberClient( - 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_subscription in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_subscription] = mock_rpc - - request = {} - client.create_subscription(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.create_subscription(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_subscription_rest_required_fields(request_type=pubsub.Subscription): - transport_class = transports.SubscriberRestTransport - - request_init = {} - request_init["name"] = "" - request_init["topic"] = "" - 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_subscription._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' - jsonified_request["topic"] = 'topic_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_subscription._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' - assert "topic" in jsonified_request - assert jsonified_request["topic"] == 'topic_value' - - client = SubscriberClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = pubsub.Subscription() - # 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': "put", - '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 = pubsub.Subscription.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.create_subscription(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_create_subscription_rest_unset_required_fields(): - transport = transports.SubscriberRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.create_subscription._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", "topic", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_create_subscription_rest_interceptors(null_interceptor): - transport = transports.SubscriberRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SubscriberRestInterceptor(), - ) - client = SubscriberClient(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.SubscriberRestInterceptor, "post_create_subscription") as post, \ - mock.patch.object(transports.SubscriberRestInterceptor, "pre_create_subscription") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = pubsub.Subscription.pb(pubsub.Subscription()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = pubsub.Subscription.to_json(pubsub.Subscription()) - - request = pubsub.Subscription() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = pubsub.Subscription() - - client.create_subscription(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_create_subscription_rest_bad_request(transport: str = 'rest', request_type=pubsub.Subscription): - client = SubscriberClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/subscriptions/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 = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.create_subscription(request) - - -def test_create_subscription_rest_flattened(): - client = SubscriberClient( - 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 = pubsub.Subscription() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/subscriptions/sample2'} - - # get truthy value for each flattened field - mock_args = dict( - name='name_value', - topic='topic_value', - push_config=pubsub.PushConfig(push_endpoint='push_endpoint_value'), - ack_deadline_seconds=2066, - ) - 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 = pubsub.Subscription.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.create_subscription(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1/{name=projects/*/subscriptions/*}" % client.transport._host, args[1]) - - -def test_create_subscription_rest_flattened_error(transport: str = 'rest'): - client = SubscriberClient( - 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_subscription( - pubsub.Subscription(), - name='name_value', - topic='topic_value', - push_config=pubsub.PushConfig(push_endpoint='push_endpoint_value'), - ack_deadline_seconds=2066, - ) - - -def test_create_subscription_rest_error(): - client = SubscriberClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - pubsub.GetSubscriptionRequest, - dict, -]) -def test_get_subscription_rest(request_type): - client = SubscriberClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'subscription': 'projects/sample1/subscriptions/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 = pubsub.Subscription( - name='name_value', - topic='topic_value', - ack_deadline_seconds=2066, - retain_acked_messages=True, - enable_message_ordering=True, - filter='filter_value', - detached=True, - enable_exactly_once_delivery=True, - state=pubsub.Subscription.State.ACTIVE, - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = pubsub.Subscription.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.get_subscription(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pubsub.Subscription) - assert response.name == 'name_value' - assert response.topic == 'topic_value' - assert response.ack_deadline_seconds == 2066 - assert response.retain_acked_messages is True - assert response.enable_message_ordering is True - assert response.filter == 'filter_value' - assert response.detached is True - assert response.enable_exactly_once_delivery is True - assert response.state == pubsub.Subscription.State.ACTIVE - -def test_get_subscription_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 = SubscriberClient( - 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_subscription in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_subscription] = mock_rpc - - request = {} - client.get_subscription(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_subscription(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_subscription_rest_required_fields(request_type=pubsub.GetSubscriptionRequest): - transport_class = transports.SubscriberRestTransport - - request_init = {} - request_init["subscription"] = "" - 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_subscription._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["subscription"] = 'subscription_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_subscription._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "subscription" in jsonified_request - assert jsonified_request["subscription"] == 'subscription_value' - - client = SubscriberClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = pubsub.Subscription() - # 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 = pubsub.Subscription.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.get_subscription(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_get_subscription_rest_unset_required_fields(): - transport = transports.SubscriberRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.get_subscription._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("subscription", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_subscription_rest_interceptors(null_interceptor): - transport = transports.SubscriberRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SubscriberRestInterceptor(), - ) - client = SubscriberClient(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.SubscriberRestInterceptor, "post_get_subscription") as post, \ - mock.patch.object(transports.SubscriberRestInterceptor, "pre_get_subscription") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = pubsub.GetSubscriptionRequest.pb(pubsub.GetSubscriptionRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = pubsub.Subscription.to_json(pubsub.Subscription()) - - request = pubsub.GetSubscriptionRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = pubsub.Subscription() - - client.get_subscription(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_subscription_rest_bad_request(transport: str = 'rest', request_type=pubsub.GetSubscriptionRequest): - client = SubscriberClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'subscription': 'projects/sample1/subscriptions/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 = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_subscription(request) - - -def test_get_subscription_rest_flattened(): - client = SubscriberClient( - 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 = pubsub.Subscription() - - # get arguments that satisfy an http rule for this method - sample_request = {'subscription': 'projects/sample1/subscriptions/sample2'} - - # get truthy value for each flattened field - mock_args = dict( - subscription='subscription_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 = pubsub.Subscription.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.get_subscription(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1/{subscription=projects/*/subscriptions/*}" % client.transport._host, args[1]) - - -def test_get_subscription_rest_flattened_error(transport: str = 'rest'): - client = SubscriberClient( - 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_subscription( - pubsub.GetSubscriptionRequest(), - subscription='subscription_value', - ) - - -def test_get_subscription_rest_error(): - client = SubscriberClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - pubsub.UpdateSubscriptionRequest, - dict, -]) -def test_update_subscription_rest(request_type): - client = SubscriberClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'subscription': {'name': 'projects/sample1/subscriptions/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 = pubsub.Subscription( - name='name_value', - topic='topic_value', - ack_deadline_seconds=2066, - retain_acked_messages=True, - enable_message_ordering=True, - filter='filter_value', - detached=True, - enable_exactly_once_delivery=True, - state=pubsub.Subscription.State.ACTIVE, - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = pubsub.Subscription.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.update_subscription(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pubsub.Subscription) - assert response.name == 'name_value' - assert response.topic == 'topic_value' - assert response.ack_deadline_seconds == 2066 - assert response.retain_acked_messages is True - assert response.enable_message_ordering is True - assert response.filter == 'filter_value' - assert response.detached is True - assert response.enable_exactly_once_delivery is True - assert response.state == pubsub.Subscription.State.ACTIVE - -def test_update_subscription_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 = SubscriberClient( - 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_subscription in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_subscription] = mock_rpc - - request = {} - client.update_subscription(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.update_subscription(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -def test_update_subscription_rest_required_fields(request_type=pubsub.UpdateSubscriptionRequest): - transport_class = transports.SubscriberRestTransport - - request_init = {} - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_subscription._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_subscription._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - - client = SubscriberClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = pubsub.Subscription() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "patch", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = pubsub.Subscription.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.update_subscription(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_update_subscription_rest_unset_required_fields(): - transport = transports.SubscriberRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.update_subscription._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("subscription", "updateMask", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_subscription_rest_interceptors(null_interceptor): - transport = transports.SubscriberRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SubscriberRestInterceptor(), - ) - client = SubscriberClient(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.SubscriberRestInterceptor, "post_update_subscription") as post, \ - mock.patch.object(transports.SubscriberRestInterceptor, "pre_update_subscription") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = pubsub.UpdateSubscriptionRequest.pb(pubsub.UpdateSubscriptionRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = pubsub.Subscription.to_json(pubsub.Subscription()) - - request = pubsub.UpdateSubscriptionRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = pubsub.Subscription() - - client.update_subscription(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_update_subscription_rest_bad_request(transport: str = 'rest', request_type=pubsub.UpdateSubscriptionRequest): - client = SubscriberClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'subscription': {'name': 'projects/sample1/subscriptions/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 = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.update_subscription(request) - - -def test_update_subscription_rest_flattened(): - client = SubscriberClient( - 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 = pubsub.Subscription() - - # get arguments that satisfy an http rule for this method - sample_request = {'subscription': {'name': 'projects/sample1/subscriptions/sample2'}} - - # get truthy value for each flattened field - mock_args = dict( - subscription=pubsub.Subscription(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = pubsub.Subscription.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.update_subscription(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1/{subscription.name=projects/*/subscriptions/*}" % client.transport._host, args[1]) - - -def test_update_subscription_rest_flattened_error(transport: str = 'rest'): - client = SubscriberClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.update_subscription( - pubsub.UpdateSubscriptionRequest(), - subscription=pubsub.Subscription(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -def test_update_subscription_rest_error(): - client = SubscriberClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - pubsub.ListSubscriptionsRequest, - dict, -]) -def test_list_subscriptions_rest(request_type): - client = SubscriberClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'project': 'projects/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 = pubsub.ListSubscriptionsResponse( - next_page_token='next_page_token_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = pubsub.ListSubscriptionsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.list_subscriptions(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListSubscriptionsPager) - assert response.next_page_token == 'next_page_token_value' - -def test_list_subscriptions_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 = SubscriberClient( - 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_subscriptions in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_subscriptions] = mock_rpc - - request = {} - client.list_subscriptions(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_subscriptions(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_subscriptions_rest_required_fields(request_type=pubsub.ListSubscriptionsRequest): - transport_class = transports.SubscriberRestTransport - - request_init = {} - request_init["project"] = "" - 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_subscriptions._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["project"] = 'project_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_subscriptions._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 "project" in jsonified_request - assert jsonified_request["project"] == 'project_value' - - client = SubscriberClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = pubsub.ListSubscriptionsResponse() - # 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 = pubsub.ListSubscriptionsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.list_subscriptions(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_list_subscriptions_rest_unset_required_fields(): - transport = transports.SubscriberRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.list_subscriptions._get_unset_required_fields({}) - assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("project", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_subscriptions_rest_interceptors(null_interceptor): - transport = transports.SubscriberRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SubscriberRestInterceptor(), - ) - client = SubscriberClient(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.SubscriberRestInterceptor, "post_list_subscriptions") as post, \ - mock.patch.object(transports.SubscriberRestInterceptor, "pre_list_subscriptions") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = pubsub.ListSubscriptionsRequest.pb(pubsub.ListSubscriptionsRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = pubsub.ListSubscriptionsResponse.to_json(pubsub.ListSubscriptionsResponse()) - - request = pubsub.ListSubscriptionsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = pubsub.ListSubscriptionsResponse() - - client.list_subscriptions(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_subscriptions_rest_bad_request(transport: str = 'rest', request_type=pubsub.ListSubscriptionsRequest): - client = SubscriberClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'project': 'projects/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 = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_subscriptions(request) - - -def test_list_subscriptions_rest_flattened(): - client = SubscriberClient( - 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 = pubsub.ListSubscriptionsResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'project': 'projects/sample1'} - - # get truthy value for each flattened field - mock_args = dict( - project='project_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 = pubsub.ListSubscriptionsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.list_subscriptions(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1/{project=projects/*}/subscriptions" % client.transport._host, args[1]) - - -def test_list_subscriptions_rest_flattened_error(transport: str = 'rest'): - client = SubscriberClient( - 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_subscriptions( - pubsub.ListSubscriptionsRequest(), - project='project_value', - ) - - -def test_list_subscriptions_rest_pager(transport: str = 'rest'): - client = SubscriberClient( - 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 = ( - pubsub.ListSubscriptionsResponse( - subscriptions=[ - pubsub.Subscription(), - pubsub.Subscription(), - pubsub.Subscription(), - ], - next_page_token='abc', - ), - pubsub.ListSubscriptionsResponse( - subscriptions=[], - next_page_token='def', - ), - pubsub.ListSubscriptionsResponse( - subscriptions=[ - pubsub.Subscription(), - ], - next_page_token='ghi', - ), - pubsub.ListSubscriptionsResponse( - subscriptions=[ - pubsub.Subscription(), - pubsub.Subscription(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(pubsub.ListSubscriptionsResponse.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 = {'project': 'projects/sample1'} - - pager = client.list_subscriptions(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, pubsub.Subscription) - for i in results) - - pages = list(client.list_subscriptions(request=sample_request).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -@pytest.mark.parametrize("request_type", [ - pubsub.DeleteSubscriptionRequest, - dict, -]) -def test_delete_subscription_rest(request_type): - client = SubscriberClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'subscription': 'projects/sample1/subscriptions/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 = Response() - response_value.status_code = 200 - json_return_value = '' - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.delete_subscription(request) - - # Establish that the response is the type that we expect. - assert response is None - -def test_delete_subscription_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 = SubscriberClient( - 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_subscription in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_subscription] = mock_rpc - - request = {} - client.delete_subscription(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.delete_subscription(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_subscription_rest_required_fields(request_type=pubsub.DeleteSubscriptionRequest): - transport_class = transports.SubscriberRestTransport - - request_init = {} - request_init["subscription"] = "" - 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_subscription._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["subscription"] = 'subscription_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_subscription._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "subscription" in jsonified_request - assert jsonified_request["subscription"] == 'subscription_value' - - client = SubscriberClient( - 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 - - response = client.delete_subscription(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_delete_subscription_rest_unset_required_fields(): - transport = transports.SubscriberRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.delete_subscription._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("subscription", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_delete_subscription_rest_interceptors(null_interceptor): - transport = transports.SubscriberRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SubscriberRestInterceptor(), - ) - client = SubscriberClient(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.SubscriberRestInterceptor, "pre_delete_subscription") as pre: - pre.assert_not_called() - pb_message = pubsub.DeleteSubscriptionRequest.pb(pubsub.DeleteSubscriptionRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - - request = pubsub.DeleteSubscriptionRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - - client.delete_subscription(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - - -def test_delete_subscription_rest_bad_request(transport: str = 'rest', request_type=pubsub.DeleteSubscriptionRequest): - client = SubscriberClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'subscription': 'projects/sample1/subscriptions/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 = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.delete_subscription(request) - - -def test_delete_subscription_rest_flattened(): - client = SubscriberClient( - 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 = {'subscription': 'projects/sample1/subscriptions/sample2'} - - # get truthy value for each flattened field - mock_args = dict( - subscription='subscription_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 - - client.delete_subscription(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1/{subscription=projects/*/subscriptions/*}" % client.transport._host, args[1]) - - -def test_delete_subscription_rest_flattened_error(transport: str = 'rest'): - client = SubscriberClient( - 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_subscription( - pubsub.DeleteSubscriptionRequest(), - subscription='subscription_value', - ) - - -def test_delete_subscription_rest_error(): - client = SubscriberClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - pubsub.ModifyAckDeadlineRequest, - dict, -]) -def test_modify_ack_deadline_rest(request_type): - client = SubscriberClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'subscription': 'projects/sample1/subscriptions/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 = Response() - response_value.status_code = 200 - json_return_value = '' - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.modify_ack_deadline(request) - - # Establish that the response is the type that we expect. - assert response is None - -def test_modify_ack_deadline_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 = SubscriberClient( - 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.modify_ack_deadline in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.modify_ack_deadline] = mock_rpc - - request = {} - client.modify_ack_deadline(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.modify_ack_deadline(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_modify_ack_deadline_rest_required_fields(request_type=pubsub.ModifyAckDeadlineRequest): - transport_class = transports.SubscriberRestTransport - - request_init = {} - request_init["subscription"] = "" - request_init["ack_ids"] = "" - request_init["ack_deadline_seconds"] = 0 - 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()).modify_ack_deadline._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["subscription"] = 'subscription_value' - jsonified_request["ackIds"] = 'ack_ids_value' - jsonified_request["ackDeadlineSeconds"] = 2066 - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).modify_ack_deadline._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "subscription" in jsonified_request - assert jsonified_request["subscription"] == 'subscription_value' - assert "ackIds" in jsonified_request - assert jsonified_request["ackIds"] == 'ack_ids_value' - assert "ackDeadlineSeconds" in jsonified_request - assert jsonified_request["ackDeadlineSeconds"] == 2066 - - client = SubscriberClient( - 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': "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 = '' - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.modify_ack_deadline(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_modify_ack_deadline_rest_unset_required_fields(): - transport = transports.SubscriberRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.modify_ack_deadline._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("subscription", "ackIds", "ackDeadlineSeconds", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_modify_ack_deadline_rest_interceptors(null_interceptor): - transport = transports.SubscriberRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SubscriberRestInterceptor(), - ) - client = SubscriberClient(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.SubscriberRestInterceptor, "pre_modify_ack_deadline") as pre: - pre.assert_not_called() - pb_message = pubsub.ModifyAckDeadlineRequest.pb(pubsub.ModifyAckDeadlineRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - - request = pubsub.ModifyAckDeadlineRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - - client.modify_ack_deadline(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - - -def test_modify_ack_deadline_rest_bad_request(transport: str = 'rest', request_type=pubsub.ModifyAckDeadlineRequest): - client = SubscriberClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'subscription': 'projects/sample1/subscriptions/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 = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.modify_ack_deadline(request) - - -def test_modify_ack_deadline_rest_flattened(): - client = SubscriberClient( - 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 = {'subscription': 'projects/sample1/subscriptions/sample2'} - - # get truthy value for each flattened field - mock_args = dict( - subscription='subscription_value', - ack_ids=['ack_ids_value'], - ack_deadline_seconds=2066, - ) - 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 - - client.modify_ack_deadline(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1/{subscription=projects/*/subscriptions/*}:modifyAckDeadline" % client.transport._host, args[1]) - - -def test_modify_ack_deadline_rest_flattened_error(transport: str = 'rest'): - client = SubscriberClient( - 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.modify_ack_deadline( - pubsub.ModifyAckDeadlineRequest(), - subscription='subscription_value', - ack_ids=['ack_ids_value'], - ack_deadline_seconds=2066, - ) - - -def test_modify_ack_deadline_rest_error(): - client = SubscriberClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - pubsub.AcknowledgeRequest, - dict, -]) -def test_acknowledge_rest(request_type): - client = SubscriberClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'subscription': 'projects/sample1/subscriptions/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 = Response() - response_value.status_code = 200 - json_return_value = '' - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.acknowledge(request) - - # Establish that the response is the type that we expect. - assert response is None - -def test_acknowledge_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 = SubscriberClient( - 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.acknowledge in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.acknowledge] = mock_rpc - - request = {} - client.acknowledge(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.acknowledge(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_acknowledge_rest_required_fields(request_type=pubsub.AcknowledgeRequest): - transport_class = transports.SubscriberRestTransport - - request_init = {} - request_init["subscription"] = "" - request_init["ack_ids"] = "" - 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()).acknowledge._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["subscription"] = 'subscription_value' - jsonified_request["ackIds"] = 'ack_ids_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).acknowledge._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "subscription" in jsonified_request - assert jsonified_request["subscription"] == 'subscription_value' - assert "ackIds" in jsonified_request - assert jsonified_request["ackIds"] == 'ack_ids_value' - - client = SubscriberClient( - 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': "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 = '' - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.acknowledge(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_acknowledge_rest_unset_required_fields(): - transport = transports.SubscriberRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.acknowledge._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("subscription", "ackIds", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_acknowledge_rest_interceptors(null_interceptor): - transport = transports.SubscriberRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SubscriberRestInterceptor(), - ) - client = SubscriberClient(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.SubscriberRestInterceptor, "pre_acknowledge") as pre: - pre.assert_not_called() - pb_message = pubsub.AcknowledgeRequest.pb(pubsub.AcknowledgeRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - - request = pubsub.AcknowledgeRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - - client.acknowledge(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - - -def test_acknowledge_rest_bad_request(transport: str = 'rest', request_type=pubsub.AcknowledgeRequest): - client = SubscriberClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'subscription': 'projects/sample1/subscriptions/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 = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.acknowledge(request) - - -def test_acknowledge_rest_flattened(): - client = SubscriberClient( - 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 = {'subscription': 'projects/sample1/subscriptions/sample2'} - - # get truthy value for each flattened field - mock_args = dict( - subscription='subscription_value', - ack_ids=['ack_ids_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 - - client.acknowledge(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1/{subscription=projects/*/subscriptions/*}:acknowledge" % client.transport._host, args[1]) - - -def test_acknowledge_rest_flattened_error(transport: str = 'rest'): - client = SubscriberClient( - 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.acknowledge( - pubsub.AcknowledgeRequest(), - subscription='subscription_value', - ack_ids=['ack_ids_value'], - ) - - -def test_acknowledge_rest_error(): - client = SubscriberClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - pubsub.PullRequest, - dict, -]) -def test_pull_rest(request_type): - client = SubscriberClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'subscription': 'projects/sample1/subscriptions/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 = pubsub.PullResponse( - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = pubsub.PullResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.pull(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pubsub.PullResponse) - -def test_pull_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 = SubscriberClient( - 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.pull in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.pull] = mock_rpc - - request = {} - client.pull(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.pull(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_pull_rest_required_fields(request_type=pubsub.PullRequest): - transport_class = transports.SubscriberRestTransport - - request_init = {} - request_init["subscription"] = "" - request_init["max_messages"] = 0 - 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()).pull._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["subscription"] = 'subscription_value' - jsonified_request["maxMessages"] = 1277 - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).pull._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "subscription" in jsonified_request - assert jsonified_request["subscription"] == 'subscription_value' - assert "maxMessages" in jsonified_request - assert jsonified_request["maxMessages"] == 1277 - - client = SubscriberClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = pubsub.PullResponse() - # 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 = pubsub.PullResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.pull(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_pull_rest_unset_required_fields(): - transport = transports.SubscriberRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.pull._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("subscription", "maxMessages", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_pull_rest_interceptors(null_interceptor): - transport = transports.SubscriberRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SubscriberRestInterceptor(), - ) - client = SubscriberClient(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.SubscriberRestInterceptor, "post_pull") as post, \ - mock.patch.object(transports.SubscriberRestInterceptor, "pre_pull") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = pubsub.PullRequest.pb(pubsub.PullRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = pubsub.PullResponse.to_json(pubsub.PullResponse()) - - request = pubsub.PullRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = pubsub.PullResponse() - - client.pull(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_pull_rest_bad_request(transport: str = 'rest', request_type=pubsub.PullRequest): - client = SubscriberClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'subscription': 'projects/sample1/subscriptions/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 = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.pull(request) - - -def test_pull_rest_flattened(): - client = SubscriberClient( - 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 = pubsub.PullResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'subscription': 'projects/sample1/subscriptions/sample2'} - - # get truthy value for each flattened field - mock_args = dict( - subscription='subscription_value', - return_immediately=True, - max_messages=1277, - ) - 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 = pubsub.PullResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.pull(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1/{subscription=projects/*/subscriptions/*}:pull" % client.transport._host, args[1]) - - -def test_pull_rest_flattened_error(transport: str = 'rest'): - client = SubscriberClient( - 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.pull( - pubsub.PullRequest(), - subscription='subscription_value', - return_immediately=True, - max_messages=1277, - ) - - -def test_pull_rest_error(): - client = SubscriberClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -def test_streaming_pull_rest_no_http_options(): - client = SubscriberClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request = pubsub.StreamingPullRequest() - requests = [request] - with pytest.raises(RuntimeError): - client.streaming_pull(requests) - - -@pytest.mark.parametrize("request_type", [ - pubsub.ModifyPushConfigRequest, - dict, -]) -def test_modify_push_config_rest(request_type): - client = SubscriberClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'subscription': 'projects/sample1/subscriptions/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 = Response() - response_value.status_code = 200 - json_return_value = '' - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.modify_push_config(request) - - # Establish that the response is the type that we expect. - assert response is None - -def test_modify_push_config_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = SubscriberClient( - 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.modify_push_config in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.modify_push_config] = mock_rpc - - request = {} - client.modify_push_config(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.modify_push_config(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -def test_modify_push_config_rest_required_fields(request_type=pubsub.ModifyPushConfigRequest): - transport_class = transports.SubscriberRestTransport - - request_init = {} - request_init["subscription"] = "" - 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()).modify_push_config._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["subscription"] = 'subscription_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).modify_push_config._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "subscription" in jsonified_request - assert jsonified_request["subscription"] == 'subscription_value' - - client = SubscriberClient( - 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': "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 = '' - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.modify_push_config(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_modify_push_config_rest_unset_required_fields(): - transport = transports.SubscriberRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.modify_push_config._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("subscription", "pushConfig", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_modify_push_config_rest_interceptors(null_interceptor): - transport = transports.SubscriberRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SubscriberRestInterceptor(), - ) - client = SubscriberClient(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.SubscriberRestInterceptor, "pre_modify_push_config") as pre: - pre.assert_not_called() - pb_message = pubsub.ModifyPushConfigRequest.pb(pubsub.ModifyPushConfigRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - - request = pubsub.ModifyPushConfigRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - - client.modify_push_config(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - - -def test_modify_push_config_rest_bad_request(transport: str = 'rest', request_type=pubsub.ModifyPushConfigRequest): - client = SubscriberClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'subscription': 'projects/sample1/subscriptions/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 = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.modify_push_config(request) - - -def test_modify_push_config_rest_flattened(): - client = SubscriberClient( - 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 = {'subscription': 'projects/sample1/subscriptions/sample2'} - - # get truthy value for each flattened field - mock_args = dict( - subscription='subscription_value', - push_config=pubsub.PushConfig(push_endpoint='push_endpoint_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 - - client.modify_push_config(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1/{subscription=projects/*/subscriptions/*}:modifyPushConfig" % client.transport._host, args[1]) - - -def test_modify_push_config_rest_flattened_error(transport: str = 'rest'): - client = SubscriberClient( - 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.modify_push_config( - pubsub.ModifyPushConfigRequest(), - subscription='subscription_value', - push_config=pubsub.PushConfig(push_endpoint='push_endpoint_value'), - ) - - -def test_modify_push_config_rest_error(): - client = SubscriberClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - pubsub.GetSnapshotRequest, - dict, -]) -def test_get_snapshot_rest(request_type): - client = SubscriberClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'snapshot': 'projects/sample1/snapshots/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 = pubsub.Snapshot( - name='name_value', - topic='topic_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = pubsub.Snapshot.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.get_snapshot(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pubsub.Snapshot) - assert response.name == 'name_value' - assert response.topic == 'topic_value' - -def test_get_snapshot_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 = SubscriberClient( - 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_snapshot in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_snapshot] = mock_rpc - - request = {} - client.get_snapshot(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_snapshot(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_snapshot_rest_required_fields(request_type=pubsub.GetSnapshotRequest): - transport_class = transports.SubscriberRestTransport - - request_init = {} - request_init["snapshot"] = "" - 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_snapshot._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["snapshot"] = 'snapshot_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_snapshot._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "snapshot" in jsonified_request - assert jsonified_request["snapshot"] == 'snapshot_value' - - client = SubscriberClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = pubsub.Snapshot() - # 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 = pubsub.Snapshot.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.get_snapshot(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_get_snapshot_rest_unset_required_fields(): - transport = transports.SubscriberRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.get_snapshot._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("snapshot", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_snapshot_rest_interceptors(null_interceptor): - transport = transports.SubscriberRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SubscriberRestInterceptor(), - ) - client = SubscriberClient(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.SubscriberRestInterceptor, "post_get_snapshot") as post, \ - mock.patch.object(transports.SubscriberRestInterceptor, "pre_get_snapshot") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = pubsub.GetSnapshotRequest.pb(pubsub.GetSnapshotRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = pubsub.Snapshot.to_json(pubsub.Snapshot()) - - request = pubsub.GetSnapshotRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = pubsub.Snapshot() - - client.get_snapshot(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_snapshot_rest_bad_request(transport: str = 'rest', request_type=pubsub.GetSnapshotRequest): - client = SubscriberClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'snapshot': 'projects/sample1/snapshots/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 = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_snapshot(request) - - -def test_get_snapshot_rest_flattened(): - client = SubscriberClient( - 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 = pubsub.Snapshot() - - # get arguments that satisfy an http rule for this method - sample_request = {'snapshot': 'projects/sample1/snapshots/sample2'} - - # get truthy value for each flattened field - mock_args = dict( - snapshot='snapshot_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 = pubsub.Snapshot.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.get_snapshot(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1/{snapshot=projects/*/snapshots/*}" % client.transport._host, args[1]) - - -def test_get_snapshot_rest_flattened_error(transport: str = 'rest'): - client = SubscriberClient( - 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_snapshot( - pubsub.GetSnapshotRequest(), - snapshot='snapshot_value', - ) - - -def test_get_snapshot_rest_error(): - client = SubscriberClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - pubsub.ListSnapshotsRequest, - dict, -]) -def test_list_snapshots_rest(request_type): - client = SubscriberClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'project': 'projects/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 = pubsub.ListSnapshotsResponse( - next_page_token='next_page_token_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = pubsub.ListSnapshotsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.list_snapshots(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListSnapshotsPager) - assert response.next_page_token == 'next_page_token_value' - -def test_list_snapshots_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 = SubscriberClient( - 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_snapshots in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_snapshots] = mock_rpc - - request = {} - client.list_snapshots(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_snapshots(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_snapshots_rest_required_fields(request_type=pubsub.ListSnapshotsRequest): - transport_class = transports.SubscriberRestTransport - - request_init = {} - request_init["project"] = "" - 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_snapshots._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["project"] = 'project_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_snapshots._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 "project" in jsonified_request - assert jsonified_request["project"] == 'project_value' - - client = SubscriberClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = pubsub.ListSnapshotsResponse() - # 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 = pubsub.ListSnapshotsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.list_snapshots(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_list_snapshots_rest_unset_required_fields(): - transport = transports.SubscriberRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.list_snapshots._get_unset_required_fields({}) - assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("project", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_snapshots_rest_interceptors(null_interceptor): - transport = transports.SubscriberRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SubscriberRestInterceptor(), - ) - client = SubscriberClient(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.SubscriberRestInterceptor, "post_list_snapshots") as post, \ - mock.patch.object(transports.SubscriberRestInterceptor, "pre_list_snapshots") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = pubsub.ListSnapshotsRequest.pb(pubsub.ListSnapshotsRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = pubsub.ListSnapshotsResponse.to_json(pubsub.ListSnapshotsResponse()) - - request = pubsub.ListSnapshotsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = pubsub.ListSnapshotsResponse() - - client.list_snapshots(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_snapshots_rest_bad_request(transport: str = 'rest', request_type=pubsub.ListSnapshotsRequest): - client = SubscriberClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'project': 'projects/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 = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_snapshots(request) - - -def test_list_snapshots_rest_flattened(): - client = SubscriberClient( - 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 = pubsub.ListSnapshotsResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'project': 'projects/sample1'} - - # get truthy value for each flattened field - mock_args = dict( - project='project_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 = pubsub.ListSnapshotsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.list_snapshots(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1/{project=projects/*}/snapshots" % client.transport._host, args[1]) - - -def test_list_snapshots_rest_flattened_error(transport: str = 'rest'): - client = SubscriberClient( - 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_snapshots( - pubsub.ListSnapshotsRequest(), - project='project_value', - ) - - -def test_list_snapshots_rest_pager(transport: str = 'rest'): - client = SubscriberClient( - 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 = ( - pubsub.ListSnapshotsResponse( - snapshots=[ - pubsub.Snapshot(), - pubsub.Snapshot(), - pubsub.Snapshot(), - ], - next_page_token='abc', - ), - pubsub.ListSnapshotsResponse( - snapshots=[], - next_page_token='def', - ), - pubsub.ListSnapshotsResponse( - snapshots=[ - pubsub.Snapshot(), - ], - next_page_token='ghi', - ), - pubsub.ListSnapshotsResponse( - snapshots=[ - pubsub.Snapshot(), - pubsub.Snapshot(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(pubsub.ListSnapshotsResponse.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 = {'project': 'projects/sample1'} - - pager = client.list_snapshots(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, pubsub.Snapshot) - for i in results) - - pages = list(client.list_snapshots(request=sample_request).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -@pytest.mark.parametrize("request_type", [ - pubsub.CreateSnapshotRequest, - dict, -]) -def test_create_snapshot_rest(request_type): - client = SubscriberClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/snapshots/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 = pubsub.Snapshot( - name='name_value', - topic='topic_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = pubsub.Snapshot.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.create_snapshot(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pubsub.Snapshot) - assert response.name == 'name_value' - assert response.topic == 'topic_value' - -def test_create_snapshot_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 = SubscriberClient( - 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_snapshot in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_snapshot] = mock_rpc - - request = {} - client.create_snapshot(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.create_snapshot(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_snapshot_rest_required_fields(request_type=pubsub.CreateSnapshotRequest): - transport_class = transports.SubscriberRestTransport - - request_init = {} - request_init["name"] = "" - request_init["subscription"] = "" - 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_snapshot._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' - jsonified_request["subscription"] = 'subscription_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_snapshot._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' - assert "subscription" in jsonified_request - assert jsonified_request["subscription"] == 'subscription_value' - - client = SubscriberClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = pubsub.Snapshot() - # 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': "put", - '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 = pubsub.Snapshot.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.create_snapshot(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_create_snapshot_rest_unset_required_fields(): - transport = transports.SubscriberRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.create_snapshot._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", "subscription", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_create_snapshot_rest_interceptors(null_interceptor): - transport = transports.SubscriberRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SubscriberRestInterceptor(), - ) - client = SubscriberClient(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.SubscriberRestInterceptor, "post_create_snapshot") as post, \ - mock.patch.object(transports.SubscriberRestInterceptor, "pre_create_snapshot") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = pubsub.CreateSnapshotRequest.pb(pubsub.CreateSnapshotRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = pubsub.Snapshot.to_json(pubsub.Snapshot()) - - request = pubsub.CreateSnapshotRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = pubsub.Snapshot() - - client.create_snapshot(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_create_snapshot_rest_bad_request(transport: str = 'rest', request_type=pubsub.CreateSnapshotRequest): - client = SubscriberClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/snapshots/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 = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.create_snapshot(request) - - -def test_create_snapshot_rest_flattened(): - client = SubscriberClient( - 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 = pubsub.Snapshot() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/snapshots/sample2'} - - # get truthy value for each flattened field - mock_args = dict( - name='name_value', - subscription='subscription_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 = pubsub.Snapshot.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.create_snapshot(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1/{name=projects/*/snapshots/*}" % client.transport._host, args[1]) - - -def test_create_snapshot_rest_flattened_error(transport: str = 'rest'): - client = SubscriberClient( - 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_snapshot( - pubsub.CreateSnapshotRequest(), - name='name_value', - subscription='subscription_value', - ) - - -def test_create_snapshot_rest_error(): - client = SubscriberClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - pubsub.UpdateSnapshotRequest, - dict, -]) -def test_update_snapshot_rest(request_type): - client = SubscriberClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'snapshot': {'name': 'projects/sample1/snapshots/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 = pubsub.Snapshot( - name='name_value', - topic='topic_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = pubsub.Snapshot.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.update_snapshot(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pubsub.Snapshot) - assert response.name == 'name_value' - assert response.topic == 'topic_value' - -def test_update_snapshot_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 = SubscriberClient( - 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_snapshot in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_snapshot] = mock_rpc - - request = {} - client.update_snapshot(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.update_snapshot(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -def test_update_snapshot_rest_required_fields(request_type=pubsub.UpdateSnapshotRequest): - transport_class = transports.SubscriberRestTransport - - request_init = {} - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_snapshot._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_snapshot._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - - client = SubscriberClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = pubsub.Snapshot() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "patch", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = pubsub.Snapshot.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.update_snapshot(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_update_snapshot_rest_unset_required_fields(): - transport = transports.SubscriberRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.update_snapshot._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("snapshot", "updateMask", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_snapshot_rest_interceptors(null_interceptor): - transport = transports.SubscriberRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SubscriberRestInterceptor(), - ) - client = SubscriberClient(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.SubscriberRestInterceptor, "post_update_snapshot") as post, \ - mock.patch.object(transports.SubscriberRestInterceptor, "pre_update_snapshot") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = pubsub.UpdateSnapshotRequest.pb(pubsub.UpdateSnapshotRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = pubsub.Snapshot.to_json(pubsub.Snapshot()) - - request = pubsub.UpdateSnapshotRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = pubsub.Snapshot() - - client.update_snapshot(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_update_snapshot_rest_bad_request(transport: str = 'rest', request_type=pubsub.UpdateSnapshotRequest): - client = SubscriberClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'snapshot': {'name': 'projects/sample1/snapshots/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 = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.update_snapshot(request) - - -def test_update_snapshot_rest_flattened(): - client = SubscriberClient( - 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 = pubsub.Snapshot() - - # get arguments that satisfy an http rule for this method - sample_request = {'snapshot': {'name': 'projects/sample1/snapshots/sample2'}} - - # get truthy value for each flattened field - mock_args = dict( - snapshot=pubsub.Snapshot(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = pubsub.Snapshot.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.update_snapshot(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1/{snapshot.name=projects/*/snapshots/*}" % client.transport._host, args[1]) - - -def test_update_snapshot_rest_flattened_error(transport: str = 'rest'): - client = SubscriberClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.update_snapshot( - pubsub.UpdateSnapshotRequest(), - snapshot=pubsub.Snapshot(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -def test_update_snapshot_rest_error(): - client = SubscriberClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - pubsub.DeleteSnapshotRequest, - dict, -]) -def test_delete_snapshot_rest(request_type): - client = SubscriberClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'snapshot': 'projects/sample1/snapshots/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 = Response() - response_value.status_code = 200 - json_return_value = '' - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.delete_snapshot(request) - - # Establish that the response is the type that we expect. - assert response is None - -def test_delete_snapshot_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 = SubscriberClient( - 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_snapshot in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_snapshot] = mock_rpc - - request = {} - client.delete_snapshot(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.delete_snapshot(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_snapshot_rest_required_fields(request_type=pubsub.DeleteSnapshotRequest): - transport_class = transports.SubscriberRestTransport - - request_init = {} - request_init["snapshot"] = "" - 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_snapshot._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["snapshot"] = 'snapshot_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_snapshot._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "snapshot" in jsonified_request - assert jsonified_request["snapshot"] == 'snapshot_value' - - client = SubscriberClient( - 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 - - response = client.delete_snapshot(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_delete_snapshot_rest_unset_required_fields(): - transport = transports.SubscriberRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.delete_snapshot._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("snapshot", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_delete_snapshot_rest_interceptors(null_interceptor): - transport = transports.SubscriberRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SubscriberRestInterceptor(), - ) - client = SubscriberClient(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.SubscriberRestInterceptor, "pre_delete_snapshot") as pre: - pre.assert_not_called() - pb_message = pubsub.DeleteSnapshotRequest.pb(pubsub.DeleteSnapshotRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - - request = pubsub.DeleteSnapshotRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - - client.delete_snapshot(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - - -def test_delete_snapshot_rest_bad_request(transport: str = 'rest', request_type=pubsub.DeleteSnapshotRequest): - client = SubscriberClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'snapshot': 'projects/sample1/snapshots/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 = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.delete_snapshot(request) - - -def test_delete_snapshot_rest_flattened(): - client = SubscriberClient( - 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 = {'snapshot': 'projects/sample1/snapshots/sample2'} - - # get truthy value for each flattened field - mock_args = dict( - snapshot='snapshot_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 - - client.delete_snapshot(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1/{snapshot=projects/*/snapshots/*}" % client.transport._host, args[1]) - - -def test_delete_snapshot_rest_flattened_error(transport: str = 'rest'): - client = SubscriberClient( - 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_snapshot( - pubsub.DeleteSnapshotRequest(), - snapshot='snapshot_value', - ) - - -def test_delete_snapshot_rest_error(): - client = SubscriberClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - pubsub.SeekRequest, - dict, -]) -def test_seek_rest(request_type): - client = SubscriberClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'subscription': 'projects/sample1/subscriptions/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 = pubsub.SeekResponse( - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = pubsub.SeekResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.seek(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pubsub.SeekResponse) - -def test_seek_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 = SubscriberClient( - 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.seek in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.seek] = mock_rpc - - request = {} - client.seek(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.seek(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_seek_rest_required_fields(request_type=pubsub.SeekRequest): - transport_class = transports.SubscriberRestTransport - - request_init = {} - request_init["subscription"] = "" - 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()).seek._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["subscription"] = 'subscription_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).seek._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "subscription" in jsonified_request - assert jsonified_request["subscription"] == 'subscription_value' - - client = SubscriberClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = pubsub.SeekResponse() - # 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 = pubsub.SeekResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.seek(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_seek_rest_unset_required_fields(): - transport = transports.SubscriberRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.seek._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("subscription", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_seek_rest_interceptors(null_interceptor): - transport = transports.SubscriberRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SubscriberRestInterceptor(), - ) - client = SubscriberClient(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.SubscriberRestInterceptor, "post_seek") as post, \ - mock.patch.object(transports.SubscriberRestInterceptor, "pre_seek") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = pubsub.SeekRequest.pb(pubsub.SeekRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = pubsub.SeekResponse.to_json(pubsub.SeekResponse()) - - request = pubsub.SeekRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = pubsub.SeekResponse() - - client.seek(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_seek_rest_bad_request(transport: str = 'rest', request_type=pubsub.SeekRequest): - client = SubscriberClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'subscription': 'projects/sample1/subscriptions/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 = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.seek(request) - - -def test_seek_rest_error(): - client = SubscriberClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -def test_streaming_pull_rest_error(): - client = SubscriberClient( - 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.streaming_pull({}) - assert ( - "Method StreamingPull 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.SubscriberGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = SubscriberClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.SubscriberGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = SubscriberClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide an api_key and a transport instance. - transport = transports.SubscriberGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = SubscriberClient( - 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 = SubscriberClient( - client_options=options, - credentials=ga_credentials.AnonymousCredentials() - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.SubscriberGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = SubscriberClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.SubscriberGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = SubscriberClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.SubscriberGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.SubscriberGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.SubscriberGrpcTransport, - transports.SubscriberGrpcAsyncIOTransport, - transports.SubscriberRestTransport, -]) -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() - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "rest", -]) -def test_transport_kind(transport_name): - transport = SubscriberClient.get_transport_class(transport_name)( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert transport.kind == transport_name - -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. - client = SubscriberClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.SubscriberGrpcTransport, - ) - -def test_subscriber_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.SubscriberTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_subscriber_base_transport(): - # Instantiate the base transport. - with mock.patch('google.pubsub_v1.services.subscriber.transports.SubscriberTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.SubscriberTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'create_subscription', - 'get_subscription', - 'update_subscription', - 'list_subscriptions', - 'delete_subscription', - 'modify_ack_deadline', - 'acknowledge', - 'pull', - 'streaming_pull', - 'modify_push_config', - 'get_snapshot', - 'list_snapshots', - 'create_snapshot', - 'update_snapshot', - 'delete_snapshot', - 'seek', - 'set_iam_policy', - 'get_iam_policy', - 'test_iam_permissions', - ) - 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_subscriber_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.pubsub_v1.services.subscriber.transports.SubscriberTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.SubscriberTransport( - credentials_file="credentials.json", - quota_project_id="octopus", - ) - load_creds.assert_called_once_with("credentials.json", - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/pubsub', -), - quota_project_id="octopus", - ) - - -def test_subscriber_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.pubsub_v1.services.subscriber.transports.SubscriberTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.SubscriberTransport() - adc.assert_called_once() - - -def test_subscriber_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) - SubscriberClient() - adc.assert_called_once_with( - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/pubsub', -), - quota_project_id=None, - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.SubscriberGrpcTransport, - transports.SubscriberGrpcAsyncIOTransport, - ], -) -def test_subscriber_transport_auth_adc(transport_class): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class(quota_project_id="octopus", scopes=["1", "2"]) - adc.assert_called_once_with( - scopes=["1", "2"], - default_scopes=( 'https://www.googleapis.com/auth/cloud-platform', 'https://www.googleapis.com/auth/pubsub',), - quota_project_id="octopus", - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.SubscriberGrpcTransport, - transports.SubscriberGrpcAsyncIOTransport, - transports.SubscriberRestTransport, - ], -) -def test_subscriber_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.SubscriberGrpcTransport, grpc_helpers), - (transports.SubscriberGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -def test_subscriber_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( - "pubsub.googleapis.com:443", - credentials=creds, - credentials_file=None, - quota_project_id="octopus", - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/pubsub', -), - scopes=["1", "2"], - default_host="pubsub.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("transport_class", [transports.SubscriberGrpcTransport, transports.SubscriberGrpcAsyncIOTransport]) -def test_subscriber_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_subscriber_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.SubscriberRestTransport ( - 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_subscriber_host_no_port(transport_name): - client = SubscriberClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='pubsub.googleapis.com'), - transport=transport_name, - ) - assert client.transport._host == ( - 'pubsub.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://pubsub.googleapis.com' - ) - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", - "rest", -]) -def test_subscriber_host_with_port(transport_name): - client = SubscriberClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='pubsub.googleapis.com:8000'), - transport=transport_name, - ) - assert client.transport._host == ( - 'pubsub.googleapis.com:8000' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://pubsub.googleapis.com:8000' - ) - -@pytest.mark.parametrize("transport_name", [ - "rest", -]) -def test_subscriber_client_transport_session_collision(transport_name): - creds1 = ga_credentials.AnonymousCredentials() - creds2 = ga_credentials.AnonymousCredentials() - client1 = SubscriberClient( - credentials=creds1, - transport=transport_name, - ) - client2 = SubscriberClient( - credentials=creds2, - transport=transport_name, - ) - session1 = client1.transport.create_subscription._session - session2 = client2.transport.create_subscription._session - assert session1 != session2 - session1 = client1.transport.get_subscription._session - session2 = client2.transport.get_subscription._session - assert session1 != session2 - session1 = client1.transport.update_subscription._session - session2 = client2.transport.update_subscription._session - assert session1 != session2 - session1 = client1.transport.list_subscriptions._session - session2 = client2.transport.list_subscriptions._session - assert session1 != session2 - session1 = client1.transport.delete_subscription._session - session2 = client2.transport.delete_subscription._session - assert session1 != session2 - session1 = client1.transport.modify_ack_deadline._session - session2 = client2.transport.modify_ack_deadline._session - assert session1 != session2 - session1 = client1.transport.acknowledge._session - session2 = client2.transport.acknowledge._session - assert session1 != session2 - session1 = client1.transport.pull._session - session2 = client2.transport.pull._session - assert session1 != session2 - session1 = client1.transport.streaming_pull._session - session2 = client2.transport.streaming_pull._session - assert session1 != session2 - session1 = client1.transport.modify_push_config._session - session2 = client2.transport.modify_push_config._session - assert session1 != session2 - session1 = client1.transport.get_snapshot._session - session2 = client2.transport.get_snapshot._session - assert session1 != session2 - session1 = client1.transport.list_snapshots._session - session2 = client2.transport.list_snapshots._session - assert session1 != session2 - session1 = client1.transport.create_snapshot._session - session2 = client2.transport.create_snapshot._session - assert session1 != session2 - session1 = client1.transport.update_snapshot._session - session2 = client2.transport.update_snapshot._session - assert session1 != session2 - session1 = client1.transport.delete_snapshot._session - session2 = client2.transport.delete_snapshot._session - assert session1 != session2 - session1 = client1.transport.seek._session - session2 = client2.transport.seek._session - assert session1 != session2 -def test_subscriber_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.SubscriberGrpcTransport( - 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_subscriber_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.SubscriberGrpcAsyncIOTransport( - host="squid.clam.whelk", - channel=channel, - ) - assert transport.grpc_channel == channel - assert transport._host == "squid.clam.whelk:443" - assert transport._ssl_channel_credentials == None - - -# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are -# removed from grpc/grpc_asyncio transport constructor. -@pytest.mark.parametrize("transport_class", [transports.SubscriberGrpcTransport, transports.SubscriberGrpcAsyncIOTransport]) -def test_subscriber_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.SubscriberGrpcTransport, transports.SubscriberGrpcAsyncIOTransport]) -def test_subscriber_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_snapshot_path(): - project = "squid" - snapshot = "clam" - expected = "projects/{project}/snapshots/{snapshot}".format(project=project, snapshot=snapshot, ) - actual = SubscriberClient.snapshot_path(project, snapshot) - assert expected == actual - - -def test_parse_snapshot_path(): - expected = { - "project": "whelk", - "snapshot": "octopus", - } - path = SubscriberClient.snapshot_path(**expected) - - # Check that the path construction is reversible. - actual = SubscriberClient.parse_snapshot_path(path) - assert expected == actual - -def test_subscription_path(): - project = "oyster" - subscription = "nudibranch" - expected = "projects/{project}/subscriptions/{subscription}".format(project=project, subscription=subscription, ) - actual = SubscriberClient.subscription_path(project, subscription) - assert expected == actual - - -def test_parse_subscription_path(): - expected = { - "project": "cuttlefish", - "subscription": "mussel", - } - path = SubscriberClient.subscription_path(**expected) - - # Check that the path construction is reversible. - actual = SubscriberClient.parse_subscription_path(path) - assert expected == actual - -def test_topic_path(): - project = "winkle" - topic = "nautilus" - expected = "projects/{project}/topics/{topic}".format(project=project, topic=topic, ) - actual = SubscriberClient.topic_path(project, topic) - assert expected == actual - - -def test_parse_topic_path(): - expected = { - "project": "scallop", - "topic": "abalone", - } - path = SubscriberClient.topic_path(**expected) - - # Check that the path construction is reversible. - actual = SubscriberClient.parse_topic_path(path) - assert expected == actual - -def test_common_billing_account_path(): - billing_account = "squid" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = SubscriberClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "clam", - } - path = SubscriberClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = SubscriberClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "whelk" - expected = "folders/{folder}".format(folder=folder, ) - actual = SubscriberClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "octopus", - } - path = SubscriberClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = SubscriberClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "oyster" - expected = "organizations/{organization}".format(organization=organization, ) - actual = SubscriberClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "nudibranch", - } - path = SubscriberClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = SubscriberClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "cuttlefish" - expected = "projects/{project}".format(project=project, ) - actual = SubscriberClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "mussel", - } - path = SubscriberClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = SubscriberClient.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 = SubscriberClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "scallop", - "location": "abalone", - } - path = SubscriberClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = SubscriberClient.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.SubscriberTransport, '_prep_wrapped_messages') as prep: - client = SubscriberClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.SubscriberTransport, '_prep_wrapped_messages') as prep: - transport_class = SubscriberClient.get_transport_class() - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - -@pytest.mark.asyncio -async def test_transport_close_async(): - client = SubscriberAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - 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_get_iam_policy_rest_bad_request(transport: str = 'rest', request_type=iam_policy_pb2.GetIamPolicyRequest): - client = SubscriberClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'resource': 'projects/sample1/topics/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() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_iam_policy(request) - -@pytest.mark.parametrize("request_type", [ - iam_policy_pb2.GetIamPolicyRequest, - dict, -]) -def test_get_iam_policy_rest(request_type): - client = SubscriberClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'resource': 'projects/sample1/topics/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 = policy_pb2.Policy() - - # 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 - - response = client.get_iam_policy(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, policy_pb2.Policy) - -def test_set_iam_policy_rest_bad_request(transport: str = 'rest', request_type=iam_policy_pb2.SetIamPolicyRequest): - client = SubscriberClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'resource': 'projects/sample1/topics/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() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.set_iam_policy(request) - -@pytest.mark.parametrize("request_type", [ - iam_policy_pb2.SetIamPolicyRequest, - dict, -]) -def test_set_iam_policy_rest(request_type): - client = SubscriberClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'resource': 'projects/sample1/topics/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 = policy_pb2.Policy() - - # 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 - - response = client.set_iam_policy(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, policy_pb2.Policy) - -def test_test_iam_permissions_rest_bad_request(transport: str = 'rest', request_type=iam_policy_pb2.TestIamPermissionsRequest): - client = SubscriberClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'resource': 'projects/sample1/subscriptions/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() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.test_iam_permissions(request) - -@pytest.mark.parametrize("request_type", [ - iam_policy_pb2.TestIamPermissionsRequest, - dict, -]) -def test_test_iam_permissions_rest(request_type): - client = SubscriberClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'resource': 'projects/sample1/subscriptions/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 = iam_policy_pb2.TestIamPermissionsResponse() - - # 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 - - 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_set_iam_policy(transport: str = "grpc"): - client = SubscriberClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional 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 = SubscriberAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional 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 = SubscriberClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = SubscriberAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = SubscriberClient( - 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 = SubscriberAsyncClient( - 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 = grpc_helpers_async.FakeUnaryUnaryCall( - policy_pb2.Policy() - ) - - response = await client.set_iam_policy( - request={ - "resource": "resource_value", - "policy": policy_pb2.Policy(version=774), - } - ) - call.assert_called() - - -def test_get_iam_policy(transport: str = "grpc"): - client = SubscriberClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional 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 = SubscriberAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional 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 = SubscriberClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = SubscriberAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = SubscriberClient( - 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 = SubscriberAsyncClient( - 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 = grpc_helpers_async.FakeUnaryUnaryCall( - policy_pb2.Policy() - ) - - response = await client.get_iam_policy( - request={ - "resource": "resource_value", - "options": options_pb2.GetPolicyOptions(requested_policy_version=2598), - } - ) - call.assert_called() - - -def test_test_iam_permissions(transport: str = "grpc"): - client = SubscriberClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional 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 = SubscriberAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional 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 = SubscriberClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = SubscriberAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = SubscriberClient( - 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 = SubscriberAsyncClient( - 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 = grpc_helpers_async.FakeUnaryUnaryCall( - iam_policy_pb2.TestIamPermissionsResponse() - ) - - response = await client.test_iam_permissions( - request={ - "resource": "resource_value", - "permissions": ["permissions_value"], - } - ) - call.assert_called() - - -def test_transport_close(): - transports = { - "rest": "_session", - "grpc": "_grpc_channel", - } - - for transport, close_name in transports.items(): - client = SubscriberClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport - ) - with mock.patch.object(type(getattr(client.transport, close_name)), "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 = SubscriberClient( - 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", [ - (SubscriberClient, transports.SubscriberGrpcTransport), - (SubscriberAsyncClient, transports.SubscriberGrpcAsyncIOTransport), -]) -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/samples/generated_samples/snippet_metadata_google.pubsub.v1.json b/samples/generated_samples/snippet_metadata_google.pubsub.v1.json index c1602f5ba..d66015ac4 100644 --- a/samples/generated_samples/snippet_metadata_google.pubsub.v1.json +++ b/samples/generated_samples/snippet_metadata_google.pubsub.v1.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-pubsub", - "version": "2.23.1" + "version": "0.1.0" }, "snippets": [ {