From 80d6657eb8c636ac21e8347f125f05df71d7b488 Mon Sep 17 00:00:00 2001 From: Owl Bot Date: Fri, 4 Feb 2022 17:53:59 +0000 Subject: [PATCH] =?UTF-8?q?=F0=9F=A6=89=20Updates=20from=20OwlBot?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit See https://github.com/googleapis/repo-automation-bots/blob/main/packages/owl-bot/README.md --- .../services/publisher/async_client.py | 175 + google/pubsub_v1/services/publisher/client.py | 184 + .../services/schema_service/async_client.py | 119 + .../services/schema_service/client.py | 125 + .../services/subscriber/async_client.py | 319 + .../pubsub_v1/services/subscriber/client.py | 335 + google/pubsub_v1/types/pubsub.py | 69 + owl-bot-staging/v1/.coveragerc | 17 - owl-bot-staging/v1/MANIFEST.in | 2 - owl-bot-staging/v1/README.rst | 49 - 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 | 7 - owl-bot-staging/v1/google/pubsub/__init__.py | 143 - owl-bot-staging/v1/google/pubsub/py.typed | 2 - .../v1/google/pubsub_v1/__init__.py | 144 - .../v1/google/pubsub_v1/gapic_metadata.json | 361 -- 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 | 1409 ----- .../pubsub_v1/services/publisher/client.py | 1571 ----- .../pubsub_v1/services/publisher/pagers.py | 381 -- .../services/publisher/transports/__init__.py | 33 - .../services/publisher/transports/base.py | 358 -- .../services/publisher/transports/grpc.py | 567 -- .../publisher/transports/grpc_asyncio.py | 572 -- .../services/schema_service/__init__.py | 22 - .../services/schema_service/async_client.py | 1060 ---- .../services/schema_service/client.py | 1268 ---- .../services/schema_service/pagers.py | 139 - .../schema_service/transports/__init__.py | 33 - .../schema_service/transports/base.py | 249 - .../schema_service/transports/grpc.py | 470 -- .../schema_service/transports/grpc_asyncio.py | 475 -- .../pubsub_v1/services/subscriber/__init__.py | 22 - .../services/subscriber/async_client.py | 2277 ------- .../pubsub_v1/services/subscriber/client.py | 2397 ------- .../pubsub_v1/services/subscriber/pagers.py | 260 - .../subscriber/transports/__init__.py | 33 - .../services/subscriber/transports/base.py | 502 -- .../services/subscriber/transports/grpc.py | 830 --- .../subscriber/transports/grpc_asyncio.py | 835 --- .../v1/google/pubsub_v1/types/__init__.py | 134 - .../v1/google/pubsub_v1/types/pubsub.py | 1779 ------ .../v1/google/pubsub_v1/types/schema.py | 319 - owl-bot-staging/v1/mypy.ini | 3 - owl-bot-staging/v1/noxfile.py | 132 - .../v1/scripts/fixup_pubsub_v1_keywords.py | 209 - owl-bot-staging/v1/setup.py | 55 - 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 | 4154 ------------- .../gapic/pubsub_v1/test_schema_service.py | 3113 ---------- .../unit/gapic/pubsub_v1/test_subscriber.py | 5493 ----------------- ..._pubsub_v1_publisher_create_topic_async.py | 0 ...d_pubsub_v1_publisher_create_topic_sync.py | 0 ..._pubsub_v1_publisher_delete_topic_async.py | 0 ...d_pubsub_v1_publisher_delete_topic_sync.py | 0 ..._v1_publisher_detach_subscription_async.py | 0 ...b_v1_publisher_detach_subscription_sync.py | 0 ...ted_pubsub_v1_publisher_get_topic_async.py | 0 ...ated_pubsub_v1_publisher_get_topic_sync.py | 0 ...v1_publisher_list_topic_snapshots_async.py | 0 ..._v1_publisher_list_topic_snapshots_sync.py | 0 ...ublisher_list_topic_subscriptions_async.py | 0 ...publisher_list_topic_subscriptions_sync.py | 0 ...d_pubsub_v1_publisher_list_topics_async.py | 0 ...ed_pubsub_v1_publisher_list_topics_sync.py | 0 ...rated_pubsub_v1_publisher_publish_async.py | 0 ...erated_pubsub_v1_publisher_publish_sync.py | 0 ..._pubsub_v1_publisher_update_topic_async.py | 0 ...d_pubsub_v1_publisher_update_topic_sync.py | 0 ...b_v1_schema_service_create_schema_async.py | 0 ...ub_v1_schema_service_create_schema_sync.py | 0 ...b_v1_schema_service_delete_schema_async.py | 0 ...ub_v1_schema_service_delete_schema_sync.py | 0 ...bsub_v1_schema_service_get_schema_async.py | 0 ...ubsub_v1_schema_service_get_schema_sync.py | 0 ...ub_v1_schema_service_list_schemas_async.py | 0 ...sub_v1_schema_service_list_schemas_sync.py | 0 ...1_schema_service_validate_message_async.py | 0 ...v1_schema_service_validate_message_sync.py | 0 ...v1_schema_service_validate_schema_async.py | 0 ..._v1_schema_service_validate_schema_sync.py | 0 ..._pubsub_v1_subscriber_acknowledge_async.py | 0 ...d_pubsub_v1_subscriber_acknowledge_sync.py | 0 ...sub_v1_subscriber_create_snapshot_async.py | 0 ...bsub_v1_subscriber_create_snapshot_sync.py | 0 ...v1_subscriber_create_subscription_async.py | 0 ..._v1_subscriber_create_subscription_sync.py | 0 ...sub_v1_subscriber_delete_snapshot_async.py | 0 ...bsub_v1_subscriber_delete_snapshot_sync.py | 0 ...v1_subscriber_delete_subscription_async.py | 0 ..._v1_subscriber_delete_subscription_sync.py | 0 ...pubsub_v1_subscriber_get_snapshot_async.py | 0 ..._pubsub_v1_subscriber_get_snapshot_sync.py | 0 ...ub_v1_subscriber_get_subscription_async.py | 0 ...sub_v1_subscriber_get_subscription_sync.py | 0 ...bsub_v1_subscriber_list_snapshots_async.py | 0 ...ubsub_v1_subscriber_list_snapshots_sync.py | 0 ..._v1_subscriber_list_subscriptions_async.py | 0 ...b_v1_subscriber_list_subscriptions_sync.py | 0 ...v1_subscriber_modify_ack_deadline_async.py | 0 ..._v1_subscriber_modify_ack_deadline_sync.py | 0 ..._v1_subscriber_modify_push_config_async.py | 0 ...b_v1_subscriber_modify_push_config_sync.py | 0 ...nerated_pubsub_v1_subscriber_pull_async.py | 0 ...enerated_pubsub_v1_subscriber_pull_sync.py | 0 ...nerated_pubsub_v1_subscriber_seek_async.py | 0 ...enerated_pubsub_v1_subscriber_seek_sync.py | 0 ...bsub_v1_subscriber_streaming_pull_async.py | 0 ...ubsub_v1_subscriber_streaming_pull_sync.py | 0 ...sub_v1_subscriber_update_snapshot_async.py | 0 ...bsub_v1_subscriber_update_snapshot_sync.py | 0 ...v1_subscriber_update_subscription_async.py | 0 ..._v1_subscriber_update_subscription_sync.py | 0 .../snippet_metadata_pubsub_v1.json | 0 scripts/fixup_pubsub_v1_keywords.py | 2 +- tests/unit/gapic/pubsub_v1/test_subscriber.py | 12 + 126 files changed, 1339 insertions(+), 32404 deletions(-) delete mode 100644 owl-bot-staging/v1/.coveragerc 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/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/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/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/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/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/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/scripts/fixup_pubsub_v1_keywords.py delete mode 100644 owl-bot-staging/v1/setup.py 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 rename {owl-bot-staging/v1/samples => samples}/generated_samples/pubsub_generated_pubsub_v1_publisher_create_topic_async.py (100%) rename {owl-bot-staging/v1/samples => samples}/generated_samples/pubsub_generated_pubsub_v1_publisher_create_topic_sync.py (100%) rename {owl-bot-staging/v1/samples => samples}/generated_samples/pubsub_generated_pubsub_v1_publisher_delete_topic_async.py (100%) rename {owl-bot-staging/v1/samples => samples}/generated_samples/pubsub_generated_pubsub_v1_publisher_delete_topic_sync.py (100%) rename {owl-bot-staging/v1/samples => samples}/generated_samples/pubsub_generated_pubsub_v1_publisher_detach_subscription_async.py (100%) rename {owl-bot-staging/v1/samples => samples}/generated_samples/pubsub_generated_pubsub_v1_publisher_detach_subscription_sync.py (100%) rename {owl-bot-staging/v1/samples => samples}/generated_samples/pubsub_generated_pubsub_v1_publisher_get_topic_async.py (100%) rename {owl-bot-staging/v1/samples => samples}/generated_samples/pubsub_generated_pubsub_v1_publisher_get_topic_sync.py (100%) rename {owl-bot-staging/v1/samples => samples}/generated_samples/pubsub_generated_pubsub_v1_publisher_list_topic_snapshots_async.py (100%) rename {owl-bot-staging/v1/samples => samples}/generated_samples/pubsub_generated_pubsub_v1_publisher_list_topic_snapshots_sync.py (100%) rename {owl-bot-staging/v1/samples => samples}/generated_samples/pubsub_generated_pubsub_v1_publisher_list_topic_subscriptions_async.py (100%) rename {owl-bot-staging/v1/samples => samples}/generated_samples/pubsub_generated_pubsub_v1_publisher_list_topic_subscriptions_sync.py (100%) rename {owl-bot-staging/v1/samples => samples}/generated_samples/pubsub_generated_pubsub_v1_publisher_list_topics_async.py (100%) rename {owl-bot-staging/v1/samples => samples}/generated_samples/pubsub_generated_pubsub_v1_publisher_list_topics_sync.py (100%) rename {owl-bot-staging/v1/samples => samples}/generated_samples/pubsub_generated_pubsub_v1_publisher_publish_async.py (100%) rename {owl-bot-staging/v1/samples => samples}/generated_samples/pubsub_generated_pubsub_v1_publisher_publish_sync.py (100%) rename {owl-bot-staging/v1/samples => samples}/generated_samples/pubsub_generated_pubsub_v1_publisher_update_topic_async.py (100%) rename {owl-bot-staging/v1/samples => samples}/generated_samples/pubsub_generated_pubsub_v1_publisher_update_topic_sync.py (100%) rename {owl-bot-staging/v1/samples => samples}/generated_samples/pubsub_generated_pubsub_v1_schema_service_create_schema_async.py (100%) rename {owl-bot-staging/v1/samples => samples}/generated_samples/pubsub_generated_pubsub_v1_schema_service_create_schema_sync.py (100%) rename {owl-bot-staging/v1/samples => samples}/generated_samples/pubsub_generated_pubsub_v1_schema_service_delete_schema_async.py (100%) rename {owl-bot-staging/v1/samples => samples}/generated_samples/pubsub_generated_pubsub_v1_schema_service_delete_schema_sync.py (100%) rename {owl-bot-staging/v1/samples => samples}/generated_samples/pubsub_generated_pubsub_v1_schema_service_get_schema_async.py (100%) rename {owl-bot-staging/v1/samples => samples}/generated_samples/pubsub_generated_pubsub_v1_schema_service_get_schema_sync.py (100%) rename {owl-bot-staging/v1/samples => samples}/generated_samples/pubsub_generated_pubsub_v1_schema_service_list_schemas_async.py (100%) rename {owl-bot-staging/v1/samples => samples}/generated_samples/pubsub_generated_pubsub_v1_schema_service_list_schemas_sync.py (100%) rename {owl-bot-staging/v1/samples => samples}/generated_samples/pubsub_generated_pubsub_v1_schema_service_validate_message_async.py (100%) rename {owl-bot-staging/v1/samples => samples}/generated_samples/pubsub_generated_pubsub_v1_schema_service_validate_message_sync.py (100%) rename {owl-bot-staging/v1/samples => samples}/generated_samples/pubsub_generated_pubsub_v1_schema_service_validate_schema_async.py (100%) rename {owl-bot-staging/v1/samples => samples}/generated_samples/pubsub_generated_pubsub_v1_schema_service_validate_schema_sync.py (100%) rename {owl-bot-staging/v1/samples => samples}/generated_samples/pubsub_generated_pubsub_v1_subscriber_acknowledge_async.py (100%) rename {owl-bot-staging/v1/samples => samples}/generated_samples/pubsub_generated_pubsub_v1_subscriber_acknowledge_sync.py (100%) rename {owl-bot-staging/v1/samples => samples}/generated_samples/pubsub_generated_pubsub_v1_subscriber_create_snapshot_async.py (100%) rename {owl-bot-staging/v1/samples => samples}/generated_samples/pubsub_generated_pubsub_v1_subscriber_create_snapshot_sync.py (100%) rename {owl-bot-staging/v1/samples => samples}/generated_samples/pubsub_generated_pubsub_v1_subscriber_create_subscription_async.py (100%) rename {owl-bot-staging/v1/samples => samples}/generated_samples/pubsub_generated_pubsub_v1_subscriber_create_subscription_sync.py (100%) rename {owl-bot-staging/v1/samples => samples}/generated_samples/pubsub_generated_pubsub_v1_subscriber_delete_snapshot_async.py (100%) rename {owl-bot-staging/v1/samples => samples}/generated_samples/pubsub_generated_pubsub_v1_subscriber_delete_snapshot_sync.py (100%) rename {owl-bot-staging/v1/samples => samples}/generated_samples/pubsub_generated_pubsub_v1_subscriber_delete_subscription_async.py (100%) rename {owl-bot-staging/v1/samples => samples}/generated_samples/pubsub_generated_pubsub_v1_subscriber_delete_subscription_sync.py (100%) rename {owl-bot-staging/v1/samples => samples}/generated_samples/pubsub_generated_pubsub_v1_subscriber_get_snapshot_async.py (100%) rename {owl-bot-staging/v1/samples => samples}/generated_samples/pubsub_generated_pubsub_v1_subscriber_get_snapshot_sync.py (100%) rename {owl-bot-staging/v1/samples => samples}/generated_samples/pubsub_generated_pubsub_v1_subscriber_get_subscription_async.py (100%) rename {owl-bot-staging/v1/samples => samples}/generated_samples/pubsub_generated_pubsub_v1_subscriber_get_subscription_sync.py (100%) rename {owl-bot-staging/v1/samples => samples}/generated_samples/pubsub_generated_pubsub_v1_subscriber_list_snapshots_async.py (100%) rename {owl-bot-staging/v1/samples => samples}/generated_samples/pubsub_generated_pubsub_v1_subscriber_list_snapshots_sync.py (100%) rename {owl-bot-staging/v1/samples => samples}/generated_samples/pubsub_generated_pubsub_v1_subscriber_list_subscriptions_async.py (100%) rename {owl-bot-staging/v1/samples => samples}/generated_samples/pubsub_generated_pubsub_v1_subscriber_list_subscriptions_sync.py (100%) rename {owl-bot-staging/v1/samples => samples}/generated_samples/pubsub_generated_pubsub_v1_subscriber_modify_ack_deadline_async.py (100%) rename {owl-bot-staging/v1/samples => samples}/generated_samples/pubsub_generated_pubsub_v1_subscriber_modify_ack_deadline_sync.py (100%) rename {owl-bot-staging/v1/samples => samples}/generated_samples/pubsub_generated_pubsub_v1_subscriber_modify_push_config_async.py (100%) rename {owl-bot-staging/v1/samples => samples}/generated_samples/pubsub_generated_pubsub_v1_subscriber_modify_push_config_sync.py (100%) rename {owl-bot-staging/v1/samples => samples}/generated_samples/pubsub_generated_pubsub_v1_subscriber_pull_async.py (100%) rename {owl-bot-staging/v1/samples => samples}/generated_samples/pubsub_generated_pubsub_v1_subscriber_pull_sync.py (100%) rename {owl-bot-staging/v1/samples => samples}/generated_samples/pubsub_generated_pubsub_v1_subscriber_seek_async.py (100%) rename {owl-bot-staging/v1/samples => samples}/generated_samples/pubsub_generated_pubsub_v1_subscriber_seek_sync.py (100%) rename {owl-bot-staging/v1/samples => samples}/generated_samples/pubsub_generated_pubsub_v1_subscriber_streaming_pull_async.py (100%) rename {owl-bot-staging/v1/samples => samples}/generated_samples/pubsub_generated_pubsub_v1_subscriber_streaming_pull_sync.py (100%) rename {owl-bot-staging/v1/samples => samples}/generated_samples/pubsub_generated_pubsub_v1_subscriber_update_snapshot_async.py (100%) rename {owl-bot-staging/v1/samples => samples}/generated_samples/pubsub_generated_pubsub_v1_subscriber_update_snapshot_sync.py (100%) rename {owl-bot-staging/v1/samples => samples}/generated_samples/pubsub_generated_pubsub_v1_subscriber_update_subscription_async.py (100%) rename {owl-bot-staging/v1/samples => samples}/generated_samples/pubsub_generated_pubsub_v1_subscriber_update_subscription_sync.py (100%) rename {owl-bot-staging/v1/samples => samples}/generated_samples/snippet_metadata_pubsub_v1.json (100%) diff --git a/google/pubsub_v1/services/publisher/async_client.py b/google/pubsub_v1/services/publisher/async_client.py index 308e0f629..2a1dd9213 100644 --- a/google/pubsub_v1/services/publisher/async_client.py +++ b/google/pubsub_v1/services/publisher/async_client.py @@ -220,6 +220,26 @@ async def create_topic( name rules] (https://cloud.google.com/pubsub/docs/admin#resource_names). + + .. code-block:: + + 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 response + print(response) + Args: request (Union[google.pubsub_v1.types.Topic, dict]): The request object. A topic resource. @@ -304,6 +324,29 @@ async def update_topic( r"""Updates an existing topic. Note that certain properties of a topic are not modifiable. + + .. code-block:: + + 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 response + print(response) + Args: request (Union[google.pubsub_v1.types.UpdateTopicRequest, dict]): The request object. Request for the UpdateTopic method. @@ -365,6 +408,26 @@ async def publish( r"""Adds one or more messages to the topic. Returns ``NOT_FOUND`` if the topic does not exist. + + .. code-block:: + + 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 response + print(response) + Args: request (Union[google.pubsub_v1.types.PublishRequest, dict]): The request object. Request for the Publish method. @@ -457,6 +520,25 @@ async def get_topic( ) -> pubsub.Topic: r"""Gets the configuration of a topic. + .. code-block:: + + 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 response + print(response) + Args: request (Union[google.pubsub_v1.types.GetTopicRequest, dict]): The request object. Request for the GetTopic method. @@ -537,6 +619,24 @@ async def list_topics( ) -> pagers.ListTopicsAsyncPager: r"""Lists matching topics. + .. code-block:: + + 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) + for response in page_result: + print(response) + Args: request (Union[google.pubsub_v1.types.ListTopicsRequest, dict]): The request object. Request for the `ListTopics` method. @@ -628,6 +728,25 @@ async def list_topic_subscriptions( r"""Lists the names of the attached subscriptions on this topic. + + .. code-block:: + + 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) + for response in page_result: + print(response) + Args: request (Union[google.pubsub_v1.types.ListTopicSubscriptionsRequest, dict]): The request object. Request for the @@ -725,6 +844,25 @@ async def list_topic_snapshots( bulk. That is, you can set the acknowledgment state of messages in an existing subscription to the state captured by a snapshot. + + .. code-block:: + + 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) + for response in page_result: + print(response) + Args: request (Union[google.pubsub_v1.types.ListTopicSnapshotsRequest, dict]): The request object. Request for the `ListTopicSnapshots` @@ -822,6 +960,23 @@ async def delete_topic( subscriptions to this topic are not deleted, but their ``topic`` field is set to ``_deleted-topic_``. + + .. code-block:: + + 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 + response = client.delete_topic(request=request) + Args: request (Union[google.pubsub_v1.types.DeleteTopicRequest, dict]): The request object. Request for the `DeleteTopic` @@ -899,6 +1054,26 @@ async def detach_subscription( the subscription is a push subscription, pushes to the endpoint will stop. + + .. code-block:: + + 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 response + print(response) + Args: request (Union[google.pubsub_v1.types.DetachSubscriptionRequest, dict]): The request object. Request for the DetachSubscription diff --git a/google/pubsub_v1/services/publisher/client.py b/google/pubsub_v1/services/publisher/client.py index d445ddd14..01612ead6 100644 --- a/google/pubsub_v1/services/publisher/client.py +++ b/google/pubsub_v1/services/publisher/client.py @@ -469,6 +469,27 @@ def create_topic( (https://cloud.google.com/pubsub/docs/admin#resource_names). + + .. code-block:: + + 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 response + print(response) + + Args: request (Union[google.pubsub_v1.types.Topic, dict]): The request object. A topic resource. @@ -545,6 +566,30 @@ def update_topic( properties of a topic are not modifiable. + + .. code-block:: + + 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 response + print(response) + + Args: request (Union[google.pubsub_v1.types.UpdateTopicRequest, dict]): The request object. Request for the UpdateTopic method. @@ -599,6 +644,27 @@ def publish( the topic does not exist. + + .. code-block:: + + 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 response + print(response) + + Args: request (Union[google.pubsub_v1.types.PublishRequest, dict]): The request object. Request for the Publish method. @@ -677,6 +743,26 @@ def get_topic( r"""Gets the configuration of a topic. + .. code-block:: + + 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 response + print(response) + + Args: request (Union[google.pubsub_v1.types.GetTopicRequest, dict]): The request object. Request for the GetTopic method. @@ -747,6 +833,25 @@ def list_topics( r"""Lists matching topics. + .. code-block:: + + 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) + for response in page_result: + print(response) + + Args: request (Union[google.pubsub_v1.types.ListTopicsRequest, dict]): The request object. Request for the `ListTopics` method. @@ -828,6 +933,26 @@ def list_topic_subscriptions( topic. + + .. code-block:: + + 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) + for response in page_result: + print(response) + + Args: request (Union[google.pubsub_v1.types.ListTopicSubscriptionsRequest, dict]): The request object. Request for the @@ -915,6 +1040,26 @@ def list_topic_snapshots( in an existing subscription to the state captured by a snapshot. + + .. code-block:: + + 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) + for response in page_result: + print(response) + + Args: request (Union[google.pubsub_v1.types.ListTopicSnapshotsRequest, dict]): The request object. Request for the `ListTopicSnapshots` @@ -1002,6 +1147,24 @@ def delete_topic( field is set to ``_deleted-topic_``. + + .. code-block:: + + 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 + response = client.delete_topic(request=request) + + Args: request (Union[google.pubsub_v1.types.DeleteTopicRequest, dict]): The request object. Request for the `DeleteTopic` @@ -1071,6 +1234,27 @@ def detach_subscription( will stop. + + .. code-block:: + + 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 response + print(response) + + Args: request (Union[google.pubsub_v1.types.DetachSubscriptionRequest, dict]): The request object. Request for the DetachSubscription diff --git a/google/pubsub_v1/services/schema_service/async_client.py b/google/pubsub_v1/services/schema_service/async_client.py index 3ab7daf7c..80826bb11 100644 --- a/google/pubsub_v1/services/schema_service/async_client.py +++ b/google/pubsub_v1/services/schema_service/async_client.py @@ -218,6 +218,29 @@ async def create_schema( ) -> gp_schema.Schema: r"""Creates a schema. + .. code-block:: + + 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 response + print(response) + Args: request (Union[google.pubsub_v1.types.CreateSchemaRequest, dict]): The request object. Request for the CreateSchema method. @@ -311,6 +334,25 @@ async def get_schema( ) -> schema.Schema: r"""Gets a schema. + .. code-block:: + + 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 response + print(response) + Args: request (Union[google.pubsub_v1.types.GetSchemaRequest, dict]): The request object. Request for the GetSchema method. @@ -379,6 +421,24 @@ async def list_schemas( ) -> pagers.ListSchemasAsyncPager: r"""Lists schemas in a project. + .. code-block:: + + 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) + for response in page_result: + print(response) + Args: request (Union[google.pubsub_v1.types.ListSchemasRequest, dict]): The request object. Request for the `ListSchemas` @@ -458,6 +518,22 @@ async def delete_schema( ) -> None: r"""Deletes a schema. + .. code-block:: + + 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 + response = client.delete_schema(request=request) + Args: request (Union[google.pubsub_v1.types.DeleteSchemaRequest, dict]): The request object. Request for the `DeleteSchema` @@ -523,6 +599,29 @@ async def validate_schema( ) -> gp_schema.ValidateSchemaResponse: r"""Validates a schema. + .. code-block:: + + 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 response + print(response) + Args: request (Union[google.pubsub_v1.types.ValidateSchemaRequest, dict]): The request object. Request for the `ValidateSchema` @@ -602,6 +701,26 @@ async def validate_message( ) -> schema.ValidateMessageResponse: r"""Validates a message against a schema. + .. code-block:: + + 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 response + print(response) + Args: request (Union[google.pubsub_v1.types.ValidateMessageRequest, dict]): The request object. Request for the `ValidateMessage` diff --git a/google/pubsub_v1/services/schema_service/client.py b/google/pubsub_v1/services/schema_service/client.py index 0a3575f6a..41914efd8 100644 --- a/google/pubsub_v1/services/schema_service/client.py +++ b/google/pubsub_v1/services/schema_service/client.py @@ -410,6 +410,30 @@ def create_schema( ) -> gp_schema.Schema: r"""Creates a schema. + + .. code-block:: + + 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 response + print(response) + Args: request (Union[google.pubsub_v1.types.CreateSchemaRequest, dict]): The request object. Request for the CreateSchema method. @@ -503,6 +527,26 @@ def get_schema( ) -> schema.Schema: r"""Gets a schema. + + .. code-block:: + + 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 response + print(response) + Args: request (Union[google.pubsub_v1.types.GetSchemaRequest, dict]): The request object. Request for the GetSchema method. @@ -571,6 +615,25 @@ def list_schemas( ) -> pagers.ListSchemasPager: r"""Lists schemas in a project. + + .. code-block:: + + 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) + for response in page_result: + print(response) + Args: request (Union[google.pubsub_v1.types.ListSchemasRequest, dict]): The request object. Request for the `ListSchemas` @@ -650,6 +713,23 @@ def delete_schema( ) -> None: r"""Deletes a schema. + + .. code-block:: + + 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 + response = client.delete_schema(request=request) + Args: request (Union[google.pubsub_v1.types.DeleteSchemaRequest, dict]): The request object. Request for the `DeleteSchema` @@ -715,6 +795,30 @@ def validate_schema( ) -> gp_schema.ValidateSchemaResponse: r"""Validates a schema. + + .. code-block:: + + 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 response + print(response) + Args: request (Union[google.pubsub_v1.types.ValidateSchemaRequest, dict]): The request object. Request for the `ValidateSchema` @@ -794,6 +898,27 @@ def validate_message( ) -> schema.ValidateMessageResponse: r"""Validates a message against a schema. + + .. code-block:: + + 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 response + print(response) + Args: request (Union[google.pubsub_v1.types.ValidateMessageRequest, dict]): The request object. Request for the `ValidateMessage` diff --git a/google/pubsub_v1/services/subscriber/async_client.py b/google/pubsub_v1/services/subscriber/async_client.py index 319915887..2137f5cc9 100644 --- a/google/pubsub_v1/services/subscriber/async_client.py +++ b/google/pubsub_v1/services/subscriber/async_client.py @@ -245,6 +245,27 @@ async def create_subscription( Note that for REST API requests, you must specify a name in the request. + + .. code-block:: + + 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 response + print(response) + Args: request (Union[google.pubsub_v1.types.Subscription, dict]): The request object. A subscription resource. @@ -385,6 +406,25 @@ async def get_subscription( ) -> pubsub.Subscription: r"""Gets the configuration details of a subscription. + .. code-block:: + + 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 response + print(response) + Args: request (Union[google.pubsub_v1.types.GetSubscriptionRequest, dict]): The request object. Request for the GetSubscription @@ -468,6 +508,30 @@ async def update_subscription( properties of a subscription, such as its topic, are not modifiable. + + .. code-block:: + + 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 response + print(response) + Args: request (Union[google.pubsub_v1.types.UpdateSubscriptionRequest, dict]): The request object. Request for the UpdateSubscription @@ -527,6 +591,24 @@ async def list_subscriptions( ) -> pagers.ListSubscriptionsAsyncPager: r"""Lists matching subscriptions. + .. code-block:: + + 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) + for response in page_result: + print(response) + Args: request (Union[google.pubsub_v1.types.ListSubscriptionsRequest, dict]): The request object. Request for the `ListSubscriptions` @@ -622,6 +704,23 @@ async def delete_subscription( new one has no association with the old subscription or its topic unless the same topic is specified. + + .. code-block:: + + 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 + response = client.delete_subscription(request=request) + Args: request (Union[google.pubsub_v1.types.DeleteSubscriptionRequest, dict]): The request object. Request for the DeleteSubscription @@ -704,6 +803,25 @@ async def modify_ack_deadline( does not modify the subscription-level ``ackDeadlineSeconds`` used for subsequent messages. + + .. code-block:: + + 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_value_1', 'ack_ids_value_2'], + ack_deadline_seconds=2066, + ) + + # Make the request + response = client.modify_ack_deadline(request=request) + Args: request (Union[google.pubsub_v1.types.ModifyAckDeadlineRequest, dict]): The request object. Request for the ModifyAckDeadline @@ -812,6 +930,24 @@ async def acknowledge( Acknowledging a message more than once will not result in an error. + + .. code-block:: + + 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_value_1', 'ack_ids_value_2'], + ) + + # Make the request + response = client.acknowledge(request=request) + Args: request (Union[google.pubsub_v1.types.AcknowledgeRequest, dict]): The request object. Request for the Acknowledge method. @@ -901,6 +1037,27 @@ async def pull( ``UNAVAILABLE`` if there are too many concurrent pull requests pending for the given subscription. + + .. code-block:: + + 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 response + print(response) + Args: request (Union[google.pubsub_v1.types.PullRequest, dict]): The request object. Request for the `Pull` method. @@ -1023,6 +1180,35 @@ def streaming_pull( re-establish the stream. Flow control can be achieved by configuring the underlying RPC channel. + + .. code-block:: + + 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()) + for response in stream: + print(response) + Args: requests (AsyncIterator[`google.pubsub_v1.types.StreamingPullRequest`]): The request object AsyncIterator. Request for the `StreamingPull` @@ -1088,6 +1274,23 @@ async def modify_push_config( Messages will accumulate for delivery continuously through the call regardless of changes to the ``PushConfig``. + + .. code-block:: + + 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 + response = client.modify_push_config(request=request) + Args: request (Union[google.pubsub_v1.types.ModifyPushConfigRequest, dict]): The request object. Request for the ModifyPushConfig @@ -1183,6 +1386,26 @@ async def get_snapshot( acknowledgment state of messages in an existing subscription to the state captured by a snapshot. + + .. code-block:: + + 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 response + print(response) + Args: request (Union[google.pubsub_v1.types.GetSnapshotRequest, dict]): The request object. Request for the GetSnapshot method. @@ -1272,6 +1495,25 @@ async def list_snapshots( bulk. That is, you can set the acknowledgment state of messages in an existing subscription to the state captured by a snapshot. + + .. code-block:: + + 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) + for response in page_result: + print(response) + Args: request (Union[google.pubsub_v1.types.ListSnapshotsRequest, dict]): The request object. Request for the `ListSnapshots` @@ -1381,6 +1623,27 @@ async def create_snapshot( Note that for REST API requests, you must specify a name in the request. + + .. code-block:: + + 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 response + print(response) + Args: request (Union[google.pubsub_v1.types.CreateSnapshotRequest, dict]): The request object. Request for the `CreateSnapshot` @@ -1493,6 +1756,25 @@ async def update_snapshot( existing subscription to the state captured by a snapshot. + + .. code-block:: + + 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 response + print(response) + Args: request (Union[google.pubsub_v1.types.UpdateSnapshotRequest, dict]): The request object. Request for the UpdateSnapshot @@ -1567,6 +1849,23 @@ async def delete_snapshot( no association with the old snapshot or its subscription, unless the same subscription is specified. + + .. code-block:: + + 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 + response = client.delete_snapshot(request=request) + Args: request (Union[google.pubsub_v1.types.DeleteSnapshotRequest, dict]): The request object. Request for the `DeleteSnapshot` @@ -1647,6 +1946,26 @@ async def seek( Note that both the subscription and the snapshot must be on the same topic. + + .. code-block:: + + 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 response + print(response) + Args: request (Union[google.pubsub_v1.types.SeekRequest, dict]): The request object. Request for the `Seek` method. diff --git a/google/pubsub_v1/services/subscriber/client.py b/google/pubsub_v1/services/subscriber/client.py index 2d2839b2a..ff5cda665 100644 --- a/google/pubsub_v1/services/subscriber/client.py +++ b/google/pubsub_v1/services/subscriber/client.py @@ -484,6 +484,28 @@ def create_subscription( request. + + .. code-block:: + + 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 response + print(response) + + Args: request (Union[google.pubsub_v1.types.Subscription, dict]): The request object. A subscription resource. @@ -614,6 +636,26 @@ def get_subscription( r"""Gets the configuration details of a subscription. + .. code-block:: + + 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 response + print(response) + + Args: request (Union[google.pubsub_v1.types.GetSubscriptionRequest, dict]): The request object. Request for the GetSubscription @@ -687,6 +729,31 @@ def update_subscription( modifiable. + + .. code-block:: + + 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 response + print(response) + + Args: request (Union[google.pubsub_v1.types.UpdateSubscriptionRequest, dict]): The request object. Request for the UpdateSubscription @@ -739,6 +806,25 @@ def list_subscriptions( r"""Lists matching subscriptions. + .. code-block:: + + 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) + for response in page_result: + print(response) + + Args: request (Union[google.pubsub_v1.types.ListSubscriptionsRequest, dict]): The request object. Request for the `ListSubscriptions` @@ -824,6 +910,24 @@ def delete_subscription( topic unless the same topic is specified. + + .. code-block:: + + 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 + response = client.delete_subscription(request=request) + + Args: request (Union[google.pubsub_v1.types.DeleteSubscriptionRequest, dict]): The request object. Request for the DeleteSubscription @@ -898,6 +1002,26 @@ def modify_ack_deadline( used for subsequent messages. + + .. code-block:: + + 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_value_1', 'ack_ids_value_2'], + ack_deadline_seconds=2066, + ) + + # Make the request + response = client.modify_ack_deadline(request=request) + + Args: request (Union[google.pubsub_v1.types.ModifyAckDeadlineRequest, dict]): The request object. Request for the ModifyAckDeadline @@ -998,6 +1122,25 @@ def acknowledge( error. + + .. code-block:: + + 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_value_1', 'ack_ids_value_2'], + ) + + # Make the request + response = client.acknowledge(request=request) + + Args: request (Union[google.pubsub_v1.types.AcknowledgeRequest, dict]): The request object. Request for the Acknowledge method. @@ -1079,6 +1222,28 @@ def pull( pending for the given subscription. + + .. code-block:: + + 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 response + print(response) + + Args: request (Union[google.pubsub_v1.types.PullRequest, dict]): The request object. Request for the `Pull` method. @@ -1191,6 +1356,36 @@ def streaming_pull( configuring the underlying RPC channel. + + .. code-block:: + + 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()) + for response in stream: + print(response) + + Args: requests (Iterator[google.pubsub_v1.types.StreamingPullRequest]): The request object iterator. Request for the `StreamingPull` @@ -1245,6 +1440,24 @@ def modify_push_config( call regardless of changes to the ``PushConfig``. + + .. code-block:: + + 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 + response = client.modify_push_config(request=request) + + Args: request (Union[google.pubsub_v1.types.ModifyPushConfigRequest, dict]): The request object. Request for the ModifyPushConfig @@ -1332,6 +1545,27 @@ def get_snapshot( subscription to the state captured by a snapshot. + + .. code-block:: + + 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 response + print(response) + + Args: request (Union[google.pubsub_v1.types.GetSnapshotRequest, dict]): The request object. Request for the GetSnapshot method. @@ -1411,6 +1645,26 @@ def list_snapshots( in an existing subscription to the state captured by a snapshot. + + .. code-block:: + + 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) + for response in page_result: + print(response) + + Args: request (Union[google.pubsub_v1.types.ListSnapshotsRequest, dict]): The request object. Request for the `ListSnapshots` @@ -1510,6 +1764,28 @@ def create_snapshot( request. + + .. code-block:: + + 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 response + print(response) + + Args: request (Union[google.pubsub_v1.types.CreateSnapshotRequest, dict]): The request object. Request for the `CreateSnapshot` @@ -1614,6 +1890,26 @@ def update_snapshot( snapshot. + + .. code-block:: + + 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 response + print(response) + + Args: request (Union[google.pubsub_v1.types.UpdateSnapshotRequest, dict]): The request object. Request for the UpdateSnapshot @@ -1681,6 +1977,24 @@ def delete_snapshot( the same subscription is specified. + + .. code-block:: + + 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 + response = client.delete_snapshot(request=request) + + Args: request (Union[google.pubsub_v1.types.DeleteSnapshotRequest, dict]): The request object. Request for the `DeleteSnapshot` @@ -1753,6 +2067,27 @@ def seek( same topic. + + .. code-block:: + + 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 response + print(response) + + Args: request (Union[google.pubsub_v1.types.SeekRequest, dict]): The request object. Request for the `Seek` method. diff --git a/google/pubsub_v1/types/pubsub.py b/google/pubsub_v1/types/pubsub.py index de29dcd10..5750f495c 100644 --- a/google/pubsub_v1/types/pubsub.py +++ b/google/pubsub_v1/types/pubsub.py @@ -558,6 +558,22 @@ class Subscription(proto.Message): ``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): + 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 @@ -588,6 +604,7 @@ class Subscription(proto.Message): ) retry_policy = proto.Field(proto.MESSAGE, number=14, message="RetryPolicy",) detached = proto.Field(proto.BOOL, number=15,) + enable_exactly_once_delivery = proto.Field(proto.BOOL, number=16,) topic_message_retention_duration = proto.Field( proto.MESSAGE, number=17, message=duration_pb2.Duration, ) @@ -1106,24 +1123,76 @@ class StreamingPullResponse(proto.Message): received_messages (Sequence[google.pubsub_v1.types.ReceivedMessage]): Received Pub/Sub messages. This will not be empty. + acknowlege_confirmation (google.pubsub_v1.types.StreamingPullResponse.AcknowledgeConfirmation): + 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): + This field will only be set if + ``enable_exactly_once_delivery`` is set to ``true``. subscription_properties (google.pubsub_v1.types.StreamingPullResponse.SubscriptionProperties): 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 (Sequence[str]): + Successfully processed acknowledgement IDs. + invalid_ack_ids (Sequence[str]): + List of acknowledgement IDs that were + malformed or whose acknowledgement deadline has + expired. + unordered_ack_ids (Sequence[str]): + List of acknowledgement IDs that were out of + order. + """ + + ack_ids = proto.RepeatedField(proto.STRING, number=1,) + invalid_ack_ids = proto.RepeatedField(proto.STRING, number=2,) + unordered_ack_ids = proto.RepeatedField(proto.STRING, number=3,) + + 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 (Sequence[str]): + Successfully processed acknowledgement IDs. + invalid_ack_ids (Sequence[str]): + List of acknowledgement IDs that were + malformed or whose acknowledgement deadline has + expired. + """ + + ack_ids = proto.RepeatedField(proto.STRING, number=1,) + invalid_ack_ids = proto.RepeatedField(proto.STRING, number=2,) + class SubscriptionProperties(proto.Message): r"""Subscription properties sent as part of the response. Attributes: + exactly_once_delivery_enabled (bool): + True iff exactly once delivery is enabled for + this subscription. message_ordering_enabled (bool): True iff message ordering is enabled for this subscription. """ + exactly_once_delivery_enabled = proto.Field(proto.BOOL, number=1,) message_ordering_enabled = proto.Field(proto.BOOL, number=2,) received_messages = proto.RepeatedField( proto.MESSAGE, number=1, message="ReceivedMessage", ) + acknowlege_confirmation = proto.Field( + proto.MESSAGE, number=2, message=AcknowledgeConfirmation, + ) + modify_ack_deadline_confirmation = proto.Field( + proto.MESSAGE, number=3, message=ModifyAckDeadlineConfirmation, + ) subscription_properties = proto.Field( proto.MESSAGE, number=4, message=SubscriptionProperties, ) diff --git a/owl-bot-staging/v1/.coveragerc b/owl-bot-staging/v1/.coveragerc deleted file mode 100644 index bcdb1c586..000000000 --- a/owl-bot-staging/v1/.coveragerc +++ /dev/null @@ -1,17 +0,0 @@ -[run] -branch = True - -[report] -show_missing = True -omit = - google/pubsub/__init__.py -exclude_lines = - # Re-enable the standard pragma - pragma: NO COVER - # Ignore debug-only repr - def __repr__ - # Ignore pkg_resources exceptions. - # This is added at the module level as a safeguard for if someone - # generates the code and tries to run it without pip installing. This - # makes it virtually impossible to test properly. - except pkg_resources.DistributionNotFound 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/conf.py b/owl-bot-staging/v1/docs/conf.py deleted file mode 100644 index 99cf05e5f..000000000 --- a/owl-bot-staging/v1/docs/conf.py +++ /dev/null @@ -1,376 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# -# google-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-pubsub" -copyright = u"2020, Google, LLC" -author = u"Google APIs" # TODO: autogenerate this bit - -# The version info for the project you're documenting, acts as replacement for -# |version| and |release|, also used in various other places throughout the -# built documents. -# -# The full version, including alpha/beta/rc tags. -release = __version__ -# The short X.Y version. -version = ".".join(release.split(".")[0:2]) - -# The language for content autogenerated by Sphinx. Refer to documentation -# for a list of supported languages. -# -# This is also used if you do content translation via gettext catalogs. -# Usually you set "language" from the command line for these cases. -language = None - -# There are two options for replacing |today|: either, you set today to some -# non-false value, then it is used: -# today = '' -# Else, today_fmt is used as the format for a strftime call. -# today_fmt = '%B %d, %Y' - -# List of patterns, relative to source directory, that match files and -# directories to ignore when looking for source files. -exclude_patterns = ["_build"] - -# The reST default role (used for this markup: `text`) to use for all -# documents. -# default_role = None - -# If true, '()' will be appended to :func: etc. cross-reference text. -# add_function_parentheses = True - -# If true, the current module name will be prepended to all description -# unit titles (such as .. function::). -# add_module_names = True - -# If true, sectionauthor and moduleauthor directives will be shown in the -# output. They are ignored by default. -# show_authors = False - -# The name of the Pygments (syntax highlighting) style to use. -pygments_style = "sphinx" - -# A list of ignored prefixes for module index sorting. -# modindex_common_prefix = [] - -# If true, keep warnings as "system message" paragraphs in the built documents. -# keep_warnings = False - -# If true, `todo` and `todoList` produce output, else they produce nothing. -todo_include_todos = True - - -# -- Options for HTML output ---------------------------------------------- - -# The theme to use for HTML and HTML Help pages. See the documentation for -# a list of builtin themes. -html_theme = "alabaster" - -# Theme options are theme-specific and customize the look and feel of a theme -# further. For a list of options available for each theme, see the -# documentation. -html_theme_options = { - "description": "Google 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-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-pubsub.tex", - u"google-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-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-pubsub", - u"google-pubsub Documentation", - author, - "google-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 964dfe575..000000000 --- a/owl-bot-staging/v1/docs/pubsub_v1/types.rst +++ /dev/null @@ -1,7 +0,0 @@ -Types for Google Pubsub v1 API -============================== - -.. automodule:: google.pubsub_v1.types - :members: - :undoc-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 b0a03eed8..000000000 --- a/owl-bot-staging/v1/google/pubsub/__init__.py +++ /dev/null @@ -1,143 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.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 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 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 CreateSchemaRequest -from google.pubsub_v1.types.schema import DeleteSchemaRequest -from google.pubsub_v1.types.schema import GetSchemaRequest -from google.pubsub_v1.types.schema import ListSchemasRequest -from google.pubsub_v1.types.schema import ListSchemasResponse -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', - 'CreateSnapshotRequest', - 'DeadLetterPolicy', - 'DeleteSnapshotRequest', - 'DeleteSubscriptionRequest', - 'DeleteTopicRequest', - 'DetachSubscriptionRequest', - 'DetachSubscriptionResponse', - 'ExpirationPolicy', - 'GetSnapshotRequest', - 'GetSubscriptionRequest', - 'GetTopicRequest', - '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', - 'CreateSchemaRequest', - 'DeleteSchemaRequest', - 'GetSchemaRequest', - 'ListSchemasRequest', - 'ListSchemasResponse', - 'Schema', - 'ValidateMessageRequest', - 'ValidateMessageResponse', - 'ValidateSchemaRequest', - 'ValidateSchemaResponse', - 'Encoding', - 'SchemaView', -) 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 9b0e37433..000000000 --- a/owl-bot-staging/v1/google/pubsub/py.typed +++ /dev/null @@ -1,2 +0,0 @@ -# Marker file for PEP 561. -# The google-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 e4f49d6e9..000000000 --- a/owl-bot-staging/v1/google/pubsub_v1/__init__.py +++ /dev/null @@ -1,144 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -from .services.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 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 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 CreateSchemaRequest -from .types.schema import DeleteSchemaRequest -from .types.schema import GetSchemaRequest -from .types.schema import ListSchemasRequest -from .types.schema import ListSchemasResponse -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', -'CreateSchemaRequest', -'CreateSnapshotRequest', -'DeadLetterPolicy', -'DeleteSchemaRequest', -'DeleteSnapshotRequest', -'DeleteSubscriptionRequest', -'DeleteTopicRequest', -'DetachSubscriptionRequest', -'DetachSubscriptionResponse', -'Encoding', -'ExpirationPolicy', -'GetSchemaRequest', -'GetSnapshotRequest', -'GetSubscriptionRequest', -'GetTopicRequest', -'ListSchemasRequest', -'ListSchemasResponse', -'ListSnapshotsRequest', -'ListSnapshotsResponse', -'ListSubscriptionsRequest', -'ListSubscriptionsResponse', -'ListTopicSnapshotsRequest', -'ListTopicSnapshotsResponse', -'ListTopicSubscriptionsRequest', -'ListTopicSubscriptionsResponse', -'ListTopicsRequest', -'ListTopicsResponse', -'MessageStoragePolicy', -'ModifyAckDeadlineRequest', -'ModifyPushConfigRequest', -'PublishRequest', -'PublishResponse', -'PublisherClient', -'PubsubMessage', -'PullRequest', -'PullResponse', -'PushConfig', -'ReceivedMessage', -'RetryPolicy', -'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 4c5b86bd1..000000000 --- a/owl-bot-staging/v1/google/pubsub_v1/gapic_metadata.json +++ /dev/null @@ -1,361 +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" - ] - } - } - } - } - }, - "SchemaService": { - "clients": { - "grpc": { - "libraryClient": "SchemaServiceClient", - "rpcs": { - "CreateSchema": { - "methods": [ - "create_schema" - ] - }, - "DeleteSchema": { - "methods": [ - "delete_schema" - ] - }, - "GetSchema": { - "methods": [ - "get_schema" - ] - }, - "ListSchemas": { - "methods": [ - "list_schemas" - ] - }, - "ValidateMessage": { - "methods": [ - "validate_message" - ] - }, - "ValidateSchema": { - "methods": [ - "validate_schema" - ] - } - } - }, - "grpc-async": { - "libraryClient": "SchemaServiceAsyncClient", - "rpcs": { - "CreateSchema": { - "methods": [ - "create_schema" - ] - }, - "DeleteSchema": { - "methods": [ - "delete_schema" - ] - }, - "GetSchema": { - "methods": [ - "get_schema" - ] - }, - "ListSchemas": { - "methods": [ - "list_schemas" - ] - }, - "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" - ] - } - } - } - } - } - } -} 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 9b0e37433..000000000 --- a/owl-bot-staging/v1/google/pubsub_v1/py.typed +++ /dev/null @@ -1,2 +0,0 @@ -# Marker file for PEP 561. -# The google-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 4de65971c..000000000 --- a/owl-bot-staging/v1/google/pubsub_v1/services/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# diff --git a/owl-bot-staging/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 d2aa30c85..000000000 --- a/owl-bot-staging/v1/google/pubsub_v1/services/publisher/__init__.py +++ /dev/null @@ -1,22 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from .client import 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 3df6a5ad5..000000000 --- a/owl-bot-staging/v1/google/pubsub_v1/services/publisher/async_client.py +++ /dev/null @@ -1,1409 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import functools -import re -from typing import Dict, Optional, Sequence, Tuple, Type, Union -import pkg_resources - -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 as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # 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.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 - - DEFAULT_ENDPOINT = PublisherClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = PublisherClient.DEFAULT_MTLS_ENDPOINT - - 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 variabel 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 - - get_transport_class = functools.partial(type(PublisherClient).get_transport_class, type(PublisherClient)) - - def __init__(self, *, - credentials: ga_credentials.Credentials = None, - transport: Union[str, PublisherTransport] = "grpc_asyncio", - client_options: ClientOptions = 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 (Union[str, ~.PublisherTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (ClientOptions): Custom options for the client. It - won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - """ - self._client = PublisherClient( - credentials=credentials, - transport=transport, - client_options=client_options, - client_info=client_info, - - ) - - async def create_topic(self, - request: Union[pubsub.Topic, dict] = None, - *, - name: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - 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/admin#resource_names). - - - .. code-block:: - - 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 response - print(response) - - Args: - request (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.Retry): Designation of what errors, if any, - should be retried. - timeout (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.") - - 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 = gapic_v1.method_async.wrap_method( - self._client._transport.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=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def update_topic(self, - request: Union[pubsub.UpdateTopicRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pubsub.Topic: - r"""Updates an existing topic. Note that certain - properties of a topic are not modifiable. - - - .. code-block:: - - 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 response - print(response) - - Args: - request (Union[google.pubsub_v1.types.UpdateTopicRequest, dict]): - 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: - google.pubsub_v1.types.Topic: - A topic resource. - """ - # Create or coerce a protobuf request object. - request = pubsub.UpdateTopicRequest(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.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=DEFAULT_CLIENT_INFO, - ) - - # 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), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def publish(self, - request: Union[pubsub.PublishRequest, dict] = None, - *, - topic: str = None, - messages: Sequence[pubsub.PubsubMessage] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - 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:: - - 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 response - print(response) - - Args: - request (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:`Sequence[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.") - - 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 = gapic_v1.method_async.wrap_method( - self._client._transport.publish, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, 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=DEFAULT_CLIENT_INFO, - ) - - # 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), - )), - ) - - # 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: Union[pubsub.GetTopicRequest, dict] = None, - *, - topic: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pubsub.Topic: - r"""Gets the configuration of a topic. - - .. code-block:: - - 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 response - print(response) - - Args: - request (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.Retry): Designation of what errors, if any, - should be retried. - timeout (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.") - - 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 = gapic_v1.method_async.wrap_method( - self._client._transport.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=DEFAULT_CLIENT_INFO, - ) - - # 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), - )), - ) - - # 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: Union[pubsub.ListTopicsRequest, dict] = None, - *, - project: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListTopicsAsyncPager: - r"""Lists matching topics. - - .. code-block:: - - 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) - 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 (: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.Retry): Designation of what errors, if any, - should be retried. - timeout (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.") - - 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 = gapic_v1.method_async.wrap_method( - self._client._transport.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=DEFAULT_CLIENT_INFO, - ) - - # 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), - )), - ) - - # 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, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def list_topic_subscriptions(self, - request: Union[pubsub.ListTopicSubscriptionsRequest, dict] = None, - *, - topic: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListTopicSubscriptionsAsyncPager: - r"""Lists the names of the attached subscriptions on this - topic. - - - .. code-block:: - - 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) - 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 (: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.Retry): Designation of what errors, if any, - should be retried. - timeout (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.") - - 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 = gapic_v1.method_async.wrap_method( - self._client._transport.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=DEFAULT_CLIENT_INFO, - ) - - # 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), - )), - ) - - # 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, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def list_topic_snapshots(self, - request: Union[pubsub.ListTopicSnapshotsRequest, dict] = None, - *, - topic: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - 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:: - - 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) - 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 (: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.Retry): Designation of what errors, if any, - should be retried. - timeout (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.") - - 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 = gapic_v1.method_async.wrap_method( - self._client._transport.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=DEFAULT_CLIENT_INFO, - ) - - # 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), - )), - ) - - # 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, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def delete_topic(self, - request: Union[pubsub.DeleteTopicRequest, dict] = None, - *, - topic: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - 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:: - - 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 - response = client.delete_topic(request=request) - - Args: - request (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.Retry): Designation of what errors, if any, - should be 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.") - - 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 = gapic_v1.method_async.wrap_method( - self._client._transport.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=DEFAULT_CLIENT_INFO, - ) - - # 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), - )), - ) - - # Send the request. - await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - async def detach_subscription(self, - request: Union[pubsub.DetachSubscriptionRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - 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:: - - 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 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. - request = pubsub.DetachSubscriptionRequest(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.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=DEFAULT_CLIENT_INFO, - ) - - # 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), - )), - ) - - # 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: iam_policy_pb2.SetIamPolicyRequest = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - 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.Retry): Designation of what errors, if any, - should be retried. - 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),)), - ) - - # 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: iam_policy_pb2.GetIamPolicyRequest = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - 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_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),)), - ) - - # 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: iam_policy_pb2.TestIamPermissionsRequest = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - 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.Retry): Designation of what errors, if any, - should be retried. - 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),)), - ) - - # Send the request. - response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - async def __aenter__(self): - return self - - async def __aexit__(self, exc_type, exc, tb): - await self.transport.close() - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-pubsub", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__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 52ab9bbf6..000000000 --- a/owl-bot-staging/v1/google/pubsub_v1/services/publisher/client.py +++ /dev/null @@ -1,1571 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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, Optional, Sequence, Tuple, Type, Union -import pkg_resources - -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] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # 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.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 - - -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 - - def get_transport_class(cls, - label: 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") - - DEFAULT_ENDPOINT = "pubsub.googleapis.com" - DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore - DEFAULT_ENDPOINT - ) - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - Args: - info (dict): The service account private key info. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - 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): - """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 variabel 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. - """ - 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 - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Union[str, PublisherTransport, None] = None, - client_options: Optional[client_options_lib.ClientOptions] = 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 (Union[str, PublisherTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. It won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - """ - if isinstance(client_options, dict): - client_options = client_options_lib.from_dict(client_options) - if client_options is None: - client_options = client_options_lib.ClientOptions() - - api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) - - api_key_value = getattr(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. - if isinstance(transport, PublisherTransport): - # transport is a PublisherTransport instance. - if credentials or client_options.credentials_file or api_key_value: - raise ValueError("When providing a transport instance, " - "provide its credentials directly.") - if client_options.scopes: - raise ValueError( - "When providing a transport instance, provide its scopes " - "directly." - ) - self._transport = transport - else: - 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 = type(self).get_transport_class(transport) - self._transport = Transport( - credentials=credentials, - credentials_file=client_options.credentials_file, - host=api_endpoint, - scopes=client_options.scopes, - client_cert_source_for_mtls=client_cert_source_func, - quota_project_id=client_options.quota_project_id, - client_info=client_info, - always_use_jwt_access=True, - ) - - def create_topic(self, - request: Union[pubsub.Topic, dict] = None, - *, - name: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - 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/admin#resource_names). - - - - .. code-block:: - - 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 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.') - - # Minor optimization to avoid making a copy if the user passes - # in a pubsub.Topic. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - 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), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def update_topic(self, - request: Union[pubsub.UpdateTopicRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pubsub.Topic: - r"""Updates an existing topic. Note that certain - properties of a topic are not modifiable. - - - - .. code-block:: - - 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 response - print(response) - - Args: - request (Union[google.pubsub_v1.types.UpdateTopicRequest, dict]): - 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: - google.pubsub_v1.types.Topic: - A topic resource. - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a pubsub.UpdateTopicRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, pubsub.UpdateTopicRequest): - request = pubsub.UpdateTopicRequest(request) - - # 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), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def publish(self, - request: Union[pubsub.PublishRequest, dict] = None, - *, - topic: str = None, - messages: Sequence[pubsub.PubsubMessage] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - 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:: - - 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 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 (Sequence[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.') - - # Minor optimization to avoid making a copy if the user passes - # in a pubsub.PublishRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - 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), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def get_topic(self, - request: Union[pubsub.GetTopicRequest, dict] = None, - *, - topic: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pubsub.Topic: - r"""Gets the configuration of a topic. - - - .. code-block:: - - 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 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.') - - # Minor optimization to avoid making a copy if the user passes - # in a pubsub.GetTopicRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - 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), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def list_topics(self, - request: Union[pubsub.ListTopicsRequest, dict] = None, - *, - project: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListTopicsPager: - r"""Lists matching topics. - - - .. code-block:: - - 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) - 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.') - - # Minor optimization to avoid making a copy if the user passes - # in a pubsub.ListTopicsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - 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), - )), - ) - - # 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, - metadata=metadata, - ) - - # Done; return the response. - return response - - def list_topic_subscriptions(self, - request: Union[pubsub.ListTopicSubscriptionsRequest, dict] = None, - *, - topic: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListTopicSubscriptionsPager: - r"""Lists the names of the attached subscriptions on this - topic. - - - - .. code-block:: - - 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) - 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.') - - # Minor optimization to avoid making a copy if the user passes - # in a pubsub.ListTopicSubscriptionsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - 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), - )), - ) - - # 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, - metadata=metadata, - ) - - # Done; return the response. - return response - - def list_topic_snapshots(self, - request: Union[pubsub.ListTopicSnapshotsRequest, dict] = None, - *, - topic: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - 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:: - - 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) - 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.') - - # Minor optimization to avoid making a copy if the user passes - # in a pubsub.ListTopicSnapshotsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - 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), - )), - ) - - # 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, - metadata=metadata, - ) - - # Done; return the response. - return response - - def delete_topic(self, - request: Union[pubsub.DeleteTopicRequest, dict] = None, - *, - topic: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - 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:: - - 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 - response = 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.') - - # Minor optimization to avoid making a copy if the user passes - # in a pubsub.DeleteTopicRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - 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), - )), - ) - - # Send the request. - rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - def detach_subscription(self, - request: Union[pubsub.DetachSubscriptionRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - 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:: - - 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 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. - # Minor optimization to avoid making a copy if the user passes - # in a pubsub.DetachSubscriptionRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - 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), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def __enter__(self): - 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: iam_policy_pb2.SetIamPolicyRequest = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - 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),)), - ) - - # Send the request. - response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - def get_iam_policy( - self, - request: iam_policy_pb2.GetIamPolicyRequest = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - 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),)), - ) - - # Send the request. - response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - def test_iam_permissions( - self, - request: iam_policy_pb2.TestIamPermissionsRequest = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - 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),)), - ) - - # Send the request. - response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-pubsub", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__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 82de4edc1..000000000 --- a/owl-bot-staging/v1/google/pubsub_v1/services/publisher/pagers.py +++ /dev/null @@ -1,381 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from typing import Any, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator - -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, - *, - 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. - 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._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, 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, - *, - 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. - 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._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, 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, - *, - 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. - 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._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, 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, - *, - 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. - 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._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, 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, - *, - 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. - 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._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, 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, - *, - 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. - 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._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, 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 004f40449..000000000 --- a/owl-bot-staging/v1/google/pubsub_v1/services/publisher/transports/__init__.py +++ /dev/null @@ -1,33 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -from typing import Dict, Type - -from .base import PublisherTransport -from .grpc import PublisherGrpcTransport -from .grpc_asyncio import PublisherGrpcAsyncIOTransport - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[PublisherTransport]] -_transport_registry['grpc'] = PublisherGrpcTransport -_transport_registry['grpc_asyncio'] = PublisherGrpcAsyncIOTransport - -__all__ = ( - 'PublisherTransport', - 'PublisherGrpcTransport', - 'PublisherGrpcAsyncIOTransport', -) 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 a4da881c2..000000000 --- a/owl-bot-staging/v1/google/pubsub_v1/services/publisher/transports/base.py +++ /dev/null @@ -1,358 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import abc -from typing import Awaitable, Callable, Dict, Optional, Sequence, Union -import pkg_resources - -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 - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - 'google-pubsub', - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -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: 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, - **kwargs, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A list of scopes. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - """ - # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ':' not in host: - host += ':443' - self._host = host - - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - - # Save the scopes. - self._scopes = scopes - - # If no credentials are provided, then determine the appropriate - # defaults. - if credentials and credentials_file: - raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") - - if credentials_file is not None: - credentials, _ = google.auth.load_credentials_from_file( - credentials_file, - **scopes_kwargs, - quota_project_id=quota_project_id - ) - elif credentials is None: - credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) - - # 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 - - 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=1.3, 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() - -__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 dd8bb68dc..000000000 --- a/owl-bot-staging/v1/google/pubsub_v1/services/publisher/transports/grpc.py +++ /dev/null @@ -1,567 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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: ga_credentials.Credentials = None, - credentials_file: str = None, - scopes: Sequence[str] = None, - channel: grpc.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - channel (Optional[grpc.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or 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 ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - 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 channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - 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: ga_credentials.Credentials = None, - credentials_file: str = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> grpc.Channel: - """Create and return a gRPC channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - grpc.Channel: A gRPC channel object. - - Raises: - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - - 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/admin#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. 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() - -__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 e369f866f..000000000 --- a/owl-bot-staging/v1/google/pubsub_v1/services/publisher/transports/grpc_asyncio.py +++ /dev/null @@ -1,572 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.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: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> aio.Channel: - """Create and return a gRPC AsyncIO channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - aio.Channel: A gRPC AsyncIO channel object. - """ - - 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: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: aio.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, - quota_project_id=None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - channel (Optional[aio.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or 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 ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - 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 channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - 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/admin#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. 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 close(self): - return self.grpc_channel.close() - - -__all__ = ( - 'PublisherGrpcAsyncIOTransport', -) 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 3887454c1..000000000 --- a/owl-bot-staging/v1/google/pubsub_v1/services/schema_service/__init__.py +++ /dev/null @@ -1,22 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from .client import 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 7e14380ce..000000000 --- a/owl-bot-staging/v1/google/pubsub_v1/services/schema_service/async_client.py +++ /dev/null @@ -1,1060 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import functools -import re -from typing import Dict, Optional, Sequence, Tuple, Type, Union -import pkg_resources - -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 as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - -from google.iam.v1 import iam_policy_pb2 # type: ignore -from google.iam.v1 import policy_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 - - DEFAULT_ENDPOINT = SchemaServiceClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = SchemaServiceClient.DEFAULT_MTLS_ENDPOINT - - 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 variabel 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 - - get_transport_class = functools.partial(type(SchemaServiceClient).get_transport_class, type(SchemaServiceClient)) - - def __init__(self, *, - credentials: ga_credentials.Credentials = None, - transport: Union[str, SchemaServiceTransport] = "grpc_asyncio", - client_options: ClientOptions = 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 (Union[str, ~.SchemaServiceTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (ClientOptions): Custom options for the client. It - won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - """ - self._client = SchemaServiceClient( - credentials=credentials, - transport=transport, - client_options=client_options, - client_info=client_info, - - ) - - async def create_schema(self, - request: Union[gp_schema.CreateSchemaRequest, dict] = None, - *, - parent: str = None, - schema: gp_schema.Schema = None, - schema_id: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gp_schema.Schema: - r"""Creates a schema. - - .. code-block:: - - 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 response - print(response) - - Args: - request (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/admin#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.") - - 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 = gapic_v1.method_async.wrap_method( - self._client._transport.create_schema, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def get_schema(self, - request: Union[schema.GetSchemaRequest, dict] = None, - *, - name: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> schema.Schema: - r"""Gets a schema. - - .. code-block:: - - 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 response - print(response) - - Args: - request (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.Retry): Designation of what errors, if any, - should be retried. - timeout (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.") - - 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 = gapic_v1.method_async.wrap_method( - self._client._transport.get_schema, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def list_schemas(self, - request: Union[schema.ListSchemasRequest, dict] = None, - *, - parent: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListSchemasAsyncPager: - r"""Lists schemas in a project. - - .. code-block:: - - 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) - 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 (: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.Retry): Designation of what errors, if any, - should be retried. - timeout (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.") - - 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 = gapic_v1.method_async.wrap_method( - self._client._transport.list_schemas, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__aiter__` convenience method. - response = pagers.ListSchemasAsyncPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def delete_schema(self, - request: Union[schema.DeleteSchemaRequest, dict] = None, - *, - name: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes a schema. - - .. code-block:: - - 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 - response = client.delete_schema(request=request) - - Args: - request (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.Retry): Designation of what errors, if any, - should be 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.") - - 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 = gapic_v1.method_async.wrap_method( - self._client._transport.delete_schema, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - async def validate_schema(self, - request: Union[gp_schema.ValidateSchemaRequest, dict] = None, - *, - parent: str = None, - schema: gp_schema.Schema = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gp_schema.ValidateSchemaResponse: - r"""Validates a schema. - - .. code-block:: - - 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 response - print(response) - - Args: - request (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.Retry): Designation of what errors, if any, - should be retried. - timeout (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.") - - 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 = gapic_v1.method_async.wrap_method( - self._client._transport.validate_schema, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def validate_message(self, - request: Union[schema.ValidateMessageRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> schema.ValidateMessageResponse: - r"""Validates a message against a schema. - - .. code-block:: - - 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 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. - request = schema.ValidateMessageRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.validate_message, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def set_iam_policy( - self, - request: iam_policy_pb2.SetIamPolicyRequest = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - 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.Retry): Designation of what errors, if any, - should be retried. - 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),)), - ) - - # 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: iam_policy_pb2.GetIamPolicyRequest = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - 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_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),)), - ) - - # 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: iam_policy_pb2.TestIamPermissionsRequest = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - 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.Retry): Designation of what errors, if any, - should be retried. - 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),)), - ) - - # Send the request. - response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - async def __aenter__(self): - return self - - async def __aexit__(self, exc_type, exc, tb): - await self.transport.close() - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-pubsub", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__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 0e4b32957..000000000 --- a/owl-bot-staging/v1/google/pubsub_v1/services/schema_service/client.py +++ /dev/null @@ -1,1268 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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, Optional, Sequence, Tuple, Type, Union -import pkg_resources - -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] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - -from google.iam.v1 import iam_policy_pb2 # type: ignore -from google.iam.v1 import policy_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 - - -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 - - def get_transport_class(cls, - label: 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") - - DEFAULT_ENDPOINT = "pubsub.googleapis.com" - DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore - DEFAULT_ENDPOINT - ) - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - Args: - info (dict): The service account private key info. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - 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): - """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 variabel 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. - """ - 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 - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Union[str, SchemaServiceTransport, None] = None, - client_options: Optional[client_options_lib.ClientOptions] = 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 (Union[str, SchemaServiceTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. It won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - """ - if isinstance(client_options, dict): - client_options = client_options_lib.from_dict(client_options) - if client_options is None: - client_options = client_options_lib.ClientOptions() - - api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) - - api_key_value = getattr(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. - if isinstance(transport, SchemaServiceTransport): - # transport is a SchemaServiceTransport instance. - if credentials or client_options.credentials_file or api_key_value: - raise ValueError("When providing a transport instance, " - "provide its credentials directly.") - if client_options.scopes: - raise ValueError( - "When providing a transport instance, provide its scopes " - "directly." - ) - self._transport = transport - else: - 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 = type(self).get_transport_class(transport) - self._transport = Transport( - credentials=credentials, - credentials_file=client_options.credentials_file, - host=api_endpoint, - scopes=client_options.scopes, - client_cert_source_for_mtls=client_cert_source_func, - quota_project_id=client_options.quota_project_id, - client_info=client_info, - always_use_jwt_access=True, - ) - - def create_schema(self, - request: Union[gp_schema.CreateSchemaRequest, dict] = None, - *, - parent: str = None, - schema: gp_schema.Schema = None, - schema_id: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gp_schema.Schema: - r"""Creates a schema. - - - .. code-block:: - - 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 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/admin#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.') - - # Minor optimization to avoid making a copy if the user passes - # in a gp_schema.CreateSchemaRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - 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), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def get_schema(self, - request: Union[schema.GetSchemaRequest, dict] = None, - *, - name: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> schema.Schema: - r"""Gets a schema. - - - .. code-block:: - - 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 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.') - - # Minor optimization to avoid making a copy if the user passes - # in a schema.GetSchemaRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - 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), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def list_schemas(self, - request: Union[schema.ListSchemasRequest, dict] = None, - *, - parent: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListSchemasPager: - r"""Lists schemas in a project. - - - .. code-block:: - - 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) - 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.') - - # Minor optimization to avoid making a copy if the user passes - # in a schema.ListSchemasRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - 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), - )), - ) - - # 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, - metadata=metadata, - ) - - # Done; return the response. - return response - - def delete_schema(self, - request: Union[schema.DeleteSchemaRequest, dict] = None, - *, - name: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes a schema. - - - .. code-block:: - - 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 - response = 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.') - - # Minor optimization to avoid making a copy if the user passes - # in a schema.DeleteSchemaRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - 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), - )), - ) - - # Send the request. - rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - def validate_schema(self, - request: Union[gp_schema.ValidateSchemaRequest, dict] = None, - *, - parent: str = None, - schema: gp_schema.Schema = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gp_schema.ValidateSchemaResponse: - r"""Validates a schema. - - - .. code-block:: - - 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 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.') - - # Minor optimization to avoid making a copy if the user passes - # in a gp_schema.ValidateSchemaRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - 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), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def validate_message(self, - request: Union[schema.ValidateMessageRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> schema.ValidateMessageResponse: - r"""Validates a message against a schema. - - - .. code-block:: - - 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 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. - # Minor optimization to avoid making a copy if the user passes - # in a schema.ValidateMessageRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - 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), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def __enter__(self): - 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: iam_policy_pb2.SetIamPolicyRequest = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - 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),)), - ) - - # Send the request. - response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - def get_iam_policy( - self, - request: iam_policy_pb2.GetIamPolicyRequest = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - 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),)), - ) - - # Send the request. - response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - def test_iam_permissions( - self, - request: iam_policy_pb2.TestIamPermissionsRequest = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - 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),)), - ) - - # Send the request. - response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-pubsub", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__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 1a950dcd5..000000000 --- a/owl-bot-staging/v1/google/pubsub_v1/services/schema_service/pagers.py +++ /dev/null @@ -1,139 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from typing import Any, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator - -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, - *, - 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. - 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._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, 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, - *, - 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. - 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._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, 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 f1a10058f..000000000 --- a/owl-bot-staging/v1/google/pubsub_v1/services/schema_service/transports/__init__.py +++ /dev/null @@ -1,33 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -from typing import Dict, Type - -from .base import SchemaServiceTransport -from .grpc import SchemaServiceGrpcTransport -from .grpc_asyncio import SchemaServiceGrpcAsyncIOTransport - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[SchemaServiceTransport]] -_transport_registry['grpc'] = SchemaServiceGrpcTransport -_transport_registry['grpc_asyncio'] = SchemaServiceGrpcAsyncIOTransport - -__all__ = ( - 'SchemaServiceTransport', - 'SchemaServiceGrpcTransport', - 'SchemaServiceGrpcAsyncIOTransport', -) 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 6d57d3e88..000000000 --- a/owl-bot-staging/v1/google/pubsub_v1/services/schema_service/transports/base.py +++ /dev/null @@ -1,249 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import abc -from typing import Awaitable, Callable, Dict, Optional, Sequence, Union -import pkg_resources - -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 - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - 'google-pubsub', - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -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: 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, - **kwargs, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A list of scopes. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - """ - # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ':' not in host: - host += ':443' - self._host = host - - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - - # Save the scopes. - self._scopes = scopes - - # If no credentials are provided, then determine the appropriate - # defaults. - if credentials and credentials_file: - raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") - - if credentials_file is not None: - credentials, _ = google.auth.load_credentials_from_file( - credentials_file, - **scopes_kwargs, - quota_project_id=quota_project_id - ) - elif credentials is None: - credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) - - # 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 - - 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_timeout=None, - client_info=client_info, - ), - self.get_schema: gapic_v1.method.wrap_method( - self.get_schema, - default_timeout=None, - client_info=client_info, - ), - self.list_schemas: gapic_v1.method.wrap_method( - self.list_schemas, - default_timeout=None, - client_info=client_info, - ), - self.delete_schema: gapic_v1.method.wrap_method( - self.delete_schema, - default_timeout=None, - client_info=client_info, - ), - self.validate_schema: gapic_v1.method.wrap_method( - self.validate_schema, - default_timeout=None, - client_info=client_info, - ), - self.validate_message: gapic_v1.method.wrap_method( - self.validate_message, - default_timeout=None, - client_info=client_info, - ), - } - - def close(self): - """Closes resources associated with the transport. - - .. warning:: - Only call this method if the transport is NOT shared - with other clients - this may cause errors in other clients! - """ - raise NotImplementedError() - - @property - def create_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 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() - -__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 b094262fe..000000000 --- a/owl-bot-staging/v1/google/pubsub_v1/services/schema_service/transports/grpc.py +++ /dev/null @@ -1,470 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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: ga_credentials.Credentials = None, - credentials_file: str = None, - scopes: Sequence[str] = None, - channel: grpc.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - channel (Optional[grpc.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or 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 ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - 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 channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - 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: ga_credentials.Credentials = None, - credentials_file: str = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> grpc.Channel: - """Create and return a gRPC channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - grpc.Channel: A gRPC channel object. - - Raises: - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - - 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 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() - -__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 e59c24506..000000000 --- a/owl-bot-staging/v1/google/pubsub_v1/services/schema_service/transports/grpc_asyncio.py +++ /dev/null @@ -1,475 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.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: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> aio.Channel: - """Create and return a gRPC AsyncIO channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - aio.Channel: A gRPC AsyncIO channel object. - """ - - 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: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: aio.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, - quota_project_id=None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - channel (Optional[aio.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or 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 ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - 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 channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - 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 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 close(self): - return self.grpc_channel.close() - - -__all__ = ( - 'SchemaServiceGrpcAsyncIOTransport', -) 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 0bdb44da8..000000000 --- a/owl-bot-staging/v1/google/pubsub_v1/services/subscriber/__init__.py +++ /dev/null @@ -1,22 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from .client import 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 8a364687e..000000000 --- a/owl-bot-staging/v1/google/pubsub_v1/services/subscriber/async_client.py +++ /dev/null @@ -1,2277 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import functools -import re -from typing import Dict, Optional, AsyncIterable, Awaitable, AsyncIterator, Sequence, Tuple, Type, Union -import pkg_resources - -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 as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # 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 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 - - DEFAULT_ENDPOINT = SubscriberClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = SubscriberClient.DEFAULT_MTLS_ENDPOINT - - 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 variabel 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 - - get_transport_class = functools.partial(type(SubscriberClient).get_transport_class, type(SubscriberClient)) - - def __init__(self, *, - credentials: ga_credentials.Credentials = None, - transport: Union[str, SubscriberTransport] = "grpc_asyncio", - client_options: ClientOptions = 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 (Union[str, ~.SubscriberTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (ClientOptions): Custom options for the client. It - won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - """ - self._client = SubscriberClient( - credentials=credentials, - transport=transport, - client_options=client_options, - client_info=client_info, - - ) - - async def create_subscription(self, - request: Union[pubsub.Subscription, dict] = None, - *, - name: str = None, - topic: str = None, - push_config: pubsub.PushConfig = None, - ack_deadline_seconds: int = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - 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/admin#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/admin#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:: - - 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 response - print(response) - - Args: - request (Union[google.pubsub_v1.types.Subscription, dict]): - The request object. A subscription resource. - 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`): - If push delivery is used with this subscription, this - field is used to configure it. An empty ``pushConfig`` - signifies that the subscriber will pull and ack messages - using API methods. - - 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`): - 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. - """ - # Create or coerce a 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.") - - 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 = gapic_v1.method_async.wrap_method( - self._client._transport.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=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def get_subscription(self, - request: Union[pubsub.GetSubscriptionRequest, dict] = None, - *, - subscription: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pubsub.Subscription: - r"""Gets the configuration details of a subscription. - - .. code-block:: - - 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 response - print(response) - - Args: - request (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.Retry): Designation of what errors, if any, - should be retried. - timeout (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. - """ - # Create or coerce a 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.") - - 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 = gapic_v1.method_async.wrap_method( - self._client._transport.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=DEFAULT_CLIENT_INFO, - ) - - # 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), - )), - ) - - # 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: Union[pubsub.UpdateSubscriptionRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pubsub.Subscription: - r"""Updates an existing subscription. Note that certain - properties of a subscription, such as its topic, are not - modifiable. - - - .. code-block:: - - 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 response - print(response) - - Args: - request (Union[google.pubsub_v1.types.UpdateSubscriptionRequest, dict]): - 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: - google.pubsub_v1.types.Subscription: - A subscription resource. - """ - # Create or coerce a protobuf request object. - request = pubsub.UpdateSubscriptionRequest(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.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=DEFAULT_CLIENT_INFO, - ) - - # 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), - )), - ) - - # 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: Union[pubsub.ListSubscriptionsRequest, dict] = None, - *, - project: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListSubscriptionsAsyncPager: - r"""Lists matching subscriptions. - - .. code-block:: - - 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) - 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 (: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.Retry): Designation of what errors, if any, - should be retried. - timeout (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.") - - 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 = gapic_v1.method_async.wrap_method( - self._client._transport.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=DEFAULT_CLIENT_INFO, - ) - - # 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), - )), - ) - - # 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, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def delete_subscription(self, - request: Union[pubsub.DeleteSubscriptionRequest, dict] = None, - *, - subscription: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - 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:: - - 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 - response = client.delete_subscription(request=request) - - Args: - request (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.Retry): Designation of what errors, if any, - should be 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.") - - 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 = gapic_v1.method_async.wrap_method( - self._client._transport.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=DEFAULT_CLIENT_INFO, - ) - - # 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), - )), - ) - - # Send the request. - await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - async def modify_ack_deadline(self, - request: Union[pubsub.ModifyAckDeadlineRequest, dict] = None, - *, - subscription: str = None, - ack_ids: Sequence[str] = None, - ack_deadline_seconds: int = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - 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:: - - 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_value_1', 'ack_ids_value_2'], - ack_deadline_seconds=2066, - ) - - # Make the request - response = client.modify_ack_deadline(request=request) - - Args: - request (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:`Sequence[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 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.") - - 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 = gapic_v1.method_async.wrap_method( - self._client._transport.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=DEFAULT_CLIENT_INFO, - ) - - # 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), - )), - ) - - # Send the request. - await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - async def acknowledge(self, - request: Union[pubsub.AcknowledgeRequest, dict] = None, - *, - subscription: str = None, - ack_ids: Sequence[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - 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:: - - 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_value_1', 'ack_ids_value_2'], - ) - - # Make the request - response = client.acknowledge(request=request) - - Args: - request (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:`Sequence[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.") - - 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 = gapic_v1.method_async.wrap_method( - self._client._transport.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=DEFAULT_CLIENT_INFO, - ) - - # 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), - )), - ) - - # Send the request. - await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - async def pull(self, - request: Union[pubsub.PullRequest, dict] = None, - *, - subscription: str = None, - return_immediately: bool = None, - max_messages: int = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pubsub.PullResponse: - r"""Pulls messages from the server. The server may return - ``UNAVAILABLE`` if there are too many concurrent pull requests - pending for the given subscription. - - - .. code-block:: - - 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 response - print(response) - - Args: - request (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.Retry): Designation of what errors, if any, - should be retried. - timeout (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.") - - 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 = gapic_v1.method_async.wrap_method( - self._client._transport.pull, - 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=DEFAULT_CLIENT_INFO, - ) - - # 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), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def streaming_pull(self, - requests: AsyncIterator[pubsub.StreamingPullRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - 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:: - - 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()) - 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.Retry): Designation of what errors, if any, - should be retried. - 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 = gapic_v1.method_async.wrap_method( - self._client._transport.streaming_pull, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, 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=DEFAULT_CLIENT_INFO, - ) - - # 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: Union[pubsub.ModifyPushConfigRequest, dict] = None, - *, - subscription: str = None, - push_config: pubsub.PushConfig = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - 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:: - - 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 - response = client.modify_push_config(request=request) - - Args: - request (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.Retry): Designation of what errors, if any, - should be 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.") - - 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 = gapic_v1.method_async.wrap_method( - self._client._transport.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=DEFAULT_CLIENT_INFO, - ) - - # 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), - )), - ) - - # Send the request. - await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - async def get_snapshot(self, - request: Union[pubsub.GetSnapshotRequest, dict] = None, - *, - snapshot: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - 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:: - - 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 response - print(response) - - Args: - request (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.Retry): Designation of what errors, if any, - should be retried. - timeout (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.") - - 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 = gapic_v1.method_async.wrap_method( - self._client._transport.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=DEFAULT_CLIENT_INFO, - ) - - # 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), - )), - ) - - # 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: Union[pubsub.ListSnapshotsRequest, dict] = None, - *, - project: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - 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:: - - 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) - 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 (: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.Retry): Designation of what errors, if any, - should be retried. - timeout (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.") - - 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 = gapic_v1.method_async.wrap_method( - self._client._transport.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=DEFAULT_CLIENT_INFO, - ) - - # 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), - )), - ) - - # 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, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def create_snapshot(self, - request: Union[pubsub.CreateSnapshotRequest, dict] = None, - *, - name: str = None, - subscription: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - 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/admin#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:: - - 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 response - print(response) - - Args: - request (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.Retry): Designation of what errors, if any, - should be retried. - timeout (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.") - - 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 = gapic_v1.method_async.wrap_method( - self._client._transport.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=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def update_snapshot(self, - request: Union[pubsub.UpdateSnapshotRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pubsub.Snapshot: - r"""Updates an existing 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:: - - 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 response - print(response) - - Args: - request (Union[google.pubsub_v1.types.UpdateSnapshotRequest, dict]): - 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: - 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. - request = pubsub.UpdateSnapshotRequest(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.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=DEFAULT_CLIENT_INFO, - ) - - # 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), - )), - ) - - # 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: Union[pubsub.DeleteSnapshotRequest, dict] = None, - *, - snapshot: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - 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:: - - 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 - response = client.delete_snapshot(request=request) - - Args: - request (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.Retry): Designation of what errors, if any, - should be 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.") - - 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 = gapic_v1.method_async.wrap_method( - self._client._transport.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=DEFAULT_CLIENT_INFO, - ) - - # 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), - )), - ) - - # Send the request. - await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - async def seek(self, - request: Union[pubsub.SeekRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - 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:: - - 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 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. - request = pubsub.SeekRequest(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.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=DEFAULT_CLIENT_INFO, - ) - - # 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), - )), - ) - - # 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: iam_policy_pb2.SetIamPolicyRequest = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - 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.Retry): Designation of what errors, if any, - should be retried. - 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),)), - ) - - # 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: iam_policy_pb2.GetIamPolicyRequest = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - 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_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),)), - ) - - # 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: iam_policy_pb2.TestIamPermissionsRequest = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - 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.Retry): Designation of what errors, if any, - should be retried. - 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),)), - ) - - # Send the request. - response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - async def __aenter__(self): - return self - - async def __aexit__(self, exc_type, exc, tb): - await self.transport.close() - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-pubsub", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__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 bdbbf3e0e..000000000 --- a/owl-bot-staging/v1/google/pubsub_v1/services/subscriber/client.py +++ /dev/null @@ -1,2397 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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, Optional, Iterable, Iterator, Sequence, Tuple, Type, Union -import pkg_resources - -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] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # 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 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 - - -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 - - def get_transport_class(cls, - label: 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") - - DEFAULT_ENDPOINT = "pubsub.googleapis.com" - DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore - DEFAULT_ENDPOINT - ) - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - Args: - info (dict): The service account private key info. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - 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): - """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 variabel 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. - """ - 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 - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Union[str, SubscriberTransport, None] = None, - client_options: Optional[client_options_lib.ClientOptions] = 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 (Union[str, SubscriberTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. It won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - """ - if isinstance(client_options, dict): - client_options = client_options_lib.from_dict(client_options) - if client_options is None: - client_options = client_options_lib.ClientOptions() - - api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) - - api_key_value = getattr(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. - if isinstance(transport, SubscriberTransport): - # transport is a SubscriberTransport instance. - if credentials or client_options.credentials_file or api_key_value: - raise ValueError("When providing a transport instance, " - "provide its credentials directly.") - if client_options.scopes: - raise ValueError( - "When providing a transport instance, provide its scopes " - "directly." - ) - self._transport = transport - else: - 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 = type(self).get_transport_class(transport) - self._transport = Transport( - credentials=credentials, - credentials_file=client_options.credentials_file, - host=api_endpoint, - scopes=client_options.scopes, - client_cert_source_for_mtls=client_cert_source_func, - quota_project_id=client_options.quota_project_id, - client_info=client_info, - always_use_jwt_access=True, - ) - - def create_subscription(self, - request: Union[pubsub.Subscription, dict] = None, - *, - name: str = None, - topic: str = None, - push_config: pubsub.PushConfig = None, - ack_deadline_seconds: int = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - 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/admin#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/admin#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:: - - 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 response - print(response) - - Args: - request (Union[google.pubsub_v1.types.Subscription, dict]): - The request object. A subscription resource. - 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): - If push delivery is used with this subscription, this - field is used to configure it. An empty ``pushConfig`` - signifies that the subscriber will pull and ack messages - using API methods. - - This corresponds to the ``push_config`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - ack_deadline_seconds (int): - 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. - """ - # Create or coerce a 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.') - - # Minor optimization to avoid making a copy if the user passes - # in a pubsub.Subscription. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - 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), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def get_subscription(self, - request: Union[pubsub.GetSubscriptionRequest, dict] = None, - *, - subscription: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pubsub.Subscription: - r"""Gets the configuration details of a subscription. - - - .. code-block:: - - 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 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. - """ - # Create or coerce a 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.') - - # Minor optimization to avoid making a copy if the user passes - # in a pubsub.GetSubscriptionRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - 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), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def update_subscription(self, - request: Union[pubsub.UpdateSubscriptionRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pubsub.Subscription: - r"""Updates an existing subscription. Note that certain - properties of a subscription, such as its topic, are not - modifiable. - - - - .. code-block:: - - 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 response - print(response) - - Args: - request (Union[google.pubsub_v1.types.UpdateSubscriptionRequest, dict]): - 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: - google.pubsub_v1.types.Subscription: - A subscription resource. - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a pubsub.UpdateSubscriptionRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, pubsub.UpdateSubscriptionRequest): - request = pubsub.UpdateSubscriptionRequest(request) - - # 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), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def list_subscriptions(self, - request: Union[pubsub.ListSubscriptionsRequest, dict] = None, - *, - project: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListSubscriptionsPager: - r"""Lists matching subscriptions. - - - .. code-block:: - - 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) - 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.') - - # Minor optimization to avoid making a copy if the user passes - # in a pubsub.ListSubscriptionsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - 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), - )), - ) - - # 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, - metadata=metadata, - ) - - # Done; return the response. - return response - - def delete_subscription(self, - request: Union[pubsub.DeleteSubscriptionRequest, dict] = None, - *, - subscription: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - 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:: - - 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 - response = 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.') - - # Minor optimization to avoid making a copy if the user passes - # in a pubsub.DeleteSubscriptionRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - 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), - )), - ) - - # Send the request. - rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - def modify_ack_deadline(self, - request: Union[pubsub.ModifyAckDeadlineRequest, dict] = None, - *, - subscription: str = None, - ack_ids: Sequence[str] = None, - ack_deadline_seconds: int = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - 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:: - - 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_value_1', 'ack_ids_value_2'], - ack_deadline_seconds=2066, - ) - - # Make the request - response = 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 (Sequence[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 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.') - - # Minor optimization to avoid making a copy if the user passes - # in a pubsub.ModifyAckDeadlineRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - 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), - )), - ) - - # Send the request. - rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - def acknowledge(self, - request: Union[pubsub.AcknowledgeRequest, dict] = None, - *, - subscription: str = None, - ack_ids: Sequence[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - 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:: - - 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_value_1', 'ack_ids_value_2'], - ) - - # Make the request - response = 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 (Sequence[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.') - - # Minor optimization to avoid making a copy if the user passes - # in a pubsub.AcknowledgeRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - 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), - )), - ) - - # Send the request. - rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - def pull(self, - request: Union[pubsub.PullRequest, dict] = None, - *, - subscription: str = None, - return_immediately: bool = None, - max_messages: int = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pubsub.PullResponse: - r"""Pulls messages from the server. The server may return - ``UNAVAILABLE`` if there are too many concurrent pull requests - pending for the given subscription. - - - - .. code-block:: - - 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 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.') - - # Minor optimization to avoid making a copy if the user passes - # in a pubsub.PullRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - 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), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def streaming_pull(self, - requests: Iterator[pubsub.StreamingPullRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - 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:: - - 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()) - 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] - - # Send the request. - response = rpc( - requests, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def modify_push_config(self, - request: Union[pubsub.ModifyPushConfigRequest, dict] = None, - *, - subscription: str = None, - push_config: pubsub.PushConfig = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - 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:: - - 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 - response = 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.') - - # Minor optimization to avoid making a copy if the user passes - # in a pubsub.ModifyPushConfigRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - 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), - )), - ) - - # Send the request. - rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - def get_snapshot(self, - request: Union[pubsub.GetSnapshotRequest, dict] = None, - *, - snapshot: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - 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:: - - 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 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.') - - # Minor optimization to avoid making a copy if the user passes - # in a pubsub.GetSnapshotRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - 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), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def list_snapshots(self, - request: Union[pubsub.ListSnapshotsRequest, dict] = None, - *, - project: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - 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:: - - 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) - 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.') - - # Minor optimization to avoid making a copy if the user passes - # in a pubsub.ListSnapshotsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - 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), - )), - ) - - # 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, - metadata=metadata, - ) - - # Done; return the response. - return response - - def create_snapshot(self, - request: Union[pubsub.CreateSnapshotRequest, dict] = None, - *, - name: str = None, - subscription: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - 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/admin#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:: - - 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 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.') - - # Minor optimization to avoid making a copy if the user passes - # in a pubsub.CreateSnapshotRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - 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), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def update_snapshot(self, - request: Union[pubsub.UpdateSnapshotRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pubsub.Snapshot: - r"""Updates an existing 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:: - - 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 response - print(response) - - Args: - request (Union[google.pubsub_v1.types.UpdateSnapshotRequest, dict]): - 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: - 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. - # Minor optimization to avoid making a copy if the user passes - # in a pubsub.UpdateSnapshotRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, pubsub.UpdateSnapshotRequest): - request = pubsub.UpdateSnapshotRequest(request) - - # 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), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def delete_snapshot(self, - request: Union[pubsub.DeleteSnapshotRequest, dict] = None, - *, - snapshot: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - 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:: - - 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 - response = 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.') - - # Minor optimization to avoid making a copy if the user passes - # in a pubsub.DeleteSnapshotRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - 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), - )), - ) - - # Send the request. - rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - def seek(self, - request: Union[pubsub.SeekRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - 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:: - - 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 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. - # Minor optimization to avoid making a copy if the user passes - # in a pubsub.SeekRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - 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), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def __enter__(self): - 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: iam_policy_pb2.SetIamPolicyRequest = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - 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),)), - ) - - # Send the request. - response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - def get_iam_policy( - self, - request: iam_policy_pb2.GetIamPolicyRequest = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - 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),)), - ) - - # Send the request. - response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - def test_iam_permissions( - self, - request: iam_policy_pb2.TestIamPermissionsRequest = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - 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),)), - ) - - # Send the request. - response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-pubsub", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__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 38abb259f..000000000 --- a/owl-bot-staging/v1/google/pubsub_v1/services/subscriber/pagers.py +++ /dev/null @@ -1,260 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from typing import Any, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator - -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, - *, - 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. - 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._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, 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, - *, - 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. - 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._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, 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, - *, - 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. - 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._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, 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, - *, - 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. - 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._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, 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 c6306fd04..000000000 --- a/owl-bot-staging/v1/google/pubsub_v1/services/subscriber/transports/__init__.py +++ /dev/null @@ -1,33 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -from typing import Dict, Type - -from .base import SubscriberTransport -from .grpc import SubscriberGrpcTransport -from .grpc_asyncio import SubscriberGrpcAsyncIOTransport - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[SubscriberTransport]] -_transport_registry['grpc'] = SubscriberGrpcTransport -_transport_registry['grpc_asyncio'] = SubscriberGrpcAsyncIOTransport - -__all__ = ( - 'SubscriberTransport', - 'SubscriberGrpcTransport', - 'SubscriberGrpcAsyncIOTransport', -) 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 e76959ffb..000000000 --- a/owl-bot-staging/v1/google/pubsub_v1/services/subscriber/transports/base.py +++ /dev/null @@ -1,502 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import abc -from typing import Awaitable, Callable, Dict, Optional, Sequence, Union -import pkg_resources - -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 - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - 'google-pubsub', - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -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: 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, - **kwargs, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A list of scopes. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - """ - # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ':' not in host: - host += ':443' - self._host = host - - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - - # Save the scopes. - self._scopes = scopes - - # If no credentials are provided, then determine the appropriate - # defaults. - if credentials and credentials_file: - raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") - - if credentials_file is not None: - credentials, _ = google.auth.load_credentials_from_file( - credentials_file, - **scopes_kwargs, - quota_project_id=quota_project_id - ) - elif credentials is None: - credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) - - # 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 - - 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.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=1.3, 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() - -__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 8ce70509e..000000000 --- a/owl-bot-staging/v1/google/pubsub_v1/services/subscriber/transports/grpc.py +++ /dev/null @@ -1,830 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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: ga_credentials.Credentials = None, - credentials_file: str = None, - scopes: Sequence[str] = None, - channel: grpc.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - channel (Optional[grpc.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or 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 ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - 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 channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - 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: ga_credentials.Credentials = None, - credentials_file: str = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> grpc.Channel: - """Create and return a gRPC channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - grpc.Channel: A gRPC channel object. - - Raises: - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - - 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/admin#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/admin#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. 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. The server may return - ``UNAVAILABLE`` if there are too many concurrent pull requests - pending for the given subscription. - - 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/admin#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. 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() - -__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 a01e7a542..000000000 --- a/owl-bot-staging/v1/google/pubsub_v1/services/subscriber/transports/grpc_asyncio.py +++ /dev/null @@ -1,835 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.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: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> aio.Channel: - """Create and return a gRPC AsyncIO channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - aio.Channel: A gRPC AsyncIO channel object. - """ - - 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: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: aio.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, - quota_project_id=None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - channel (Optional[aio.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or 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 ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - 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 channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - 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/admin#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/admin#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. 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. The server may return - ``UNAVAILABLE`` if there are too many concurrent pull requests - pending for the given subscription. - - 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/admin#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. 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 close(self): - return self.grpc_channel.close() - - -__all__ = ( - 'SubscriberGrpcAsyncIOTransport', -) 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 e9bd9fd82..000000000 --- a/owl-bot-staging/v1/google/pubsub_v1/types/__init__.py +++ /dev/null @@ -1,134 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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, - CreateSnapshotRequest, - DeadLetterPolicy, - DeleteSnapshotRequest, - DeleteSubscriptionRequest, - DeleteTopicRequest, - DetachSubscriptionRequest, - DetachSubscriptionResponse, - ExpirationPolicy, - GetSnapshotRequest, - GetSubscriptionRequest, - GetTopicRequest, - 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 ( - CreateSchemaRequest, - DeleteSchemaRequest, - GetSchemaRequest, - ListSchemasRequest, - ListSchemasResponse, - Schema, - ValidateMessageRequest, - ValidateMessageResponse, - ValidateSchemaRequest, - ValidateSchemaResponse, - Encoding, - SchemaView, -) - -__all__ = ( - 'AcknowledgeRequest', - 'CreateSnapshotRequest', - 'DeadLetterPolicy', - 'DeleteSnapshotRequest', - 'DeleteSubscriptionRequest', - 'DeleteTopicRequest', - 'DetachSubscriptionRequest', - 'DetachSubscriptionResponse', - 'ExpirationPolicy', - 'GetSnapshotRequest', - 'GetSubscriptionRequest', - 'GetTopicRequest', - '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', - 'CreateSchemaRequest', - 'DeleteSchemaRequest', - 'GetSchemaRequest', - 'ListSchemasRequest', - 'ListSchemasResponse', - '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 f274228c8..000000000 --- a/owl-bot-staging/v1/google/pubsub_v1/types/pubsub.py +++ /dev/null @@ -1,1779 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import proto # type: ignore - -from google.protobuf import duration_pb2 # type: ignore -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from google.pubsub_v1.types import schema as gp_schema - - -__protobuf__ = proto.module( - package='google.pubsub.v1', - manifest={ - 'MessageStoragePolicy', - 'SchemaSettings', - 'Topic', - 'PubsubMessage', - 'GetTopicRequest', - 'UpdateTopicRequest', - 'PublishRequest', - 'PublishResponse', - 'ListTopicsRequest', - 'ListTopicsResponse', - 'ListTopicSubscriptionsRequest', - 'ListTopicSubscriptionsResponse', - 'ListTopicSnapshotsRequest', - 'ListTopicSnapshotsResponse', - 'DeleteTopicRequest', - 'DetachSubscriptionRequest', - 'DetachSubscriptionResponse', - 'Subscription', - 'RetryPolicy', - 'DeadLetterPolicy', - 'ExpirationPolicy', - 'PushConfig', - '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 (Sequence[str]): - A list of IDs of GCP regions where messages - that are published to the topic may be persisted - in storage. Messages published by publishers - running in non-allowed GCP regions (or running - outside of GCP altogether) will be routed for - storage in one of the allowed regions. An empty - list means that no regions are allowed, and is - not a valid configuration. - """ - - allowed_persistence_regions = proto.RepeatedField( - proto.STRING, - number=1, - ) - - -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): - The encoding of messages validated against ``schema``. - """ - - schema = proto.Field( - proto.STRING, - number=1, - ) - encoding = proto.Field( - proto.ENUM, - number=2, - enum=gp_schema.Encoding, - ) - - -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 (Sequence[google.pubsub_v1.types.Topic.LabelsEntry]): - See [Creating and managing labels] - (https://cloud.google.com/pubsub/docs/labels). - message_storage_policy (google.pubsub_v1.types.MessageStoragePolicy): - 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): - 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): - Settings for validating messages published - against a schema. - satisfies_pzs (bool): - 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): - 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 7 - days or less than 10 minutes. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - labels = proto.MapField( - proto.STRING, - proto.STRING, - number=2, - ) - message_storage_policy = proto.Field( - proto.MESSAGE, - number=3, - message='MessageStoragePolicy', - ) - kms_key_name = proto.Field( - proto.STRING, - number=5, - ) - schema_settings = proto.Field( - proto.MESSAGE, - number=6, - message='SchemaSettings', - ) - satisfies_pzs = proto.Field( - proto.BOOL, - number=7, - ) - message_retention_duration = proto.Field( - proto.MESSAGE, - number=8, - message=duration_pb2.Duration, - ) - - -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): - The message data field. If this field is - empty, the message must contain at least one - attribute. - attributes (Sequence[google.pubsub_v1.types.PubsubMessage.AttributesEntry]): - 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): - 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. - """ - - data = proto.Field( - proto.BYTES, - number=1, - ) - attributes = proto.MapField( - proto.STRING, - proto.STRING, - number=2, - ) - message_id = proto.Field( - proto.STRING, - number=3, - ) - publish_time = proto.Field( - proto.MESSAGE, - number=4, - message=timestamp_pb2.Timestamp, - ) - ordering_key = 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 = 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 = proto.Field( - proto.MESSAGE, - number=1, - message='Topic', - ) - update_mask = 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 (Sequence[google.pubsub_v1.types.PubsubMessage]): - Required. The messages to publish. - """ - - topic = proto.Field( - proto.STRING, - number=1, - ) - messages = proto.RepeatedField( - proto.MESSAGE, - number=2, - message='PubsubMessage', - ) - - -class PublishResponse(proto.Message): - r"""Response for the ``Publish`` method. - - Attributes: - message_ids (Sequence[str]): - 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 = 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): - Maximum number of topics to return. - page_token (str): - 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 = proto.Field( - proto.STRING, - number=1, - ) - page_size = proto.Field( - proto.INT32, - number=2, - ) - page_token = proto.Field( - proto.STRING, - number=3, - ) - - -class ListTopicsResponse(proto.Message): - r"""Response for the ``ListTopics`` method. - - Attributes: - topics (Sequence[google.pubsub_v1.types.Topic]): - The resulting topics. - next_page_token (str): - 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 = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='Topic', - ) - next_page_token = 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): - Maximum number of subscription names to - return. - page_token (str): - 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 = proto.Field( - proto.STRING, - number=1, - ) - page_size = proto.Field( - proto.INT32, - number=2, - ) - page_token = proto.Field( - proto.STRING, - number=3, - ) - - -class ListTopicSubscriptionsResponse(proto.Message): - r"""Response for the ``ListTopicSubscriptions`` method. - - Attributes: - subscriptions (Sequence[str]): - The names of subscriptions attached to the - topic specified in the request. - next_page_token (str): - 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 = proto.RepeatedField( - proto.STRING, - number=1, - ) - next_page_token = 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): - Maximum number of snapshot names to return. - page_token (str): - 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 = proto.Field( - proto.STRING, - number=1, - ) - page_size = proto.Field( - proto.INT32, - number=2, - ) - page_token = proto.Field( - proto.STRING, - number=3, - ) - - -class ListTopicSnapshotsResponse(proto.Message): - r"""Response for the ``ListTopicSnapshots`` method. - - Attributes: - snapshots (Sequence[str]): - The names of the snapshots that match the - request. - next_page_token (str): - 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 = proto.RepeatedField( - proto.STRING, - number=1, - ) - next_page_token = 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 = 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 = 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. - - 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): - If push delivery is used with this subscription, this field - is used to configure it. An empty ``pushConfig`` signifies - that the subscriber will pull and ack messages using API - methods. - ack_deadline_seconds (int): - 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): - 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): - 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 7 days or less than - 10 minutes. - labels (Sequence[google.pubsub_v1.types.Subscription.LabelsEntry]): - See - Creating and managing labels. - enable_message_ordering (bool): - 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): - 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. - filter (str): - 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): - 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 Cloud 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): - 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): - 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): - 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. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - topic = proto.Field( - proto.STRING, - number=2, - ) - push_config = proto.Field( - proto.MESSAGE, - number=4, - message='PushConfig', - ) - ack_deadline_seconds = proto.Field( - proto.INT32, - number=5, - ) - retain_acked_messages = proto.Field( - proto.BOOL, - number=7, - ) - message_retention_duration = proto.Field( - proto.MESSAGE, - number=8, - message=duration_pb2.Duration, - ) - labels = proto.MapField( - proto.STRING, - proto.STRING, - number=9, - ) - enable_message_ordering = proto.Field( - proto.BOOL, - number=10, - ) - expiration_policy = proto.Field( - proto.MESSAGE, - number=11, - message='ExpirationPolicy', - ) - filter = proto.Field( - proto.STRING, - number=12, - ) - dead_letter_policy = proto.Field( - proto.MESSAGE, - number=13, - message='DeadLetterPolicy', - ) - retry_policy = proto.Field( - proto.MESSAGE, - number=14, - message='RetryPolicy', - ) - detached = proto.Field( - proto.BOOL, - number=15, - ) - enable_exactly_once_delivery = proto.Field( - proto.BOOL, - number=16, - ) - topic_message_retention_duration = proto.Field( - proto.MESSAGE, - number=17, - message=duration_pb2.Duration, - ) - - -class RetryPolicy(proto.Message): - r"""A policy that specifies how Cloud 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): - 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): - The maximum delay between consecutive - deliveries of a given message. Value should be - between 0 and 600 seconds. Defaults to 600 - seconds. - """ - - minimum_backoff = proto.Field( - proto.MESSAGE, - number=1, - message=duration_pb2.Duration, - ) - maximum_backoff = 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): - The name of the topic to which dead letter messages should - be published. Format is - ``projects/{project}/topics/{topic}``.The Cloud 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): - 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 = proto.Field( - proto.STRING, - number=1, - ) - max_delivery_attempts = 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): - 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 = proto.Field( - proto.MESSAGE, - number=1, - message=duration_pb2.Duration, - ) - - -class PushConfig(proto.Message): - r"""Configuration for a push delivery endpoint. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - push_endpoint (str): - A URL locating the endpoint to which messages should be - pushed. For example, a Webhook endpoint might use - ``https://example.com/push``. - attributes (Sequence[google.pubsub_v1.types.PushConfig.AttributesEntry]): - 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: - - .. raw:: html - -
attributes { "x-goog-version": "v1" } 
- oidc_token (google.pubsub_v1.types.PushConfig.OidcToken): - 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``. - """ - - class OidcToken(proto.Message): - r"""Contains information needed for generating an `OpenID Connect - token `__. - - Attributes: - service_account_email (str): - `Service account - email `__ - to be used for generating the OIDC token. The caller (for - CreateSubscription, UpdateSubscription, and ModifyPushConfig - RPCs) must have the iam.serviceAccounts.actAs permission for - the service account. - audience (str): - 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 = proto.Field( - proto.STRING, - number=1, - ) - audience = proto.Field( - proto.STRING, - number=2, - ) - - push_endpoint = proto.Field( - proto.STRING, - number=1, - ) - attributes = proto.MapField( - proto.STRING, - proto.STRING, - number=2, - ) - oidc_token = proto.Field( - proto.MESSAGE, - number=3, - oneof='authentication_method', - message=OidcToken, - ) - - -class ReceivedMessage(proto.Message): - r"""A message and its corresponding acknowledgment ID. - - Attributes: - ack_id (str): - This ID can be used to acknowledge the - received message. - message (google.pubsub_v1.types.PubsubMessage): - The message. - delivery_attempt (int): - The approximate number of times that Cloud 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 = proto.Field( - proto.STRING, - number=1, - ) - message = proto.Field( - proto.MESSAGE, - number=2, - message='PubsubMessage', - ) - delivery_attempt = 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 = 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 = proto.Field( - proto.MESSAGE, - number=1, - message='Subscription', - ) - update_mask = 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): - Maximum number of subscriptions to return. - page_token (str): - 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 = proto.Field( - proto.STRING, - number=1, - ) - page_size = proto.Field( - proto.INT32, - number=2, - ) - page_token = proto.Field( - proto.STRING, - number=3, - ) - - -class ListSubscriptionsResponse(proto.Message): - r"""Response for the ``ListSubscriptions`` method. - - Attributes: - subscriptions (Sequence[google.pubsub_v1.types.Subscription]): - The subscriptions that match the request. - next_page_token (str): - 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 = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='Subscription', - ) - next_page_token = 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 = 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 = proto.Field( - proto.STRING, - number=1, - ) - push_config = 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 = proto.Field( - proto.STRING, - number=1, - ) - return_immediately = proto.Field( - proto.BOOL, - number=2, - ) - max_messages = proto.Field( - proto.INT32, - number=3, - ) - - -class PullResponse(proto.Message): - r"""Response for the ``Pull`` method. - - Attributes: - received_messages (Sequence[google.pubsub_v1.types.ReceivedMessage]): - Received Pub/Sub messages. The list will be empty if there - are no more messages available in the backlog. 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 = 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 (Sequence[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 is 600 - seconds (10 minutes). - """ - - subscription = proto.Field( - proto.STRING, - number=1, - ) - ack_ids = proto.RepeatedField( - proto.STRING, - number=4, - ) - ack_deadline_seconds = 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 (Sequence[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 = proto.Field( - proto.STRING, - number=1, - ) - ack_ids = 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 (Sequence[str]): - 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 (Sequence[int]): - 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 (Sequence[str]): - 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): - 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): - Flow control settings for the maximum number of outstanding - messages. When there are ``max_outstanding_messages`` or - more 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): - 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 = proto.Field( - proto.STRING, - number=1, - ) - ack_ids = proto.RepeatedField( - proto.STRING, - number=2, - ) - modify_deadline_seconds = proto.RepeatedField( - proto.INT32, - number=3, - ) - modify_deadline_ack_ids = proto.RepeatedField( - proto.STRING, - number=4, - ) - stream_ack_deadline_seconds = proto.Field( - proto.INT32, - number=5, - ) - client_id = proto.Field( - proto.STRING, - number=6, - ) - max_outstanding_messages = proto.Field( - proto.INT64, - number=7, - ) - max_outstanding_bytes = 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 (Sequence[google.pubsub_v1.types.ReceivedMessage]): - Received Pub/Sub messages. This will not be - empty. - acknowlege_confirmation (google.pubsub_v1.types.StreamingPullResponse.AcknowledgeConfirmation): - 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): - This field will only be set if - ``enable_exactly_once_delivery`` is set to ``true``. - subscription_properties (google.pubsub_v1.types.StreamingPullResponse.SubscriptionProperties): - 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 (Sequence[str]): - Successfully processed acknowledgement IDs. - invalid_ack_ids (Sequence[str]): - List of acknowledgement IDs that were - malformed or whose acknowledgement deadline has - expired. - unordered_ack_ids (Sequence[str]): - List of acknowledgement IDs that were out of - order. - """ - - ack_ids = proto.RepeatedField( - proto.STRING, - number=1, - ) - invalid_ack_ids = proto.RepeatedField( - proto.STRING, - number=2, - ) - unordered_ack_ids = proto.RepeatedField( - proto.STRING, - number=3, - ) - - 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 (Sequence[str]): - Successfully processed acknowledgement IDs. - invalid_ack_ids (Sequence[str]): - List of acknowledgement IDs that were - malformed or whose acknowledgement deadline has - expired. - """ - - ack_ids = proto.RepeatedField( - proto.STRING, - number=1, - ) - invalid_ack_ids = proto.RepeatedField( - proto.STRING, - number=2, - ) - - class SubscriptionProperties(proto.Message): - r"""Subscription properties sent as part of the response. - - Attributes: - exactly_once_delivery_enabled (bool): - True iff exactly once delivery is enabled for - this subscription. - message_ordering_enabled (bool): - True iff message ordering is enabled for this - subscription. - """ - - exactly_once_delivery_enabled = proto.Field( - proto.BOOL, - number=1, - ) - message_ordering_enabled = proto.Field( - proto.BOOL, - number=2, - ) - - received_messages = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='ReceivedMessage', - ) - acknowlege_confirmation = proto.Field( - proto.MESSAGE, - number=2, - message=AcknowledgeConfirmation, - ) - modify_ack_deadline_confirmation = proto.Field( - proto.MESSAGE, - number=3, - message=ModifyAckDeadlineConfirmation, - ) - subscription_properties = 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 (Sequence[google.pubsub_v1.types.CreateSnapshotRequest.LabelsEntry]): - See - Creating and managing labels. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - subscription = proto.Field( - proto.STRING, - number=2, - ) - labels = 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 = proto.Field( - proto.MESSAGE, - number=1, - message='Snapshot', - ) - update_mask = 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): - The name of the snapshot. - topic (str): - The name of the topic from which this - snapshot is retaining messages. - expire_time (google.protobuf.timestamp_pb2.Timestamp): - 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 (Sequence[google.pubsub_v1.types.Snapshot.LabelsEntry]): - See [Creating and managing labels] - (https://cloud.google.com/pubsub/docs/labels). - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - topic = proto.Field( - proto.STRING, - number=2, - ) - expire_time = proto.Field( - proto.MESSAGE, - number=3, - message=timestamp_pb2.Timestamp, - ) - labels = 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 = 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): - Maximum number of snapshots to return. - page_token (str): - 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 = proto.Field( - proto.STRING, - number=1, - ) - page_size = proto.Field( - proto.INT32, - number=2, - ) - page_token = proto.Field( - proto.STRING, - number=3, - ) - - -class ListSnapshotsResponse(proto.Message): - r"""Response for the ``ListSnapshots`` method. - - Attributes: - snapshots (Sequence[google.pubsub_v1.types.Snapshot]): - The resulting snapshots. - next_page_token (str): - 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 = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='Snapshot', - ) - next_page_token = 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 = 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): - 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): - 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 = proto.Field( - proto.STRING, - number=1, - ) - time = proto.Field( - proto.MESSAGE, - number=2, - oneof='target', - message=timestamp_pb2.Timestamp, - ) - snapshot = 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 7d13dfba5..000000000 --- a/owl-bot-staging/v1/google/pubsub_v1/types/schema.py +++ /dev/null @@ -1,319 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import proto # type: ignore - - -__protobuf__ = proto.module( - package='google.pubsub.v1', - manifest={ - 'SchemaView', - 'Encoding', - 'Schema', - 'CreateSchemaRequest', - 'GetSchemaRequest', - 'ListSchemasRequest', - 'ListSchemasResponse', - 'DeleteSchemaRequest', - 'ValidateSchemaRequest', - 'ValidateSchemaResponse', - 'ValidateMessageRequest', - 'ValidateMessageResponse', - }, -) - - -class SchemaView(proto.Enum): - r"""View of Schema object fields to be returned by GetSchema and - ListSchemas. - """ - SCHEMA_VIEW_UNSPECIFIED = 0 - BASIC = 1 - FULL = 2 - - -class Encoding(proto.Enum): - r"""Possible encoding types for messages.""" - 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``. - """ - class Type(proto.Enum): - r"""Possible schema definition types.""" - TYPE_UNSPECIFIED = 0 - PROTOCOL_BUFFER = 1 - AVRO = 2 - - name = proto.Field( - proto.STRING, - number=1, - ) - type_ = proto.Field( - proto.ENUM, - number=2, - enum=Type, - ) - definition = proto.Field( - proto.STRING, - number=3, - ) - - -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/admin#resource_names - for resource name constraints. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - schema = proto.Field( - proto.MESSAGE, - number=2, - message='Schema', - ) - schema_id = 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 ``name`` and ``type``, but not - ``definition``. Set to ``FULL`` to retrieve all fields. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - view = 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 = proto.Field( - proto.STRING, - number=1, - ) - view = proto.Field( - proto.ENUM, - number=2, - enum='SchemaView', - ) - page_size = proto.Field( - proto.INT32, - number=3, - ) - page_token = proto.Field( - proto.STRING, - number=4, - ) - - -class ListSchemasResponse(proto.Message): - r"""Response for the ``ListSchemas`` method. - - Attributes: - schemas (Sequence[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 = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='Schema', - ) - next_page_token = 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 = 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 = proto.Field( - proto.STRING, - number=1, - ) - 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 = proto.Field( - proto.STRING, - number=1, - ) - name = proto.Field( - proto.STRING, - number=2, - oneof='schema_spec', - ) - schema = proto.Field( - proto.MESSAGE, - number=3, - oneof='schema_spec', - message='Schema', - ) - message = proto.Field( - proto.BYTES, - number=4, - ) - 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 4505b4854..000000000 --- a/owl-bot-staging/v1/mypy.ini +++ /dev/null @@ -1,3 +0,0 @@ -[mypy] -python_version = 3.6 -namespace_packages = True diff --git a/owl-bot-staging/v1/noxfile.py b/owl-bot-staging/v1/noxfile.py deleted file mode 100644 index c7644f48f..000000000 --- a/owl-bot-staging/v1/noxfile.py +++ /dev/null @@ -1,132 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import os -import pathlib -import shutil -import subprocess -import sys - - -import nox # type: ignore - -CURRENT_DIRECTORY = pathlib.Path(__file__).parent.absolute() - -LOWER_BOUND_CONSTRAINTS_FILE = CURRENT_DIRECTORY / "constraints.txt" -PACKAGE_NAME = subprocess.check_output([sys.executable, "setup.py", "--name"], encoding="utf-8") - - -nox.sessions = [ - "unit", - "cover", - "mypy", - "check_lower_bounds" - # exclude update_lower_bounds from default - "docs", -] - -@nox.session(python=['3.6', '3.7', '3.8', '3.9', '3.10']) -def unit(session): - """Run the unit test suite.""" - - session.install('coverage', 'pytest', 'pytest-cov', 'asyncmock', 'pytest-asyncio') - session.install('-e', '.') - - session.run( - 'py.test', - '--quiet', - '--cov=google/pubsub_v1/', - '--cov-config=.coveragerc', - '--cov-report=term', - '--cov-report=html', - os.path.join('tests', 'unit', ''.join(session.posargs)) - ) - - -@nox.session(python='3.9') -def cover(session): - """Run the final coverage report. - This outputs the coverage report aggregating coverage from the unit - test runs (not system test runs), and then erases coverage data. - """ - session.install("coverage", "pytest-cov") - session.run("coverage", "report", "--show-missing", "--fail-under=100") - - session.run("coverage", "erase") - - -@nox.session(python=['3.6', '3.7', '3.8', '3.9']) -def mypy(session): - """Run the type checker.""" - session.install('mypy', 'types-pkg_resources') - session.install('.') - session.run( - 'mypy', - '--explicit-package-bases', - 'google', - ) - - -@nox.session -def update_lower_bounds(session): - """Update lower bounds in constraints.txt to match setup.py""" - session.install('google-cloud-testutils') - session.install('.') - - session.run( - 'lower-bound-checker', - 'update', - '--package-name', - PACKAGE_NAME, - '--constraints-file', - str(LOWER_BOUND_CONSTRAINTS_FILE), - ) - - -@nox.session -def check_lower_bounds(session): - """Check lower bounds in setup.py are reflected in constraints file""" - session.install('google-cloud-testutils') - session.install('.') - - session.run( - 'lower-bound-checker', - 'check', - '--package-name', - PACKAGE_NAME, - '--constraints-file', - str(LOWER_BOUND_CONSTRAINTS_FILE), - ) - -@nox.session(python='3.9') -def docs(session): - """Build the docs for this library.""" - - session.install("-e", ".") - session.install("sphinx==4.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", ""), - ) 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 039fa1e8f..000000000 --- a/owl-bot-staging/v1/scripts/fixup_pubsub_v1_keywords.py +++ /dev/null @@ -1,209 +0,0 @@ -#! /usr/bin/env python3 -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import argparse -import os -import libcst as cst -import pathlib -import sys -from typing import (Any, Callable, Dict, List, Sequence, Tuple) - - -def partition( - predicate: Callable[[Any], bool], - iterator: Sequence[Any] -) -> Tuple[List[Any], List[Any]]: - """A stable, out-of-place partition.""" - results = ([], []) - - for i in iterator: - results[int(predicate(i))].append(i) - - # Returns trueList, falseList - return results[1], results[0] - - -class pubsubCallTransformer(cst.CSTTransformer): - CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') - METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { - 'acknowledge': ('subscription', 'ack_ids', ), - 'create_schema': ('parent', 'schema', 'schema_id', ), - 'create_snapshot': ('name', 'subscription', 'labels', ), - 'create_subscription': ('name', 'topic', 'push_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', ), - 'create_topic': ('name', 'labels', 'message_storage_policy', 'kms_key_name', 'schema_settings', 'satisfies_pzs', 'message_retention_duration', ), - 'delete_schema': ('name', ), - '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_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', ), - '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 8c17ed743..000000000 --- a/owl-bot-staging/v1/setup.py +++ /dev/null @@ -1,55 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import io -import os -import setuptools # type: ignore - -version = '0.1.0' - -package_root = os.path.abspath(os.path.dirname(__file__)) - -readme_filename = os.path.join(package_root, 'README.rst') -with io.open(readme_filename, encoding='utf-8') as readme_file: - readme = readme_file.read() - -setuptools.setup( - name='google-pubsub', - version=version, - long_description=readme, - packages=setuptools.PEP420PackageFinder.find(), - namespace_packages=('google',), - platforms='Posix; MacOS X; Windows', - include_package_data=True, - install_requires=( - 'google-api-core[grpc] >= 1.28.0, < 3.0.0dev', - 'libcst >= 0.2.5', - 'proto-plus >= 1.19.7', - 'grpc-google-iam-v1 >= 0.12.3, < 0.13dev', - ), - python_requires='>=3.6', - classifiers=[ - 'Development Status :: 3 - Alpha', - 'Intended Audience :: Developers', - 'Operating System :: OS Independent', - 'Programming Language :: Python :: 3.6', - 'Programming Language :: Python :: 3.7', - 'Programming Language :: Python :: 3.8', - 'Programming Language :: Python :: 3.9', - 'Topic :: Internet', - 'Topic :: Software Development :: Libraries :: Python Modules', - ], - zip_safe=False, -) diff --git a/owl-bot-staging/v1/tests/__init__.py b/owl-bot-staging/v1/tests/__init__.py deleted file mode 100644 index b54a5fcc4..000000000 --- a/owl-bot-staging/v1/tests/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# diff --git a/owl-bot-staging/v1/tests/unit/__init__.py b/owl-bot-staging/v1/tests/unit/__init__.py deleted file mode 100644 index b54a5fcc4..000000000 --- a/owl-bot-staging/v1/tests/unit/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# diff --git a/owl-bot-staging/v1/tests/unit/gapic/__init__.py b/owl-bot-staging/v1/tests/unit/gapic/__init__.py deleted file mode 100644 index b54a5fcc4..000000000 --- a/owl-bot-staging/v1/tests/unit/gapic/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# diff --git a/owl-bot-staging/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 b54a5fcc4..000000000 --- a/owl-bot-staging/v1/tests/unit/gapic/pubsub_v1/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# diff --git a/owl-bot-staging/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 06c8c90fa..000000000 --- a/owl-bot-staging/v1/tests/unit/gapic/pubsub_v1/test_publisher.py +++ /dev/null @@ -1,4154 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import os -import mock - -import grpc -from grpc.experimental import aio -import math -import pytest -from proto.marshal.rules.dates import DurationRule, TimestampRule - - -from google.api_core import client_options -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers -from google.api_core import grpc_helpers_async -from google.api_core import path_template -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 - - -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 - - -@pytest.mark.parametrize("client_class", [ - PublisherClient, - PublisherAsyncClient, -]) -def test_publisher_client_from_service_account_info(client_class): - creds = ga_credentials.AnonymousCredentials() - with mock.patch.object(service_account.Credentials, 'from_service_account_info') as factory: - factory.return_value = creds - info = {"valid": True} - client = client_class.from_service_account_info(info) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == 'pubsub.googleapis.com:443' - - -@pytest.mark.parametrize("transport_class,transport_name", [ - (transports.PublisherGrpcTransport, "grpc"), - (transports.PublisherGrpcAsyncIOTransport, "grpc_asyncio"), -]) -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", [ - PublisherClient, - PublisherAsyncClient, -]) -def test_publisher_client_from_service_account_file(client_class): - creds = ga_credentials.AnonymousCredentials() - with mock.patch.object(service_account.Credentials, 'from_service_account_file') as factory: - factory.return_value = creds - client = client_class.from_service_account_file("dummy/file/path.json") - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - client = client_class.from_service_account_json("dummy/file/path.json") - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == 'pubsub.googleapis.com:443' - - -def test_publisher_client_get_transport_class(): - transport = PublisherClient.get_transport_class() - available_transports = [ - transports.PublisherGrpcTransport, - ] - 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"), -]) -@mock.patch.object(PublisherClient, "DEFAULT_ENDPOINT", modify_default_endpoint(PublisherClient)) -@mock.patch.object(PublisherAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(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, - ) - - # 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, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - # 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, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has - # unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError): - client = client_class(transport=transport_name) - - # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError): - client = client_class(transport=transport_name) - - # 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, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id="octopus", - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - -@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"), -]) -@mock.patch.object(PublisherClient, "DEFAULT_ENDPOINT", modify_default_endpoint(PublisherClient)) -@mock.patch.object(PublisherAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(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 - 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, - ) - - # Check the case ADC client cert is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): - if use_client_cert_env == "false": - expected_host = client.DEFAULT_ENDPOINT - expected_client_cert_source = None - else: - expected_host = client.DEFAULT_MTLS_ENDPOINT - expected_client_cert_source = client_cert_source_callback - - patched.return_value = None - client = client_class(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, - ) - - # 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, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - -@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 - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (PublisherClient, transports.PublisherGrpcTransport, "grpc"), - (PublisherAsyncClient, transports.PublisherGrpcAsyncIOTransport, "grpc_asyncio"), -]) -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, - 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, - ) - -@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_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, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - -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, - ) - - -@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, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - # 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, - ) - 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] - assert args[0] == pubsub.Topic() - - # 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 - - -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: - 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(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, - )) - 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] - assert args[0] == pubsub.Topic() - - # 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 - - -@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, - ) - 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] - assert args[0] == pubsub.UpdateTopicRequest() - - # 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 - - -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: - 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(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, - )) - 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] - assert args[0] == pubsub.UpdateTopicRequest() - - # 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 - - -@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 = 'topic.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=topic.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 = 'topic.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=topic.name/value', - ) in kw['metadata'] - - -@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] - assert args[0] == pubsub.PublishRequest() - - # 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: - client.publish() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == pubsub.PublishRequest() - - -@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] - assert args[0] == pubsub.PublishRequest() - - # 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, - ) - 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] - assert args[0] == pubsub.GetTopicRequest() - - # 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 - - -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: - 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(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, - )) - 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] - assert args[0] == pubsub.GetTopicRequest() - - # 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 - - -@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] - assert args[0] == pubsub.ListTopicsRequest() - - # 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: - 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(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] - assert args[0] == pubsub.ListTopicsRequest() - - # 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, - ) - - metadata = () - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('project', ''), - )), - ) - pager = client.list_topics(request={}) - - assert pager._metadata == metadata - - results = [i for i in 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: - 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 = [] - async for page_ in (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] - assert args[0] == pubsub.ListTopicSubscriptionsRequest() - - # 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: - 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(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] - assert args[0] == pubsub.ListTopicSubscriptionsRequest() - - # 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, - ) - - metadata = () - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('topic', ''), - )), - ) - pager = client.list_topic_subscriptions(request={}) - - assert pager._metadata == metadata - - results = [i for i in 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: - 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 = [] - async for page_ in (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] - assert args[0] == pubsub.ListTopicSnapshotsRequest() - - # 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: - 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(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] - assert args[0] == pubsub.ListTopicSnapshotsRequest() - - # 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, - ) - - metadata = () - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('topic', ''), - )), - ) - pager = client.list_topic_snapshots(request={}) - - assert pager._metadata == metadata - - results = [i for i in 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: - 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 = [] - async for page_ in (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] - assert args[0] == pubsub.DeleteTopicRequest() - - # 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: - 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(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] - assert args[0] == pubsub.DeleteTopicRequest() - - # 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] - assert args[0] == pubsub.DetachSubscriptionRequest() - - # 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: - 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(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] - assert args[0] == pubsub.DetachSubscriptionRequest() - - # 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'] - - -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 = mock.Mock() - 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, -]) -def test_transport_adc(transport_class): - # Test default credentials are used if not provided. - with mock.patch.object(google.auth, 'default') as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class() - adc.assert_called_once() - -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. - client = 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() - - -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,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_host_no_port(): - client = PublisherClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='pubsub.googleapis.com'), - ) - assert client.transport._host == 'pubsub.googleapis.com:443' - - -def test_publisher_host_with_port(): - client = PublisherClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='pubsub.googleapis.com:8000'), - ) - assert client.transport._host == 'pubsub.googleapis.com:8000' - -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) - - -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. - 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) - _, 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) - _, args, _ = call.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() - - -@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_transport_close(): - transports = { - "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 = [ - '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, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) 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 32f6d258d..000000000 --- a/owl-bot-staging/v1/tests/unit/gapic/pubsub_v1/test_schema_service.py +++ /dev/null @@ -1,3113 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import os -import mock - -import grpc -from grpc.experimental import aio -import math -import pytest -from proto.marshal.rules.dates import DurationRule, TimestampRule - - -from google.api_core import client_options -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers -from google.api_core import grpc_helpers_async -from google.api_core import path_template -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.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 - - -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 - - -@pytest.mark.parametrize("client_class", [ - SchemaServiceClient, - SchemaServiceAsyncClient, -]) -def test_schema_service_client_from_service_account_info(client_class): - creds = ga_credentials.AnonymousCredentials() - with mock.patch.object(service_account.Credentials, 'from_service_account_info') as factory: - factory.return_value = creds - info = {"valid": True} - client = client_class.from_service_account_info(info) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == 'pubsub.googleapis.com:443' - - -@pytest.mark.parametrize("transport_class,transport_name", [ - (transports.SchemaServiceGrpcTransport, "grpc"), - (transports.SchemaServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -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", [ - SchemaServiceClient, - SchemaServiceAsyncClient, -]) -def test_schema_service_client_from_service_account_file(client_class): - creds = ga_credentials.AnonymousCredentials() - with mock.patch.object(service_account.Credentials, 'from_service_account_file') as factory: - factory.return_value = creds - client = client_class.from_service_account_file("dummy/file/path.json") - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - client = client_class.from_service_account_json("dummy/file/path.json") - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == 'pubsub.googleapis.com:443' - - -def test_schema_service_client_get_transport_class(): - transport = SchemaServiceClient.get_transport_class() - available_transports = [ - transports.SchemaServiceGrpcTransport, - ] - 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"), -]) -@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_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, - ) - - # 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, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - # 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, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has - # unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError): - client = client_class(transport=transport_name) - - # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError): - client = client_class(transport=transport_name) - - # 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, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id="octopus", - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - -@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"), -]) -@mock.patch.object(SchemaServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SchemaServiceClient)) -@mock.patch.object(SchemaServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(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 - 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, - ) - - # Check the case ADC client cert is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): - if use_client_cert_env == "false": - expected_host = client.DEFAULT_ENDPOINT - expected_client_cert_source = None - else: - expected_host = client.DEFAULT_MTLS_ENDPOINT - expected_client_cert_source = client_cert_source_callback - - patched.return_value = None - client = client_class(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, - ) - - # 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, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - -@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 - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (SchemaServiceClient, transports.SchemaServiceGrpcTransport, "grpc"), - (SchemaServiceAsyncClient, transports.SchemaServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -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, - 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, - ) - -@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_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, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - -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, - ) - - -@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, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - # 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', - ) - 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] - assert args[0] == gp_schema.CreateSchemaRequest() - - # 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' - - -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: - 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(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', - )) - 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] - assert args[0] == gp_schema.CreateSchemaRequest() - - # 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' - - -@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', - ) - 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] - assert args[0] == schema.GetSchemaRequest() - - # 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' - - -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: - 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(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', - )) - 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] - assert args[0] == schema.GetSchemaRequest() - - # 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' - - -@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] - assert args[0] == schema.ListSchemasRequest() - - # 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: - 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(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] - assert args[0] == schema.ListSchemasRequest() - - # 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, - ) - - metadata = () - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_schemas(request={}) - - assert pager._metadata == metadata - - results = [i for i in 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: - 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 = [] - async for page_ in (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.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] - assert args[0] == schema.DeleteSchemaRequest() - - # 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: - 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(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] - assert args[0] == schema.DeleteSchemaRequest() - - # 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] - assert args[0] == gp_schema.ValidateSchemaRequest() - - # 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: - 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(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] - assert args[0] == gp_schema.ValidateSchemaRequest() - - # 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] - assert args[0] == schema.ValidateMessageRequest() - - # 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: - 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(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] - assert args[0] == schema.ValidateMessageRequest() - - # 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'] - - -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 = mock.Mock() - 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, -]) -def test_transport_adc(transport_class): - # Test default credentials are used if not provided. - with mock.patch.object(google.auth, 'default') as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class() - adc.assert_called_once() - -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. - client = 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', - '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() - - -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,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_host_no_port(): - client = SchemaServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='pubsub.googleapis.com'), - ) - assert client.transport._host == 'pubsub.googleapis.com:443' - - -def test_schema_service_host_with_port(): - client = SchemaServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='pubsub.googleapis.com:8000'), - ) - assert client.transport._host == 'pubsub.googleapis.com:8000' - -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) - - -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. - 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) - _, 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) - _, args, _ = call.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() - - -@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_transport_close(): - transports = { - "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 = [ - '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, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) 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 d6bd2b9b1..000000000 --- a/owl-bot-staging/v1/tests/unit/gapic/pubsub_v1/test_subscriber.py +++ /dev/null @@ -1,5493 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import os -import mock - -import grpc -from grpc.experimental import aio -import math -import pytest -from proto.marshal.rules.dates import DurationRule, TimestampRule - - -from google.api_core import client_options -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers -from google.api_core import grpc_helpers_async -from google.api_core import path_template -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 - - -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 - - -@pytest.mark.parametrize("client_class", [ - SubscriberClient, - SubscriberAsyncClient, -]) -def test_subscriber_client_from_service_account_info(client_class): - creds = ga_credentials.AnonymousCredentials() - with mock.patch.object(service_account.Credentials, 'from_service_account_info') as factory: - factory.return_value = creds - info = {"valid": True} - client = client_class.from_service_account_info(info) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == 'pubsub.googleapis.com:443' - - -@pytest.mark.parametrize("transport_class,transport_name", [ - (transports.SubscriberGrpcTransport, "grpc"), - (transports.SubscriberGrpcAsyncIOTransport, "grpc_asyncio"), -]) -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", [ - SubscriberClient, - SubscriberAsyncClient, -]) -def test_subscriber_client_from_service_account_file(client_class): - creds = ga_credentials.AnonymousCredentials() - with mock.patch.object(service_account.Credentials, 'from_service_account_file') as factory: - factory.return_value = creds - client = client_class.from_service_account_file("dummy/file/path.json") - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - client = client_class.from_service_account_json("dummy/file/path.json") - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == 'pubsub.googleapis.com:443' - - -def test_subscriber_client_get_transport_class(): - transport = SubscriberClient.get_transport_class() - available_transports = [ - transports.SubscriberGrpcTransport, - ] - 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"), -]) -@mock.patch.object(SubscriberClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SubscriberClient)) -@mock.patch.object(SubscriberAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(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, - ) - - # 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, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - # 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, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has - # unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError): - client = client_class(transport=transport_name) - - # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError): - client = client_class(transport=transport_name) - - # 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, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id="octopus", - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - -@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"), -]) -@mock.patch.object(SubscriberClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SubscriberClient)) -@mock.patch.object(SubscriberAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(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 - 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, - ) - - # Check the case ADC client cert is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): - if use_client_cert_env == "false": - expected_host = client.DEFAULT_ENDPOINT - expected_client_cert_source = None - else: - expected_host = client.DEFAULT_MTLS_ENDPOINT - expected_client_cert_source = client_cert_source_callback - - patched.return_value = None - client = client_class(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, - ) - - # 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, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - -@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 - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (SubscriberClient, transports.SubscriberGrpcTransport, "grpc"), - (SubscriberAsyncClient, transports.SubscriberGrpcAsyncIOTransport, "grpc_asyncio"), -]) -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, - 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, - ) - -@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_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, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - -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, - ) - - -@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, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - # 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, - ) - 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] - assert args[0] == pubsub.Subscription() - - # 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 - - -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: - 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(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, - )) - 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] - assert args[0] == pubsub.Subscription() - - # 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 - - -@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, - ) - 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] - assert args[0] == pubsub.GetSubscriptionRequest() - - # 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 - - -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: - 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(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, - )) - 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] - assert args[0] == pubsub.GetSubscriptionRequest() - - # 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 - - -@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, - ) - 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] - assert args[0] == pubsub.UpdateSubscriptionRequest() - - # 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 - - -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: - 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(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, - )) - 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] - assert args[0] == pubsub.UpdateSubscriptionRequest() - - # 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 - - -@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 = 'subscription.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=subscription.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 = 'subscription.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=subscription.name/value', - ) in kw['metadata'] - - -@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] - assert args[0] == pubsub.ListSubscriptionsRequest() - - # 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: - 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(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] - assert args[0] == pubsub.ListSubscriptionsRequest() - - # 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, - ) - - metadata = () - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('project', ''), - )), - ) - pager = client.list_subscriptions(request={}) - - assert pager._metadata == metadata - - results = [i for i in 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: - 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 = [] - async for page_ in (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] - assert args[0] == pubsub.DeleteSubscriptionRequest() - - # 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: - 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(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] - assert args[0] == pubsub.DeleteSubscriptionRequest() - - # 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] - assert args[0] == pubsub.ModifyAckDeadlineRequest() - - # 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: - 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(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] - assert args[0] == pubsub.ModifyAckDeadlineRequest() - - # 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] - assert args[0] == pubsub.AcknowledgeRequest() - - # 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: - client.acknowledge() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == pubsub.AcknowledgeRequest() - - -@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] - assert args[0] == pubsub.AcknowledgeRequest() - - # 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] - assert args[0] == pubsub.PullRequest() - - # 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: - client.pull() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == pubsub.PullRequest() - - -@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] - assert args[0] == pubsub.PullRequest() - - # 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) - - -@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] - assert args[0] == pubsub.ModifyPushConfigRequest() - - # 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: - 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(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] - assert args[0] == pubsub.ModifyPushConfigRequest() - - # 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] - assert args[0] == pubsub.GetSnapshotRequest() - - # 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: - 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(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] - assert args[0] == pubsub.GetSnapshotRequest() - - # 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] - assert args[0] == pubsub.ListSnapshotsRequest() - - # 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: - 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(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] - assert args[0] == pubsub.ListSnapshotsRequest() - - # 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, - ) - - metadata = () - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('project', ''), - )), - ) - pager = client.list_snapshots(request={}) - - assert pager._metadata == metadata - - results = [i for i in 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: - 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 = [] - async for page_ in (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] - assert args[0] == pubsub.CreateSnapshotRequest() - - # 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: - 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(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] - assert args[0] == pubsub.CreateSnapshotRequest() - - # 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] - assert args[0] == pubsub.UpdateSnapshotRequest() - - # 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: - 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(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] - assert args[0] == pubsub.UpdateSnapshotRequest() - - # 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 = 'snapshot.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=snapshot.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 = 'snapshot.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=snapshot.name/value', - ) in kw['metadata'] - - -@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] - assert args[0] == pubsub.DeleteSnapshotRequest() - - # 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: - 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(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] - assert args[0] == pubsub.DeleteSnapshotRequest() - - # 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] - assert args[0] == pubsub.SeekRequest() - - # 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: - client.seek() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == pubsub.SeekRequest() - - -@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] - assert args[0] == pubsub.SeekRequest() - - # 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'] - - -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 = mock.Mock() - 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, -]) -def test_transport_adc(transport_class): - # Test default credentials are used if not provided. - with mock.patch.object(google.auth, 'default') as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class() - adc.assert_called_once() - -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. - client = 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() - - -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,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_host_no_port(): - client = SubscriberClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='pubsub.googleapis.com'), - ) - assert client.transport._host == 'pubsub.googleapis.com:443' - - -def test_subscriber_host_with_port(): - client = SubscriberClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='pubsub.googleapis.com:8000'), - ) - assert client.transport._host == 'pubsub.googleapis.com:8000' - -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) - - -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. - 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) - _, 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) - _, args, _ = call.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() - - -@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_transport_close(): - transports = { - "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 = [ - '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, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) diff --git a/owl-bot-staging/v1/samples/generated_samples/pubsub_generated_pubsub_v1_publisher_create_topic_async.py b/samples/generated_samples/pubsub_generated_pubsub_v1_publisher_create_topic_async.py similarity index 100% rename from owl-bot-staging/v1/samples/generated_samples/pubsub_generated_pubsub_v1_publisher_create_topic_async.py rename to samples/generated_samples/pubsub_generated_pubsub_v1_publisher_create_topic_async.py diff --git a/owl-bot-staging/v1/samples/generated_samples/pubsub_generated_pubsub_v1_publisher_create_topic_sync.py b/samples/generated_samples/pubsub_generated_pubsub_v1_publisher_create_topic_sync.py similarity index 100% rename from owl-bot-staging/v1/samples/generated_samples/pubsub_generated_pubsub_v1_publisher_create_topic_sync.py rename to samples/generated_samples/pubsub_generated_pubsub_v1_publisher_create_topic_sync.py diff --git a/owl-bot-staging/v1/samples/generated_samples/pubsub_generated_pubsub_v1_publisher_delete_topic_async.py b/samples/generated_samples/pubsub_generated_pubsub_v1_publisher_delete_topic_async.py similarity index 100% rename from owl-bot-staging/v1/samples/generated_samples/pubsub_generated_pubsub_v1_publisher_delete_topic_async.py rename to samples/generated_samples/pubsub_generated_pubsub_v1_publisher_delete_topic_async.py diff --git a/owl-bot-staging/v1/samples/generated_samples/pubsub_generated_pubsub_v1_publisher_delete_topic_sync.py b/samples/generated_samples/pubsub_generated_pubsub_v1_publisher_delete_topic_sync.py similarity index 100% rename from owl-bot-staging/v1/samples/generated_samples/pubsub_generated_pubsub_v1_publisher_delete_topic_sync.py rename to samples/generated_samples/pubsub_generated_pubsub_v1_publisher_delete_topic_sync.py diff --git a/owl-bot-staging/v1/samples/generated_samples/pubsub_generated_pubsub_v1_publisher_detach_subscription_async.py b/samples/generated_samples/pubsub_generated_pubsub_v1_publisher_detach_subscription_async.py similarity index 100% rename from owl-bot-staging/v1/samples/generated_samples/pubsub_generated_pubsub_v1_publisher_detach_subscription_async.py rename to samples/generated_samples/pubsub_generated_pubsub_v1_publisher_detach_subscription_async.py diff --git a/owl-bot-staging/v1/samples/generated_samples/pubsub_generated_pubsub_v1_publisher_detach_subscription_sync.py b/samples/generated_samples/pubsub_generated_pubsub_v1_publisher_detach_subscription_sync.py similarity index 100% rename from owl-bot-staging/v1/samples/generated_samples/pubsub_generated_pubsub_v1_publisher_detach_subscription_sync.py rename to samples/generated_samples/pubsub_generated_pubsub_v1_publisher_detach_subscription_sync.py diff --git a/owl-bot-staging/v1/samples/generated_samples/pubsub_generated_pubsub_v1_publisher_get_topic_async.py b/samples/generated_samples/pubsub_generated_pubsub_v1_publisher_get_topic_async.py similarity index 100% rename from owl-bot-staging/v1/samples/generated_samples/pubsub_generated_pubsub_v1_publisher_get_topic_async.py rename to samples/generated_samples/pubsub_generated_pubsub_v1_publisher_get_topic_async.py diff --git a/owl-bot-staging/v1/samples/generated_samples/pubsub_generated_pubsub_v1_publisher_get_topic_sync.py b/samples/generated_samples/pubsub_generated_pubsub_v1_publisher_get_topic_sync.py similarity index 100% rename from owl-bot-staging/v1/samples/generated_samples/pubsub_generated_pubsub_v1_publisher_get_topic_sync.py rename to samples/generated_samples/pubsub_generated_pubsub_v1_publisher_get_topic_sync.py diff --git a/owl-bot-staging/v1/samples/generated_samples/pubsub_generated_pubsub_v1_publisher_list_topic_snapshots_async.py b/samples/generated_samples/pubsub_generated_pubsub_v1_publisher_list_topic_snapshots_async.py similarity index 100% rename from owl-bot-staging/v1/samples/generated_samples/pubsub_generated_pubsub_v1_publisher_list_topic_snapshots_async.py rename to samples/generated_samples/pubsub_generated_pubsub_v1_publisher_list_topic_snapshots_async.py diff --git a/owl-bot-staging/v1/samples/generated_samples/pubsub_generated_pubsub_v1_publisher_list_topic_snapshots_sync.py b/samples/generated_samples/pubsub_generated_pubsub_v1_publisher_list_topic_snapshots_sync.py similarity index 100% rename from owl-bot-staging/v1/samples/generated_samples/pubsub_generated_pubsub_v1_publisher_list_topic_snapshots_sync.py rename to samples/generated_samples/pubsub_generated_pubsub_v1_publisher_list_topic_snapshots_sync.py diff --git a/owl-bot-staging/v1/samples/generated_samples/pubsub_generated_pubsub_v1_publisher_list_topic_subscriptions_async.py b/samples/generated_samples/pubsub_generated_pubsub_v1_publisher_list_topic_subscriptions_async.py similarity index 100% rename from owl-bot-staging/v1/samples/generated_samples/pubsub_generated_pubsub_v1_publisher_list_topic_subscriptions_async.py rename to samples/generated_samples/pubsub_generated_pubsub_v1_publisher_list_topic_subscriptions_async.py diff --git a/owl-bot-staging/v1/samples/generated_samples/pubsub_generated_pubsub_v1_publisher_list_topic_subscriptions_sync.py b/samples/generated_samples/pubsub_generated_pubsub_v1_publisher_list_topic_subscriptions_sync.py similarity index 100% rename from owl-bot-staging/v1/samples/generated_samples/pubsub_generated_pubsub_v1_publisher_list_topic_subscriptions_sync.py rename to samples/generated_samples/pubsub_generated_pubsub_v1_publisher_list_topic_subscriptions_sync.py diff --git a/owl-bot-staging/v1/samples/generated_samples/pubsub_generated_pubsub_v1_publisher_list_topics_async.py b/samples/generated_samples/pubsub_generated_pubsub_v1_publisher_list_topics_async.py similarity index 100% rename from owl-bot-staging/v1/samples/generated_samples/pubsub_generated_pubsub_v1_publisher_list_topics_async.py rename to samples/generated_samples/pubsub_generated_pubsub_v1_publisher_list_topics_async.py diff --git a/owl-bot-staging/v1/samples/generated_samples/pubsub_generated_pubsub_v1_publisher_list_topics_sync.py b/samples/generated_samples/pubsub_generated_pubsub_v1_publisher_list_topics_sync.py similarity index 100% rename from owl-bot-staging/v1/samples/generated_samples/pubsub_generated_pubsub_v1_publisher_list_topics_sync.py rename to samples/generated_samples/pubsub_generated_pubsub_v1_publisher_list_topics_sync.py diff --git a/owl-bot-staging/v1/samples/generated_samples/pubsub_generated_pubsub_v1_publisher_publish_async.py b/samples/generated_samples/pubsub_generated_pubsub_v1_publisher_publish_async.py similarity index 100% rename from owl-bot-staging/v1/samples/generated_samples/pubsub_generated_pubsub_v1_publisher_publish_async.py rename to samples/generated_samples/pubsub_generated_pubsub_v1_publisher_publish_async.py diff --git a/owl-bot-staging/v1/samples/generated_samples/pubsub_generated_pubsub_v1_publisher_publish_sync.py b/samples/generated_samples/pubsub_generated_pubsub_v1_publisher_publish_sync.py similarity index 100% rename from owl-bot-staging/v1/samples/generated_samples/pubsub_generated_pubsub_v1_publisher_publish_sync.py rename to samples/generated_samples/pubsub_generated_pubsub_v1_publisher_publish_sync.py diff --git a/owl-bot-staging/v1/samples/generated_samples/pubsub_generated_pubsub_v1_publisher_update_topic_async.py b/samples/generated_samples/pubsub_generated_pubsub_v1_publisher_update_topic_async.py similarity index 100% rename from owl-bot-staging/v1/samples/generated_samples/pubsub_generated_pubsub_v1_publisher_update_topic_async.py rename to samples/generated_samples/pubsub_generated_pubsub_v1_publisher_update_topic_async.py diff --git a/owl-bot-staging/v1/samples/generated_samples/pubsub_generated_pubsub_v1_publisher_update_topic_sync.py b/samples/generated_samples/pubsub_generated_pubsub_v1_publisher_update_topic_sync.py similarity index 100% rename from owl-bot-staging/v1/samples/generated_samples/pubsub_generated_pubsub_v1_publisher_update_topic_sync.py rename to samples/generated_samples/pubsub_generated_pubsub_v1_publisher_update_topic_sync.py diff --git a/owl-bot-staging/v1/samples/generated_samples/pubsub_generated_pubsub_v1_schema_service_create_schema_async.py b/samples/generated_samples/pubsub_generated_pubsub_v1_schema_service_create_schema_async.py similarity index 100% rename from owl-bot-staging/v1/samples/generated_samples/pubsub_generated_pubsub_v1_schema_service_create_schema_async.py rename to samples/generated_samples/pubsub_generated_pubsub_v1_schema_service_create_schema_async.py diff --git a/owl-bot-staging/v1/samples/generated_samples/pubsub_generated_pubsub_v1_schema_service_create_schema_sync.py b/samples/generated_samples/pubsub_generated_pubsub_v1_schema_service_create_schema_sync.py similarity index 100% rename from owl-bot-staging/v1/samples/generated_samples/pubsub_generated_pubsub_v1_schema_service_create_schema_sync.py rename to samples/generated_samples/pubsub_generated_pubsub_v1_schema_service_create_schema_sync.py diff --git a/owl-bot-staging/v1/samples/generated_samples/pubsub_generated_pubsub_v1_schema_service_delete_schema_async.py b/samples/generated_samples/pubsub_generated_pubsub_v1_schema_service_delete_schema_async.py similarity index 100% rename from owl-bot-staging/v1/samples/generated_samples/pubsub_generated_pubsub_v1_schema_service_delete_schema_async.py rename to samples/generated_samples/pubsub_generated_pubsub_v1_schema_service_delete_schema_async.py diff --git a/owl-bot-staging/v1/samples/generated_samples/pubsub_generated_pubsub_v1_schema_service_delete_schema_sync.py b/samples/generated_samples/pubsub_generated_pubsub_v1_schema_service_delete_schema_sync.py similarity index 100% rename from owl-bot-staging/v1/samples/generated_samples/pubsub_generated_pubsub_v1_schema_service_delete_schema_sync.py rename to samples/generated_samples/pubsub_generated_pubsub_v1_schema_service_delete_schema_sync.py diff --git a/owl-bot-staging/v1/samples/generated_samples/pubsub_generated_pubsub_v1_schema_service_get_schema_async.py b/samples/generated_samples/pubsub_generated_pubsub_v1_schema_service_get_schema_async.py similarity index 100% rename from owl-bot-staging/v1/samples/generated_samples/pubsub_generated_pubsub_v1_schema_service_get_schema_async.py rename to samples/generated_samples/pubsub_generated_pubsub_v1_schema_service_get_schema_async.py diff --git a/owl-bot-staging/v1/samples/generated_samples/pubsub_generated_pubsub_v1_schema_service_get_schema_sync.py b/samples/generated_samples/pubsub_generated_pubsub_v1_schema_service_get_schema_sync.py similarity index 100% rename from owl-bot-staging/v1/samples/generated_samples/pubsub_generated_pubsub_v1_schema_service_get_schema_sync.py rename to samples/generated_samples/pubsub_generated_pubsub_v1_schema_service_get_schema_sync.py diff --git a/owl-bot-staging/v1/samples/generated_samples/pubsub_generated_pubsub_v1_schema_service_list_schemas_async.py b/samples/generated_samples/pubsub_generated_pubsub_v1_schema_service_list_schemas_async.py similarity index 100% rename from owl-bot-staging/v1/samples/generated_samples/pubsub_generated_pubsub_v1_schema_service_list_schemas_async.py rename to samples/generated_samples/pubsub_generated_pubsub_v1_schema_service_list_schemas_async.py diff --git a/owl-bot-staging/v1/samples/generated_samples/pubsub_generated_pubsub_v1_schema_service_list_schemas_sync.py b/samples/generated_samples/pubsub_generated_pubsub_v1_schema_service_list_schemas_sync.py similarity index 100% rename from owl-bot-staging/v1/samples/generated_samples/pubsub_generated_pubsub_v1_schema_service_list_schemas_sync.py rename to samples/generated_samples/pubsub_generated_pubsub_v1_schema_service_list_schemas_sync.py diff --git a/owl-bot-staging/v1/samples/generated_samples/pubsub_generated_pubsub_v1_schema_service_validate_message_async.py b/samples/generated_samples/pubsub_generated_pubsub_v1_schema_service_validate_message_async.py similarity index 100% rename from owl-bot-staging/v1/samples/generated_samples/pubsub_generated_pubsub_v1_schema_service_validate_message_async.py rename to samples/generated_samples/pubsub_generated_pubsub_v1_schema_service_validate_message_async.py diff --git a/owl-bot-staging/v1/samples/generated_samples/pubsub_generated_pubsub_v1_schema_service_validate_message_sync.py b/samples/generated_samples/pubsub_generated_pubsub_v1_schema_service_validate_message_sync.py similarity index 100% rename from owl-bot-staging/v1/samples/generated_samples/pubsub_generated_pubsub_v1_schema_service_validate_message_sync.py rename to samples/generated_samples/pubsub_generated_pubsub_v1_schema_service_validate_message_sync.py diff --git a/owl-bot-staging/v1/samples/generated_samples/pubsub_generated_pubsub_v1_schema_service_validate_schema_async.py b/samples/generated_samples/pubsub_generated_pubsub_v1_schema_service_validate_schema_async.py similarity index 100% rename from owl-bot-staging/v1/samples/generated_samples/pubsub_generated_pubsub_v1_schema_service_validate_schema_async.py rename to samples/generated_samples/pubsub_generated_pubsub_v1_schema_service_validate_schema_async.py diff --git a/owl-bot-staging/v1/samples/generated_samples/pubsub_generated_pubsub_v1_schema_service_validate_schema_sync.py b/samples/generated_samples/pubsub_generated_pubsub_v1_schema_service_validate_schema_sync.py similarity index 100% rename from owl-bot-staging/v1/samples/generated_samples/pubsub_generated_pubsub_v1_schema_service_validate_schema_sync.py rename to samples/generated_samples/pubsub_generated_pubsub_v1_schema_service_validate_schema_sync.py diff --git a/owl-bot-staging/v1/samples/generated_samples/pubsub_generated_pubsub_v1_subscriber_acknowledge_async.py b/samples/generated_samples/pubsub_generated_pubsub_v1_subscriber_acknowledge_async.py similarity index 100% rename from owl-bot-staging/v1/samples/generated_samples/pubsub_generated_pubsub_v1_subscriber_acknowledge_async.py rename to samples/generated_samples/pubsub_generated_pubsub_v1_subscriber_acknowledge_async.py diff --git a/owl-bot-staging/v1/samples/generated_samples/pubsub_generated_pubsub_v1_subscriber_acknowledge_sync.py b/samples/generated_samples/pubsub_generated_pubsub_v1_subscriber_acknowledge_sync.py similarity index 100% rename from owl-bot-staging/v1/samples/generated_samples/pubsub_generated_pubsub_v1_subscriber_acknowledge_sync.py rename to samples/generated_samples/pubsub_generated_pubsub_v1_subscriber_acknowledge_sync.py diff --git a/owl-bot-staging/v1/samples/generated_samples/pubsub_generated_pubsub_v1_subscriber_create_snapshot_async.py b/samples/generated_samples/pubsub_generated_pubsub_v1_subscriber_create_snapshot_async.py similarity index 100% rename from owl-bot-staging/v1/samples/generated_samples/pubsub_generated_pubsub_v1_subscriber_create_snapshot_async.py rename to samples/generated_samples/pubsub_generated_pubsub_v1_subscriber_create_snapshot_async.py diff --git a/owl-bot-staging/v1/samples/generated_samples/pubsub_generated_pubsub_v1_subscriber_create_snapshot_sync.py b/samples/generated_samples/pubsub_generated_pubsub_v1_subscriber_create_snapshot_sync.py similarity index 100% rename from owl-bot-staging/v1/samples/generated_samples/pubsub_generated_pubsub_v1_subscriber_create_snapshot_sync.py rename to samples/generated_samples/pubsub_generated_pubsub_v1_subscriber_create_snapshot_sync.py diff --git a/owl-bot-staging/v1/samples/generated_samples/pubsub_generated_pubsub_v1_subscriber_create_subscription_async.py b/samples/generated_samples/pubsub_generated_pubsub_v1_subscriber_create_subscription_async.py similarity index 100% rename from owl-bot-staging/v1/samples/generated_samples/pubsub_generated_pubsub_v1_subscriber_create_subscription_async.py rename to samples/generated_samples/pubsub_generated_pubsub_v1_subscriber_create_subscription_async.py diff --git a/owl-bot-staging/v1/samples/generated_samples/pubsub_generated_pubsub_v1_subscriber_create_subscription_sync.py b/samples/generated_samples/pubsub_generated_pubsub_v1_subscriber_create_subscription_sync.py similarity index 100% rename from owl-bot-staging/v1/samples/generated_samples/pubsub_generated_pubsub_v1_subscriber_create_subscription_sync.py rename to samples/generated_samples/pubsub_generated_pubsub_v1_subscriber_create_subscription_sync.py diff --git a/owl-bot-staging/v1/samples/generated_samples/pubsub_generated_pubsub_v1_subscriber_delete_snapshot_async.py b/samples/generated_samples/pubsub_generated_pubsub_v1_subscriber_delete_snapshot_async.py similarity index 100% rename from owl-bot-staging/v1/samples/generated_samples/pubsub_generated_pubsub_v1_subscriber_delete_snapshot_async.py rename to samples/generated_samples/pubsub_generated_pubsub_v1_subscriber_delete_snapshot_async.py diff --git a/owl-bot-staging/v1/samples/generated_samples/pubsub_generated_pubsub_v1_subscriber_delete_snapshot_sync.py b/samples/generated_samples/pubsub_generated_pubsub_v1_subscriber_delete_snapshot_sync.py similarity index 100% rename from owl-bot-staging/v1/samples/generated_samples/pubsub_generated_pubsub_v1_subscriber_delete_snapshot_sync.py rename to samples/generated_samples/pubsub_generated_pubsub_v1_subscriber_delete_snapshot_sync.py diff --git a/owl-bot-staging/v1/samples/generated_samples/pubsub_generated_pubsub_v1_subscriber_delete_subscription_async.py b/samples/generated_samples/pubsub_generated_pubsub_v1_subscriber_delete_subscription_async.py similarity index 100% rename from owl-bot-staging/v1/samples/generated_samples/pubsub_generated_pubsub_v1_subscriber_delete_subscription_async.py rename to samples/generated_samples/pubsub_generated_pubsub_v1_subscriber_delete_subscription_async.py diff --git a/owl-bot-staging/v1/samples/generated_samples/pubsub_generated_pubsub_v1_subscriber_delete_subscription_sync.py b/samples/generated_samples/pubsub_generated_pubsub_v1_subscriber_delete_subscription_sync.py similarity index 100% rename from owl-bot-staging/v1/samples/generated_samples/pubsub_generated_pubsub_v1_subscriber_delete_subscription_sync.py rename to samples/generated_samples/pubsub_generated_pubsub_v1_subscriber_delete_subscription_sync.py diff --git a/owl-bot-staging/v1/samples/generated_samples/pubsub_generated_pubsub_v1_subscriber_get_snapshot_async.py b/samples/generated_samples/pubsub_generated_pubsub_v1_subscriber_get_snapshot_async.py similarity index 100% rename from owl-bot-staging/v1/samples/generated_samples/pubsub_generated_pubsub_v1_subscriber_get_snapshot_async.py rename to samples/generated_samples/pubsub_generated_pubsub_v1_subscriber_get_snapshot_async.py diff --git a/owl-bot-staging/v1/samples/generated_samples/pubsub_generated_pubsub_v1_subscriber_get_snapshot_sync.py b/samples/generated_samples/pubsub_generated_pubsub_v1_subscriber_get_snapshot_sync.py similarity index 100% rename from owl-bot-staging/v1/samples/generated_samples/pubsub_generated_pubsub_v1_subscriber_get_snapshot_sync.py rename to samples/generated_samples/pubsub_generated_pubsub_v1_subscriber_get_snapshot_sync.py diff --git a/owl-bot-staging/v1/samples/generated_samples/pubsub_generated_pubsub_v1_subscriber_get_subscription_async.py b/samples/generated_samples/pubsub_generated_pubsub_v1_subscriber_get_subscription_async.py similarity index 100% rename from owl-bot-staging/v1/samples/generated_samples/pubsub_generated_pubsub_v1_subscriber_get_subscription_async.py rename to samples/generated_samples/pubsub_generated_pubsub_v1_subscriber_get_subscription_async.py diff --git a/owl-bot-staging/v1/samples/generated_samples/pubsub_generated_pubsub_v1_subscriber_get_subscription_sync.py b/samples/generated_samples/pubsub_generated_pubsub_v1_subscriber_get_subscription_sync.py similarity index 100% rename from owl-bot-staging/v1/samples/generated_samples/pubsub_generated_pubsub_v1_subscriber_get_subscription_sync.py rename to samples/generated_samples/pubsub_generated_pubsub_v1_subscriber_get_subscription_sync.py diff --git a/owl-bot-staging/v1/samples/generated_samples/pubsub_generated_pubsub_v1_subscriber_list_snapshots_async.py b/samples/generated_samples/pubsub_generated_pubsub_v1_subscriber_list_snapshots_async.py similarity index 100% rename from owl-bot-staging/v1/samples/generated_samples/pubsub_generated_pubsub_v1_subscriber_list_snapshots_async.py rename to samples/generated_samples/pubsub_generated_pubsub_v1_subscriber_list_snapshots_async.py diff --git a/owl-bot-staging/v1/samples/generated_samples/pubsub_generated_pubsub_v1_subscriber_list_snapshots_sync.py b/samples/generated_samples/pubsub_generated_pubsub_v1_subscriber_list_snapshots_sync.py similarity index 100% rename from owl-bot-staging/v1/samples/generated_samples/pubsub_generated_pubsub_v1_subscriber_list_snapshots_sync.py rename to samples/generated_samples/pubsub_generated_pubsub_v1_subscriber_list_snapshots_sync.py diff --git a/owl-bot-staging/v1/samples/generated_samples/pubsub_generated_pubsub_v1_subscriber_list_subscriptions_async.py b/samples/generated_samples/pubsub_generated_pubsub_v1_subscriber_list_subscriptions_async.py similarity index 100% rename from owl-bot-staging/v1/samples/generated_samples/pubsub_generated_pubsub_v1_subscriber_list_subscriptions_async.py rename to samples/generated_samples/pubsub_generated_pubsub_v1_subscriber_list_subscriptions_async.py diff --git a/owl-bot-staging/v1/samples/generated_samples/pubsub_generated_pubsub_v1_subscriber_list_subscriptions_sync.py b/samples/generated_samples/pubsub_generated_pubsub_v1_subscriber_list_subscriptions_sync.py similarity index 100% rename from owl-bot-staging/v1/samples/generated_samples/pubsub_generated_pubsub_v1_subscriber_list_subscriptions_sync.py rename to samples/generated_samples/pubsub_generated_pubsub_v1_subscriber_list_subscriptions_sync.py diff --git a/owl-bot-staging/v1/samples/generated_samples/pubsub_generated_pubsub_v1_subscriber_modify_ack_deadline_async.py b/samples/generated_samples/pubsub_generated_pubsub_v1_subscriber_modify_ack_deadline_async.py similarity index 100% rename from owl-bot-staging/v1/samples/generated_samples/pubsub_generated_pubsub_v1_subscriber_modify_ack_deadline_async.py rename to samples/generated_samples/pubsub_generated_pubsub_v1_subscriber_modify_ack_deadline_async.py diff --git a/owl-bot-staging/v1/samples/generated_samples/pubsub_generated_pubsub_v1_subscriber_modify_ack_deadline_sync.py b/samples/generated_samples/pubsub_generated_pubsub_v1_subscriber_modify_ack_deadline_sync.py similarity index 100% rename from owl-bot-staging/v1/samples/generated_samples/pubsub_generated_pubsub_v1_subscriber_modify_ack_deadline_sync.py rename to samples/generated_samples/pubsub_generated_pubsub_v1_subscriber_modify_ack_deadline_sync.py diff --git a/owl-bot-staging/v1/samples/generated_samples/pubsub_generated_pubsub_v1_subscriber_modify_push_config_async.py b/samples/generated_samples/pubsub_generated_pubsub_v1_subscriber_modify_push_config_async.py similarity index 100% rename from owl-bot-staging/v1/samples/generated_samples/pubsub_generated_pubsub_v1_subscriber_modify_push_config_async.py rename to samples/generated_samples/pubsub_generated_pubsub_v1_subscriber_modify_push_config_async.py diff --git a/owl-bot-staging/v1/samples/generated_samples/pubsub_generated_pubsub_v1_subscriber_modify_push_config_sync.py b/samples/generated_samples/pubsub_generated_pubsub_v1_subscriber_modify_push_config_sync.py similarity index 100% rename from owl-bot-staging/v1/samples/generated_samples/pubsub_generated_pubsub_v1_subscriber_modify_push_config_sync.py rename to samples/generated_samples/pubsub_generated_pubsub_v1_subscriber_modify_push_config_sync.py diff --git a/owl-bot-staging/v1/samples/generated_samples/pubsub_generated_pubsub_v1_subscriber_pull_async.py b/samples/generated_samples/pubsub_generated_pubsub_v1_subscriber_pull_async.py similarity index 100% rename from owl-bot-staging/v1/samples/generated_samples/pubsub_generated_pubsub_v1_subscriber_pull_async.py rename to samples/generated_samples/pubsub_generated_pubsub_v1_subscriber_pull_async.py diff --git a/owl-bot-staging/v1/samples/generated_samples/pubsub_generated_pubsub_v1_subscriber_pull_sync.py b/samples/generated_samples/pubsub_generated_pubsub_v1_subscriber_pull_sync.py similarity index 100% rename from owl-bot-staging/v1/samples/generated_samples/pubsub_generated_pubsub_v1_subscriber_pull_sync.py rename to samples/generated_samples/pubsub_generated_pubsub_v1_subscriber_pull_sync.py diff --git a/owl-bot-staging/v1/samples/generated_samples/pubsub_generated_pubsub_v1_subscriber_seek_async.py b/samples/generated_samples/pubsub_generated_pubsub_v1_subscriber_seek_async.py similarity index 100% rename from owl-bot-staging/v1/samples/generated_samples/pubsub_generated_pubsub_v1_subscriber_seek_async.py rename to samples/generated_samples/pubsub_generated_pubsub_v1_subscriber_seek_async.py diff --git a/owl-bot-staging/v1/samples/generated_samples/pubsub_generated_pubsub_v1_subscriber_seek_sync.py b/samples/generated_samples/pubsub_generated_pubsub_v1_subscriber_seek_sync.py similarity index 100% rename from owl-bot-staging/v1/samples/generated_samples/pubsub_generated_pubsub_v1_subscriber_seek_sync.py rename to samples/generated_samples/pubsub_generated_pubsub_v1_subscriber_seek_sync.py diff --git a/owl-bot-staging/v1/samples/generated_samples/pubsub_generated_pubsub_v1_subscriber_streaming_pull_async.py b/samples/generated_samples/pubsub_generated_pubsub_v1_subscriber_streaming_pull_async.py similarity index 100% rename from owl-bot-staging/v1/samples/generated_samples/pubsub_generated_pubsub_v1_subscriber_streaming_pull_async.py rename to samples/generated_samples/pubsub_generated_pubsub_v1_subscriber_streaming_pull_async.py diff --git a/owl-bot-staging/v1/samples/generated_samples/pubsub_generated_pubsub_v1_subscriber_streaming_pull_sync.py b/samples/generated_samples/pubsub_generated_pubsub_v1_subscriber_streaming_pull_sync.py similarity index 100% rename from owl-bot-staging/v1/samples/generated_samples/pubsub_generated_pubsub_v1_subscriber_streaming_pull_sync.py rename to samples/generated_samples/pubsub_generated_pubsub_v1_subscriber_streaming_pull_sync.py diff --git a/owl-bot-staging/v1/samples/generated_samples/pubsub_generated_pubsub_v1_subscriber_update_snapshot_async.py b/samples/generated_samples/pubsub_generated_pubsub_v1_subscriber_update_snapshot_async.py similarity index 100% rename from owl-bot-staging/v1/samples/generated_samples/pubsub_generated_pubsub_v1_subscriber_update_snapshot_async.py rename to samples/generated_samples/pubsub_generated_pubsub_v1_subscriber_update_snapshot_async.py diff --git a/owl-bot-staging/v1/samples/generated_samples/pubsub_generated_pubsub_v1_subscriber_update_snapshot_sync.py b/samples/generated_samples/pubsub_generated_pubsub_v1_subscriber_update_snapshot_sync.py similarity index 100% rename from owl-bot-staging/v1/samples/generated_samples/pubsub_generated_pubsub_v1_subscriber_update_snapshot_sync.py rename to samples/generated_samples/pubsub_generated_pubsub_v1_subscriber_update_snapshot_sync.py diff --git a/owl-bot-staging/v1/samples/generated_samples/pubsub_generated_pubsub_v1_subscriber_update_subscription_async.py b/samples/generated_samples/pubsub_generated_pubsub_v1_subscriber_update_subscription_async.py similarity index 100% rename from owl-bot-staging/v1/samples/generated_samples/pubsub_generated_pubsub_v1_subscriber_update_subscription_async.py rename to samples/generated_samples/pubsub_generated_pubsub_v1_subscriber_update_subscription_async.py diff --git a/owl-bot-staging/v1/samples/generated_samples/pubsub_generated_pubsub_v1_subscriber_update_subscription_sync.py b/samples/generated_samples/pubsub_generated_pubsub_v1_subscriber_update_subscription_sync.py similarity index 100% rename from owl-bot-staging/v1/samples/generated_samples/pubsub_generated_pubsub_v1_subscriber_update_subscription_sync.py rename to samples/generated_samples/pubsub_generated_pubsub_v1_subscriber_update_subscription_sync.py diff --git a/owl-bot-staging/v1/samples/generated_samples/snippet_metadata_pubsub_v1.json b/samples/generated_samples/snippet_metadata_pubsub_v1.json similarity index 100% rename from owl-bot-staging/v1/samples/generated_samples/snippet_metadata_pubsub_v1.json rename to samples/generated_samples/snippet_metadata_pubsub_v1.json diff --git a/scripts/fixup_pubsub_v1_keywords.py b/scripts/fixup_pubsub_v1_keywords.py index ab7623917..039fa1e8f 100644 --- a/scripts/fixup_pubsub_v1_keywords.py +++ b/scripts/fixup_pubsub_v1_keywords.py @@ -42,7 +42,7 @@ class pubsubCallTransformer(cst.CSTTransformer): 'acknowledge': ('subscription', 'ack_ids', ), 'create_schema': ('parent', 'schema', 'schema_id', ), 'create_snapshot': ('name', 'subscription', 'labels', ), - 'create_subscription': ('name', 'topic', 'push_config', 'ack_deadline_seconds', 'retain_acked_messages', 'message_retention_duration', 'labels', 'enable_message_ordering', 'expiration_policy', 'filter', 'dead_letter_policy', 'retry_policy', 'detached', 'topic_message_retention_duration', ), + 'create_subscription': ('name', 'topic', 'push_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', ), 'create_topic': ('name', 'labels', 'message_storage_policy', 'kms_key_name', 'schema_settings', 'satisfies_pzs', 'message_retention_duration', ), 'delete_schema': ('name', ), 'delete_snapshot': ('snapshot', ), diff --git a/tests/unit/gapic/pubsub_v1/test_subscriber.py b/tests/unit/gapic/pubsub_v1/test_subscriber.py index 37a208c34..7ba54cc6d 100644 --- a/tests/unit/gapic/pubsub_v1/test_subscriber.py +++ b/tests/unit/gapic/pubsub_v1/test_subscriber.py @@ -638,6 +638,7 @@ def test_create_subscription(request_type, transport: str = "grpc"): enable_message_ordering=True, filter="filter_value", detached=True, + enable_exactly_once_delivery=True, ) response = client.create_subscription(request) @@ -655,6 +656,7 @@ def test_create_subscription(request_type, transport: str = "grpc"): 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 def test_create_subscription_empty_call(): @@ -700,6 +702,7 @@ async def test_create_subscription_async( enable_message_ordering=True, filter="filter_value", detached=True, + enable_exactly_once_delivery=True, ) ) response = await client.create_subscription(request) @@ -718,6 +721,7 @@ async def test_create_subscription_async( 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 @pytest.mark.asyncio @@ -905,6 +909,7 @@ def test_get_subscription(request_type, transport: str = "grpc"): enable_message_ordering=True, filter="filter_value", detached=True, + enable_exactly_once_delivery=True, ) response = client.get_subscription(request) @@ -922,6 +927,7 @@ def test_get_subscription(request_type, transport: str = "grpc"): 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 def test_get_subscription_empty_call(): @@ -963,6 +969,7 @@ async def test_get_subscription_async( enable_message_ordering=True, filter="filter_value", detached=True, + enable_exactly_once_delivery=True, ) ) response = await client.get_subscription(request) @@ -981,6 +988,7 @@ async def test_get_subscription_async( 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 @pytest.mark.asyncio @@ -1130,6 +1138,7 @@ def test_update_subscription(request_type, transport: str = "grpc"): enable_message_ordering=True, filter="filter_value", detached=True, + enable_exactly_once_delivery=True, ) response = client.update_subscription(request) @@ -1147,6 +1156,7 @@ def test_update_subscription(request_type, transport: str = "grpc"): 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 def test_update_subscription_empty_call(): @@ -1192,6 +1202,7 @@ async def test_update_subscription_async( enable_message_ordering=True, filter="filter_value", detached=True, + enable_exactly_once_delivery=True, ) ) response = await client.update_subscription(request) @@ -1210,6 +1221,7 @@ async def test_update_subscription_async( 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 @pytest.mark.asyncio