From e041eb5a78896dd72557cde34267cf8d9c357451 Mon Sep 17 00:00:00 2001 From: yoshi-automation Date: Sun, 18 Jul 2021 04:30:11 +0000 Subject: [PATCH 01/18] changes without context autosynth cannot find the source of changes triggered by earlier changes in this repository, or by version upgrades to tools such as linters. --- .kokoro/docker/docs/Dockerfile | 35 +-------------- .kokoro/docker/docs/fetch_gpg_keys.sh | 45 ------------------- .kokoro/presubmit/common.cfg | 8 ++-- .kokoro/presubmit/presubmit.cfg | 7 +-- .kokoro/samples/python3.9/common.cfg | 40 +++++++++++++++++ .kokoro/samples/python3.9/continuous.cfg | 6 +++ .kokoro/samples/python3.9/periodic-head.cfg | 11 +++++ .kokoro/samples/python3.9/periodic.cfg | 6 +++ .kokoro/samples/python3.9/presubmit.cfg | 6 +++ .kokoro/test-samples-impl.sh | 6 +-- .pre-commit-config.yaml | 4 +- CONTRIBUTING.rst | 37 ++++----------- docs/conf.py | 13 +++--- docs/multiprocessing.rst | 4 +- .../services/publisher/async_client.py | 9 ++++ google/pubsub_v1/services/publisher/client.py | 5 +++ google/pubsub_v1/types/__init__.py | 2 + noxfile.py | 20 +++------ samples/snippets/noxfile.py | 13 ++++-- synth.metadata | 30 +++---------- 20 files changed, 137 insertions(+), 170 deletions(-) delete mode 100755 .kokoro/docker/docs/fetch_gpg_keys.sh create mode 100644 .kokoro/samples/python3.9/common.cfg create mode 100644 .kokoro/samples/python3.9/continuous.cfg create mode 100644 .kokoro/samples/python3.9/periodic-head.cfg create mode 100644 .kokoro/samples/python3.9/periodic.cfg create mode 100644 .kokoro/samples/python3.9/presubmit.cfg diff --git a/.kokoro/docker/docs/Dockerfile b/.kokoro/docker/docs/Dockerfile index 412b0b56a..4e1b1fb8b 100644 --- a/.kokoro/docker/docs/Dockerfile +++ b/.kokoro/docker/docs/Dockerfile @@ -40,6 +40,7 @@ RUN apt-get update \ libssl-dev \ libsqlite3-dev \ portaudio19-dev \ + python3-distutils \ redis-server \ software-properties-common \ ssh \ @@ -59,40 +60,8 @@ RUN apt-get update \ && rm -rf /var/lib/apt/lists/* \ && rm -f /var/cache/apt/archives/*.deb - -COPY fetch_gpg_keys.sh /tmp -# Install the desired versions of Python. -RUN set -ex \ - && export GNUPGHOME="$(mktemp -d)" \ - && echo "disable-ipv6" >> "${GNUPGHOME}/dirmngr.conf" \ - && /tmp/fetch_gpg_keys.sh \ - && for PYTHON_VERSION in 3.7.8 3.8.5; do \ - wget --no-check-certificate -O python-${PYTHON_VERSION}.tar.xz "https://www.python.org/ftp/python/${PYTHON_VERSION%%[a-z]*}/Python-$PYTHON_VERSION.tar.xz" \ - && wget --no-check-certificate -O python-${PYTHON_VERSION}.tar.xz.asc "https://www.python.org/ftp/python/${PYTHON_VERSION%%[a-z]*}/Python-$PYTHON_VERSION.tar.xz.asc" \ - && gpg --batch --verify python-${PYTHON_VERSION}.tar.xz.asc python-${PYTHON_VERSION}.tar.xz \ - && rm -r python-${PYTHON_VERSION}.tar.xz.asc \ - && mkdir -p /usr/src/python-${PYTHON_VERSION} \ - && tar -xJC /usr/src/python-${PYTHON_VERSION} --strip-components=1 -f python-${PYTHON_VERSION}.tar.xz \ - && rm python-${PYTHON_VERSION}.tar.xz \ - && cd /usr/src/python-${PYTHON_VERSION} \ - && ./configure \ - --enable-shared \ - # This works only on Python 2.7 and throws a warning on every other - # version, but seems otherwise harmless. - --enable-unicode=ucs4 \ - --with-system-ffi \ - --without-ensurepip \ - && make -j$(nproc) \ - && make install \ - && ldconfig \ - ; done \ - && rm -rf "${GNUPGHOME}" \ - && rm -rf /usr/src/python* \ - && rm -rf ~/.cache/ - RUN wget -O /tmp/get-pip.py 'https://bootstrap.pypa.io/get-pip.py' \ - && python3.7 /tmp/get-pip.py \ && python3.8 /tmp/get-pip.py \ && rm /tmp/get-pip.py -CMD ["python3.7"] +CMD ["python3.8"] diff --git a/.kokoro/docker/docs/fetch_gpg_keys.sh b/.kokoro/docker/docs/fetch_gpg_keys.sh deleted file mode 100755 index d653dd868..000000000 --- a/.kokoro/docker/docs/fetch_gpg_keys.sh +++ /dev/null @@ -1,45 +0,0 @@ -#!/bin/bash -# 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. - -# A script to fetch gpg keys with retry. -# Avoid jinja parsing the file. -# - -function retry { - if [[ "${#}" -le 1 ]]; then - echo "Usage: ${0} retry_count commands.." - exit 1 - fi - local retries=${1} - local command="${@:2}" - until [[ "${retries}" -le 0 ]]; do - $command && return 0 - if [[ $? -ne 0 ]]; then - echo "command failed, retrying" - ((retries--)) - fi - done - return 1 -} - -# 3.6.9, 3.7.5 (Ned Deily) -retry 3 gpg --keyserver ha.pool.sks-keyservers.net --recv-keys \ - 0D96DF4D4110E5C43FBFB17F2D347EA6AA65421D - -# 3.8.0 (Ɓukasz Langa) -retry 3 gpg --keyserver ha.pool.sks-keyservers.net --recv-keys \ - E3FF2839C048B25C084DEBE9B26995E310250568 - -# diff --git a/.kokoro/presubmit/common.cfg b/.kokoro/presubmit/common.cfg index 7d78fd1f7..a812af888 100644 --- a/.kokoro/presubmit/common.cfg +++ b/.kokoro/presubmit/common.cfg @@ -21,9 +21,7 @@ env_vars: { key: "TRAMPOLINE_IMAGE" value: "gcr.io/cloud-devrel-kokoro-resources/python-multi" } - -# Obtain environment variables for running Pub/Sub Lite samples tests env_vars: { - key: "SECRET_MANAGER_KEYS" - value: "python-docs-samples-test-env" -} \ No newline at end of file + key: "TRAMPOLINE_BUILD_FILE" + value: "github/python-pubsub/.kokoro/build.sh" +} diff --git a/.kokoro/presubmit/presubmit.cfg b/.kokoro/presubmit/presubmit.cfg index 9b689c788..8f43917d9 100644 --- a/.kokoro/presubmit/presubmit.cfg +++ b/.kokoro/presubmit/presubmit.cfg @@ -1,6 +1 @@ -# Format: //devtools/kokoro/config/proto/build.proto - -env_vars: { - key: "TRAMPOLINE_BUILD_FILE" - value: "github/python-pubsub/.kokoro/build.sh" -} \ No newline at end of file +# Format: //devtools/kokoro/config/proto/build.proto \ No newline at end of file diff --git a/.kokoro/samples/python3.9/common.cfg b/.kokoro/samples/python3.9/common.cfg new file mode 100644 index 000000000..b858ccbd4 --- /dev/null +++ b/.kokoro/samples/python3.9/common.cfg @@ -0,0 +1,40 @@ +# Format: //devtools/kokoro/config/proto/build.proto + +# Build logs will be here +action { + define_artifacts { + regex: "**/*sponge_log.xml" + } +} + +# Specify which tests to run +env_vars: { + key: "RUN_TESTS_SESSION" + value: "py-3.9" +} + +# Declare build specific Cloud project. +env_vars: { + key: "BUILD_SPECIFIC_GCLOUD_PROJECT" + value: "python-docs-samples-tests-py39" +} + +env_vars: { + key: "TRAMPOLINE_BUILD_FILE" + value: "github/python-pubsub/.kokoro/test-samples.sh" +} + +# Configure the docker image for kokoro-trampoline. +env_vars: { + key: "TRAMPOLINE_IMAGE" + value: "gcr.io/cloud-devrel-kokoro-resources/python-samples-testing-docker" +} + +# Download secrets for samples +gfile_resources: "/bigstore/cloud-devrel-kokoro-resources/python-docs-samples" + +# Download trampoline resources. +gfile_resources: "/bigstore/cloud-devrel-kokoro-resources/trampoline" + +# Use the trampoline script to run in docker. +build_file: "python-pubsub/.kokoro/trampoline.sh" \ No newline at end of file diff --git a/.kokoro/samples/python3.9/continuous.cfg b/.kokoro/samples/python3.9/continuous.cfg new file mode 100644 index 000000000..a1c8d9759 --- /dev/null +++ b/.kokoro/samples/python3.9/continuous.cfg @@ -0,0 +1,6 @@ +# Format: //devtools/kokoro/config/proto/build.proto + +env_vars: { + key: "INSTALL_LIBRARY_FROM_SOURCE" + value: "True" +} \ No newline at end of file diff --git a/.kokoro/samples/python3.9/periodic-head.cfg b/.kokoro/samples/python3.9/periodic-head.cfg new file mode 100644 index 000000000..f9cfcd33e --- /dev/null +++ b/.kokoro/samples/python3.9/periodic-head.cfg @@ -0,0 +1,11 @@ +# Format: //devtools/kokoro/config/proto/build.proto + +env_vars: { + key: "INSTALL_LIBRARY_FROM_SOURCE" + value: "True" +} + +env_vars: { + key: "TRAMPOLINE_BUILD_FILE" + value: "github/python-pubsub/.kokoro/test-samples-against-head.sh" +} diff --git a/.kokoro/samples/python3.9/periodic.cfg b/.kokoro/samples/python3.9/periodic.cfg new file mode 100644 index 000000000..50fec9649 --- /dev/null +++ b/.kokoro/samples/python3.9/periodic.cfg @@ -0,0 +1,6 @@ +# Format: //devtools/kokoro/config/proto/build.proto + +env_vars: { + key: "INSTALL_LIBRARY_FROM_SOURCE" + value: "False" +} \ No newline at end of file diff --git a/.kokoro/samples/python3.9/presubmit.cfg b/.kokoro/samples/python3.9/presubmit.cfg new file mode 100644 index 000000000..a1c8d9759 --- /dev/null +++ b/.kokoro/samples/python3.9/presubmit.cfg @@ -0,0 +1,6 @@ +# Format: //devtools/kokoro/config/proto/build.proto + +env_vars: { + key: "INSTALL_LIBRARY_FROM_SOURCE" + value: "True" +} \ No newline at end of file diff --git a/.kokoro/test-samples-impl.sh b/.kokoro/test-samples-impl.sh index cf5de74c1..311a8d54b 100755 --- a/.kokoro/test-samples-impl.sh +++ b/.kokoro/test-samples-impl.sh @@ -20,9 +20,9 @@ set -eo pipefail # Enables `**` to include files nested inside sub-folders shopt -s globstar -# Exit early if samples directory doesn't exist -if [ ! -d "./samples" ]; then - echo "No tests run. `./samples` not found" +# Exit early if samples don't exist +if ! find samples -name 'requirements.txt' | grep -q .; then + echo "No tests run. './samples/**/requirements.txt' not found" exit 0 fi diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 8912e9b5d..62eb5a77d 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -16,7 +16,7 @@ # See https://pre-commit.com/hooks.html for more hooks repos: - repo: https://github.com/pre-commit/pre-commit-hooks - rev: v3.4.0 + rev: v4.0.1 hooks: - id: trailing-whitespace - id: end-of-file-fixer @@ -26,6 +26,6 @@ repos: hooks: - id: black - repo: https://gitlab.com/pycqa/flake8 - rev: 3.9.0 + rev: 3.9.2 hooks: - id: flake8 diff --git a/CONTRIBUTING.rst b/CONTRIBUTING.rst index 6dbc9d2d6..e2853513f 100644 --- a/CONTRIBUTING.rst +++ b/CONTRIBUTING.rst @@ -68,15 +68,12 @@ Using ``nox`` We use `nox `__ to instrument our tests. - To test your changes, run unit tests with ``nox``:: + $ nox -s unit - $ nox -s unit-2.7 - $ nox -s unit-3.8 - $ ... +- To run a single unit test:: -- Args to pytest can be passed through the nox command separated by a `--`. For - example, to run a single test:: + $ nox -s unit-3.9 -- -k - $ nox -s unit-3.8 -- -k .. note:: @@ -143,8 +140,7 @@ Running System Tests - To run system tests, you can execute:: # Run all system tests - $ nox -s system-3.8 - $ nox -s system-2.7 + $ nox -s system # Run a single system test $ nox -s system-3.8 -- -k @@ -152,29 +148,14 @@ Running System Tests .. note:: - System tests are only configured to run under Python 2.7 and - Python 3.8. For expediency, we do not run them in older versions - of Python 3. + System tests are only configured to run under Python 3.8. + For expediency, we do not run them in older versions of Python 3. This alone will not run the tests. You'll need to change some local auth settings and change some configuration in your project to run all the tests. -- System tests will be run against an actual project and - so you'll need to provide some environment variables to facilitate - authentication to your project: - - - ``GOOGLE_APPLICATION_CREDENTIALS``: The path to a JSON key file; - Such a file can be downloaded directly from the developer's console by clicking - "Generate new JSON key". See private key - `docs `__ - for more details. - -- Once you have downloaded your json keys, set the environment variable - ``GOOGLE_APPLICATION_CREDENTIALS`` to the absolute path of the json file:: - - $ export GOOGLE_APPLICATION_CREDENTIALS="/Users//path/to/app_credentials.json" - +- System tests will be run against an actual project. You should use local credentials from gcloud when possible. See `Best practices for application authentication `__. Some tests require a service account. For those tests see `Authenticating as a service account `__. ************* Test Coverage @@ -232,8 +213,8 @@ Supported versions can be found in our ``noxfile.py`` `config`_. .. _config: https://github.com/googleapis/python-pubsub/blob/master/noxfile.py -We also explicitly decided to support Python 3 beginning with version -3.6. Reasons for this include: +We also explicitly decided to support Python 3 beginning with version 3.6. +Reasons for this include: - Encouraging use of newest versions of Python 3 - Taking the lead of `prominent`_ open-source `projects`_ diff --git a/docs/conf.py b/docs/conf.py index e2d55cde2..b1ed409cf 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -80,9 +80,9 @@ master_doc = "index" # General information about the project. -project = u"google-cloud-pubsub" -copyright = u"2019, Google" -author = u"Google APIs" +project = "google-cloud-pubsub" +copyright = "2019, Google" +author = "Google APIs" # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the @@ -281,7 +281,7 @@ ( master_doc, "google-cloud-pubsub.tex", - u"google-cloud-pubsub Documentation", + "google-cloud-pubsub Documentation", author, "manual", ) @@ -316,7 +316,7 @@ ( master_doc, "google-cloud-pubsub", - u"google-cloud-pubsub Documentation", + "google-cloud-pubsub Documentation", [author], 1, ) @@ -335,7 +335,7 @@ ( master_doc, "google-cloud-pubsub", - u"google-cloud-pubsub Documentation", + "google-cloud-pubsub Documentation", author, "google-cloud-pubsub", "google-cloud-pubsub Library", @@ -363,6 +363,7 @@ "google.api_core": ("https://googleapis.dev/python/google-api-core/latest/", None,), "grpc": ("https://grpc.github.io/grpc/python/", None), "proto-plus": ("https://proto-plus-python.readthedocs.io/en/latest/", None), + "protobuf": ("https://googleapis.dev/python/protobuf/latest/", None), } diff --git a/docs/multiprocessing.rst b/docs/multiprocessing.rst index 1cb29d4ca..536d17b2e 100644 --- a/docs/multiprocessing.rst +++ b/docs/multiprocessing.rst @@ -1,7 +1,7 @@ .. note:: - Because this client uses :mod:`grpcio` library, it is safe to + Because this client uses :mod:`grpc` library, it is safe to share instances across threads. In multiprocessing scenarios, the best practice is to create client instances *after* the invocation of - :func:`os.fork` by :class:`multiprocessing.Pool` or + :func:`os.fork` by :class:`multiprocessing.pool.Pool` or :class:`multiprocessing.Process`. diff --git a/google/pubsub_v1/services/publisher/async_client.py b/google/pubsub_v1/services/publisher/async_client.py index 041391c57..056ba288d 100644 --- a/google/pubsub_v1/services/publisher/async_client.py +++ b/google/pubsub_v1/services/publisher/async_client.py @@ -34,6 +34,7 @@ from google.pubsub_v1.services.publisher import pagers from google.pubsub_v1.types import pubsub from google.pubsub_v1.types import TimeoutType + from .transports.base import PublisherTransport, DEFAULT_CLIENT_INFO from .transports.grpc_asyncio import PublisherGrpcAsyncIOTransport from .client import PublisherClient @@ -272,6 +273,7 @@ async def update_topic( Args: request (:class:`google.pubsub_v1.types.UpdateTopicRequest`): The request object. Request for the UpdateTopic method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (TimeoutType): @@ -345,6 +347,7 @@ async def 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 (TimeoutType): @@ -433,6 +436,7 @@ async def get_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 (TimeoutType): @@ -514,6 +518,7 @@ async def list_topics( 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 (TimeoutType): @@ -608,6 +613,7 @@ async def list_topic_subscriptions( 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 (TimeoutType): @@ -706,6 +712,7 @@ async def list_topic_snapshots( 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 (TimeoutType): @@ -803,6 +810,7 @@ async def delete_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 (TimeoutType): @@ -872,6 +880,7 @@ async def detach_subscription( request (:class:`google.pubsub_v1.types.DetachSubscriptionRequest`): The request object. Request for the DetachSubscription method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (TimeoutType): diff --git a/google/pubsub_v1/services/publisher/client.py b/google/pubsub_v1/services/publisher/client.py index 3f249b01b..3a3db1ebe 100644 --- a/google/pubsub_v1/services/publisher/client.py +++ b/google/pubsub_v1/services/publisher/client.py @@ -796,6 +796,7 @@ def list_topic_subscriptions( 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 (TimeoutType): @@ -1207,6 +1208,8 @@ def get_iam_policy( request (:class:`~.iam_policy.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 (TimeoutType): The timeout for this request. metadata (Sequence[Tuple[str, str]]): Strings which should be @@ -1317,6 +1320,8 @@ def test_iam_permissions( request (:class:`~.iam_policy.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 (TimeoutType): The timeout for this request. metadata (Sequence[Tuple[str, str]]): Strings which should be diff --git a/google/pubsub_v1/types/__init__.py b/google/pubsub_v1/types/__init__.py index ebc8b5399..5203abfe7 100644 --- a/google/pubsub_v1/types/__init__.py +++ b/google/pubsub_v1/types/__init__.py @@ -1,4 +1,5 @@ # -*- coding: utf-8 -*- + # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -13,6 +14,7 @@ # See the License for the specific language governing permissions and # limitations under the License. # + from typing import Union from .pubsub import ( diff --git a/noxfile.py b/noxfile.py index 6ccdf5e63..08c6654f4 100644 --- a/noxfile.py +++ b/noxfile.py @@ -62,16 +62,9 @@ def lint(session): session.run("flake8", "google", "tests") -@nox.session(python="3.6") +@nox.session(python=DEFAULT_PYTHON_VERSION) def blacken(session): - """Run black. - - Format code to uniform standard. - - This currently uses Python 3.6 due to the automated Kokoro run of synthtool. - That run uses an image that doesn't have 3.6 installed. Before updating this - check the state of the `gcp_ubuntu_config` we use for that Kokoro run. - """ + """Run black. Format code to uniform standard.""" session.install(BLACK_VERSION) session.run( "black", *BLACK_PATHS, @@ -131,9 +124,6 @@ def system(session): # Check the value of `RUN_SYSTEM_TESTS` env var. It defaults to true. if os.environ.get("RUN_SYSTEM_TESTS", "true") == "false": session.skip("RUN_SYSTEM_TESTS is set to false, skipping") - # Sanity check: Only run tests if the environment variable is set. - if not os.environ.get("GOOGLE_APPLICATION_CREDENTIALS", ""): - session.skip("Credentials must be set via environment variable") # Install pyopenssl for mTLS testing. if os.environ.get("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") == "true": session.install("pyopenssl") @@ -191,7 +181,7 @@ def docs(session): """Build the docs for this library.""" session.install("-e", ".") - session.install("sphinx", "alabaster", "recommonmark") + session.install("sphinx==4.0.1", "alabaster", "recommonmark") shutil.rmtree(os.path.join("docs", "_build"), ignore_errors=True) session.run( @@ -213,7 +203,9 @@ def docfx(session): """Build the docfx yaml files for this library.""" session.install("-e", ".") - session.install("sphinx", "alabaster", "recommonmark", "gcp-sphinx-docfx-yaml") + session.install( + "sphinx==4.0.1", "alabaster", "recommonmark", "gcp-sphinx-docfx-yaml" + ) shutil.rmtree(os.path.join("docs", "_build"), ignore_errors=True) session.run( diff --git a/samples/snippets/noxfile.py b/samples/snippets/noxfile.py index 956cdf4f9..6a8ccdae2 100644 --- a/samples/snippets/noxfile.py +++ b/samples/snippets/noxfile.py @@ -28,8 +28,9 @@ # WARNING - WARNING - WARNING - WARNING - WARNING # WARNING - WARNING - WARNING - WARNING - WARNING -# Copy `noxfile_config.py` to your directory and modify it instead. +BLACK_VERSION = "black==19.10b0" +# Copy `noxfile_config.py` to your directory and modify it instead. # `TEST_CONFIG` dict is a configuration hook that allows users to # modify the test configurations. The values here should be in sync @@ -50,7 +51,10 @@ # to use your own Cloud project. 'gcloud_project_env': 'GOOGLE_CLOUD_PROJECT', # 'gcloud_project_env': 'BUILD_SPECIFIC_GCLOUD_PROJECT', - + # If you need to use a specific version of pip, + # change pip_version_override to the string representation + # of the version number, for example, "20.2.4" + "pip_version_override": None, # A dictionary you want to inject into your test. Don't put any # secrets here. These values will override predefined values. 'envs': {}, @@ -156,7 +160,7 @@ def lint(session: nox.sessions.Session) -> None: @nox.session def blacken(session: nox.sessions.Session) -> None: - session.install("black") + session.install(BLACK_VERSION) python_files = [path for path in os.listdir(".") if path.endswith(".py")] session.run("black", *python_files) @@ -170,6 +174,9 @@ def blacken(session: nox.sessions.Session) -> None: def _session_tests(session: nox.sessions.Session, post_install: Callable = None) -> None: + if TEST_CONFIG["pip_version_override"]: + pip_version = TEST_CONFIG["pip_version_override"] + session.install(f"pip=={pip_version}") """Runs py.test for a particular project.""" if os.path.exists("requirements.txt"): if os.path.exists("constraints.txt"): diff --git a/synth.metadata b/synth.metadata index 02da2833c..7938695bf 100644 --- a/synth.metadata +++ b/synth.metadata @@ -4,7 +4,7 @@ "git": { "name": ".", "remote": "https://github.com/googleapis/python-pubsub.git", - "sha": "b8352f91c63e0cb7d64c4d0e557651248cd301b5" + "sha": "f1ee3463a89a1a994af0cc522d25bfd1c4412824" } }, { @@ -14,27 +14,6 @@ "sha": "6598bb829c9e9a534be674649ffd1b4671a821f9", "internalRef": "364449524" } - }, - { - "git": { - "name": "synthtool", - "remote": "https://github.com/googleapis/synthtool.git", - "sha": "043cc620d6a6111816d9e09f2a97208565fde958" - } - }, - { - "git": { - "name": "synthtool", - "remote": "https://github.com/googleapis/synthtool.git", - "sha": "043cc620d6a6111816d9e09f2a97208565fde958" - } - }, - { - "git": { - "name": "synthtool", - "remote": "https://github.com/googleapis/synthtool.git", - "sha": "043cc620d6a6111816d9e09f2a97208565fde958" - } } ], "destinations": [ @@ -64,7 +43,6 @@ ".kokoro/continuous/common.cfg", ".kokoro/continuous/continuous.cfg", ".kokoro/docker/docs/Dockerfile", - ".kokoro/docker/docs/fetch_gpg_keys.sh", ".kokoro/docs/common.cfg", ".kokoro/docs/docs-presubmit.cfg", ".kokoro/docs/docs.cfg", @@ -94,6 +72,11 @@ ".kokoro/samples/python3.8/periodic-head.cfg", ".kokoro/samples/python3.8/periodic.cfg", ".kokoro/samples/python3.8/presubmit.cfg", + ".kokoro/samples/python3.9/common.cfg", + ".kokoro/samples/python3.9/continuous.cfg", + ".kokoro/samples/python3.9/periodic-head.cfg", + ".kokoro/samples/python3.9/periodic.cfg", + ".kokoro/samples/python3.9/presubmit.cfg", ".kokoro/test-samples-against-head.sh", ".kokoro/test-samples-impl.sh", ".kokoro/test-samples.sh", @@ -105,6 +88,7 @@ "CONTRIBUTING.rst", "LICENSE", "MANIFEST.in", + "SECURITY.md", "docs/_static/custom.css", "docs/_templates/layout.html", "docs/conf.py", From aa09a8e3363e953c00d2c7075dfba3abbf28b5c8 Mon Sep 17 00:00:00 2001 From: yoshi-automation Date: Sun, 18 Jul 2021 04:43:10 +0000 Subject: [PATCH 02/18] chore: upgrade to gapic-generator-python 0.44.0 chore: add GAPIC metadata feat: add support for self-signed JWT PiperOrigin-RevId: 370525906 Source-Author: Google APIs Source-Date: Mon Apr 26 13:12:26 2021 -0700 Source-Repo: googleapis/googleapis Source-Sha: 60e129d0672a1be2c70b41bf76aadc7ad1b1ca0f Source-Link: https://github.com/googleapis/googleapis/commit/60e129d0672a1be2c70b41bf76aadc7ad1b1ca0f --- .coveragerc | 1 - google/pubsub/__init__.py | 1 - google/pubsub_v1/__init__.py | 3 +- google/pubsub_v1/gapic_metadata.json | 361 +++++++++++++ google/pubsub_v1/services/__init__.py | 1 - .../pubsub_v1/services/publisher/__init__.py | 2 - .../services/publisher/async_client.py | 55 +- google/pubsub_v1/services/publisher/client.py | 55 +- google/pubsub_v1/services/publisher/pagers.py | 2 - .../services/publisher/transports/__init__.py | 2 - .../services/publisher/transports/base.py | 145 ++++-- .../services/publisher/transports/grpc.py | 50 +- .../publisher/transports/grpc_asyncio.py | 52 +- .../services/schema_service/__init__.py | 2 - .../services/schema_service/async_client.py | 39 +- .../services/schema_service/client.py | 38 +- .../services/schema_service/pagers.py | 2 - .../schema_service/transports/__init__.py | 2 - .../schema_service/transports/base.py | 131 +++-- .../schema_service/transports/grpc.py | 38 +- .../schema_service/transports/grpc_asyncio.py | 40 +- .../pubsub_v1/services/subscriber/__init__.py | 2 - .../services/subscriber/async_client.py | 89 ++-- .../pubsub_v1/services/subscriber/client.py | 93 ++-- .../pubsub_v1/services/subscriber/pagers.py | 2 - .../subscriber/transports/__init__.py | 2 - .../services/subscriber/transports/base.py | 176 ++++--- .../services/subscriber/transports/grpc.py | 78 ++- .../subscriber/transports/grpc_asyncio.py | 80 ++- google/pubsub_v1/types/__init__.py | 2 - google/pubsub_v1/types/pubsub.py | 261 +++------- google/pubsub_v1/types/schema.py | 56 +- scripts/fixup_pubsub_v1_keywords.py | 68 ++- synth.metadata | 8 +- tests/__init__.py | 15 + tests/unit/__init__.py | 15 + tests/unit/gapic/__init__.py | 15 + tests/unit/gapic/pubsub_v1/__init__.py | 1 - tests/unit/gapic/pubsub_v1/test_publisher.py | 367 ++++++++----- .../gapic/pubsub_v1/test_schema_service.py | 329 ++++++++---- tests/unit/gapic/pubsub_v1/test_subscriber.py | 492 +++++++++--------- 41 files changed, 1896 insertions(+), 1277 deletions(-) create mode 100644 google/pubsub_v1/gapic_metadata.json create mode 100644 tests/__init__.py create mode 100644 tests/unit/gapic/__init__.py diff --git a/.coveragerc b/.coveragerc index a48e62f2e..96190b454 100644 --- a/.coveragerc +++ b/.coveragerc @@ -2,7 +2,6 @@ branch = True [report] -fail_under = 100 show_missing = True omit = google/cloud/__init__.py diff --git a/google/pubsub/__init__.py b/google/pubsub/__init__.py index b146fadef..5529b3ca6 100644 --- a/google/pubsub/__init__.py +++ b/google/pubsub/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); diff --git a/google/pubsub_v1/__init__.py b/google/pubsub_v1/__init__.py index d5a1de488..33fca22fc 100644 --- a/google/pubsub_v1/__init__.py +++ b/google/pubsub_v1/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -18,6 +17,7 @@ from .services.publisher import PublisherClient from .services.schema_service import SchemaServiceClient from .services.subscriber import SubscriberClient + from .types.pubsub import AcknowledgeRequest from .types.pubsub import CreateSnapshotRequest from .types.pubsub import DeadLetterPolicy @@ -75,7 +75,6 @@ from .types.schema import ValidateSchemaRequest from .types.schema import ValidateSchemaResponse - __all__ = ( "AcknowledgeRequest", "CreateSchemaRequest", diff --git a/google/pubsub_v1/gapic_metadata.json b/google/pubsub_v1/gapic_metadata.json new file mode 100644 index 000000000..4c5b86bd1 --- /dev/null +++ b/google/pubsub_v1/gapic_metadata.json @@ -0,0 +1,361 @@ + { + "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/google/pubsub_v1/services/__init__.py b/google/pubsub_v1/services/__init__.py index 42ffdf2bc..4de65971c 100644 --- a/google/pubsub_v1/services/__init__.py +++ b/google/pubsub_v1/services/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); diff --git a/google/pubsub_v1/services/publisher/__init__.py b/google/pubsub_v1/services/publisher/__init__.py index 970a1a3b4..98e50425d 100644 --- a/google/pubsub_v1/services/publisher/__init__.py +++ b/google/pubsub_v1/services/publisher/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from .client import PublisherClient from .async_client import PublisherAsyncClient diff --git a/google/pubsub_v1/services/publisher/async_client.py b/google/pubsub_v1/services/publisher/async_client.py index 056ba288d..9311b05e4 100644 --- a/google/pubsub_v1/services/publisher/async_client.py +++ b/google/pubsub_v1/services/publisher/async_client.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict import functools import re @@ -34,7 +32,6 @@ from google.pubsub_v1.services.publisher import pagers from google.pubsub_v1.types import pubsub from google.pubsub_v1.types import TimeoutType - from .transports.base import PublisherTransport, DEFAULT_CLIENT_INFO from .transports.grpc_asyncio import PublisherGrpcAsyncIOTransport from .client import PublisherClient @@ -56,25 +53,20 @@ class PublisherAsyncClient: 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 @@ -165,7 +157,6 @@ def __init__( google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport creation failed for any reason. """ - self._client = PublisherClient( credentials=credentials, transport=transport, @@ -188,7 +179,8 @@ async def create_topic( Args: request (:class:`google.pubsub_v1.types.Topic`): - The request object. A topic resource. + 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}`` @@ -202,7 +194,6 @@ async def create_topic( 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 (TimeoutType): @@ -228,7 +219,6 @@ async def create_topic( # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -272,8 +262,8 @@ async def update_topic( Args: request (:class:`google.pubsub_v1.types.UpdateTopicRequest`): - The request object. Request for the UpdateTopic method. - + The request object. + Request for the UpdateTopic method. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (TimeoutType): @@ -286,7 +276,6 @@ async def update_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, @@ -333,7 +322,8 @@ async def publish( Args: request (:class:`google.pubsub_v1.types.PublishRequest`): - The request object. Request for the Publish method. + 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 @@ -347,7 +337,6 @@ async def 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 (TimeoutType): @@ -373,10 +362,8 @@ async def publish( # 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) @@ -428,7 +415,8 @@ async def get_topic( Args: request (:class:`google.pubsub_v1.types.GetTopicRequest`): - The request object. Request for the GetTopic method. + 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}``. @@ -436,7 +424,6 @@ async def get_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 (TimeoutType): @@ -462,7 +449,6 @@ async def get_topic( # If we have keyword arguments corresponding to fields on the # request, apply these. - if topic is not None: request.topic = topic @@ -510,7 +496,8 @@ async def list_topics( Args: request (:class:`google.pubsub_v1.types.ListTopicsRequest`): - The request object. Request for the `ListTopics` method. + 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}``. @@ -518,7 +505,6 @@ async def list_topics( 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 (TimeoutType): @@ -548,7 +534,6 @@ async def list_topics( # If we have keyword arguments corresponding to fields on the # request, apply these. - if project is not None: request.project = project @@ -603,7 +588,8 @@ async def list_topic_subscriptions( Args: request (:class:`google.pubsub_v1.types.ListTopicSubscriptionsRequest`): - The request object. Request for the + The request object. + Request for the `ListTopicSubscriptions` method. topic (:class:`str`): Required. The name of the topic that subscriptions are @@ -613,7 +599,6 @@ async def list_topic_subscriptions( 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 (TimeoutType): @@ -643,7 +628,6 @@ async def list_topic_subscriptions( # If we have keyword arguments corresponding to fields on the # request, apply these. - if topic is not None: request.topic = topic @@ -702,7 +686,8 @@ async def list_topic_snapshots( Args: request (:class:`google.pubsub_v1.types.ListTopicSnapshotsRequest`): - The request object. Request for the `ListTopicSnapshots` + The request object. + Request for the `ListTopicSnapshots` method. topic (:class:`str`): Required. The name of the topic that snapshots are @@ -712,7 +697,6 @@ async def list_topic_snapshots( 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 (TimeoutType): @@ -742,7 +726,6 @@ async def list_topic_snapshots( # If we have keyword arguments corresponding to fields on the # request, apply these. - if topic is not None: request.topic = topic @@ -801,7 +784,8 @@ async def delete_topic( Args: request (:class:`google.pubsub_v1.types.DeleteTopicRequest`): - The request object. Request for the `DeleteTopic` + The request object. + Request for the `DeleteTopic` method. topic (:class:`str`): Required. Name of the topic to delete. Format is @@ -810,7 +794,6 @@ async def delete_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 (TimeoutType): @@ -832,7 +815,6 @@ async def delete_topic( # If we have keyword arguments corresponding to fields on the # request, apply these. - if topic is not None: request.topic = topic @@ -878,9 +860,9 @@ async def detach_subscription( Args: request (:class:`google.pubsub_v1.types.DetachSubscriptionRequest`): - The request object. Request for the DetachSubscription + The request object. + Request for the DetachSubscription method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (TimeoutType): @@ -895,7 +877,6 @@ async def detach_subscription( """ # Create or coerce a protobuf request object. - request = pubsub.DetachSubscriptionRequest(request) # Wrap the RPC method; this adds retry and timeout information, diff --git a/google/pubsub_v1/services/publisher/client.py b/google/pubsub_v1/services/publisher/client.py index 3a3db1ebe..736f3e3ce 100644 --- a/google/pubsub_v1/services/publisher/client.py +++ b/google/pubsub_v1/services/publisher/client.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from distutils import util import functools @@ -41,7 +39,6 @@ from google.pubsub_v1.types import TimeoutType import grpc - from .transports.base import PublisherTransport, DEFAULT_CLIENT_INFO from .transports.grpc import PublisherGrpcTransport from .transports.grpc_asyncio import PublisherGrpcAsyncIOTransport @@ -413,7 +410,8 @@ def create_topic( Args: request (google.pubsub_v1.types.Topic): - The request object. A topic resource. + The request object. + A topic resource. name (str): Required. The name of the topic. It must have the format ``"projects/{project}/topics/{topic}"``. ``{topic}`` @@ -427,7 +425,6 @@ def create_topic( 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 (TimeoutType): @@ -455,10 +452,8 @@ def create_topic( # 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 @@ -492,8 +487,8 @@ def update_topic( Args: request (google.pubsub_v1.types.UpdateTopicRequest): - The request object. Request for the UpdateTopic method. - + The request object. + Request for the UpdateTopic method. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (TimeoutType): @@ -506,7 +501,6 @@ def update_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 @@ -548,7 +542,8 @@ def publish( Args: request (google.pubsub_v1.types.PublishRequest): - The request object. Request for the Publish method. + The request object. + Request for the Publish method. topic (str): Required. The messages in the request will be published on this topic. Format is @@ -562,7 +557,6 @@ def 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 (TimeoutType): @@ -590,10 +584,8 @@ def publish( # 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: @@ -629,7 +621,8 @@ def get_topic( Args: request (google.pubsub_v1.types.GetTopicRequest): - The request object. Request for the GetTopic method. + The request object. + Request for the GetTopic method. topic (str): Required. The name of the topic to get. Format is ``projects/{project}/topics/{topic}``. @@ -637,7 +630,6 @@ def get_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 (TimeoutType): @@ -665,10 +657,8 @@ def get_topic( # 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 @@ -702,7 +692,8 @@ def list_topics( Args: request (google.pubsub_v1.types.ListTopicsRequest): - The request object. Request for the `ListTopics` method. + 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}``. @@ -710,7 +701,6 @@ def list_topics( 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 (TimeoutType): @@ -742,10 +732,8 @@ def list_topics( # 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 @@ -786,7 +774,8 @@ def list_topic_subscriptions( Args: request (google.pubsub_v1.types.ListTopicSubscriptionsRequest): - The request object. Request for the + The request object. + Request for the `ListTopicSubscriptions` method. topic (str): Required. The name of the topic that subscriptions are @@ -796,7 +785,6 @@ def list_topic_subscriptions( 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 (TimeoutType): @@ -828,10 +816,8 @@ def list_topic_subscriptions( # 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 @@ -876,7 +862,8 @@ def list_topic_snapshots( Args: request (google.pubsub_v1.types.ListTopicSnapshotsRequest): - The request object. Request for the `ListTopicSnapshots` + The request object. + Request for the `ListTopicSnapshots` method. topic (str): Required. The name of the topic that snapshots are @@ -886,7 +873,6 @@ def list_topic_snapshots( 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 (TimeoutType): @@ -918,10 +904,8 @@ def list_topic_snapshots( # 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 @@ -966,7 +950,8 @@ def delete_topic( Args: request (google.pubsub_v1.types.DeleteTopicRequest): - The request object. Request for the `DeleteTopic` + The request object. + Request for the `DeleteTopic` method. topic (str): Required. Name of the topic to delete. Format is @@ -975,7 +960,6 @@ def delete_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 (TimeoutType): @@ -999,10 +983,8 @@ def delete_topic( # 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 @@ -1038,9 +1020,9 @@ def detach_subscription( Args: request (google.pubsub_v1.types.DetachSubscriptionRequest): - The request object. Request for the DetachSubscription + The request object. + Request for the DetachSubscription method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (TimeoutType): @@ -1055,7 +1037,6 @@ def detach_subscription( """ # 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 diff --git a/google/pubsub_v1/services/publisher/pagers.py b/google/pubsub_v1/services/publisher/pagers.py index e8836d410..592e3d507 100644 --- a/google/pubsub_v1/services/publisher/pagers.py +++ b/google/pubsub_v1/services/publisher/pagers.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from typing import ( Any, AsyncIterable, diff --git a/google/pubsub_v1/services/publisher/transports/__init__.py b/google/pubsub_v1/services/publisher/transports/__init__.py index 9eec7fc5d..34066edc3 100644 --- a/google/pubsub_v1/services/publisher/transports/__init__.py +++ b/google/pubsub_v1/services/publisher/transports/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from typing import Dict, Type diff --git a/google/pubsub_v1/services/publisher/transports/base.py b/google/pubsub_v1/services/publisher/transports/base.py index b1111a841..e814c9cbb 100644 --- a/google/pubsub_v1/services/publisher/transports/base.py +++ b/google/pubsub_v1/services/publisher/transports/base.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,12 +13,13 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import abc -import typing +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union +import packaging.version import pkg_resources from google import auth # type: ignore +import google.api_core # type: ignore from google.api_core import exceptions # type: ignore from google.api_core import gapic_v1 # type: ignore from google.api_core import retry as retries # type: ignore @@ -30,7 +30,6 @@ from google.protobuf import empty_pb2 as empty # type: ignore from google.pubsub_v1.types import pubsub - try: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( client_library_version=pkg_resources.get_distribution( @@ -40,6 +39,17 @@ except pkg_resources.DistributionNotFound: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() +try: + # google.auth.__version__ was added in 1.26.0 + _GOOGLE_AUTH_VERSION = auth.__version__ +except AttributeError: + try: # try pkg_resources if it is available + _GOOGLE_AUTH_VERSION = pkg_resources.get_distribution("google-auth").version + except pkg_resources.DistributionNotFound: # pragma: NO COVER + _GOOGLE_AUTH_VERSION = None + +_API_CORE_VERSION = google.api_core.__version__ + class PublisherTransport(abc.ABC): """Abstract transport class for Publisher.""" @@ -49,21 +59,24 @@ class PublisherTransport(abc.ABC): "https://www.googleapis.com/auth/pubsub", ) + DEFAULT_HOST: str = "pubsub.googleapis.com" + def __init__( self, *, - host: str = "pubsub.googleapis.com", + host: str = DEFAULT_HOST, credentials: credentials.Credentials = None, - credentials_file: typing.Optional[str] = None, - scopes: typing.Optional[typing.Sequence[str]] = AUTH_SCOPES, - quota_project_id: typing.Optional[str] = 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, **kwargs, ) -> None: """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + 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 @@ -72,7 +85,7 @@ def __init__( 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. - scope (Optional[Sequence[str]]): A list of scopes. + 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): @@ -86,6 +99,8 @@ def __init__( host += ":443" self._host = host + scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) + # Save the scopes. self._scopes = scopes or self.AUTH_SCOPES @@ -98,17 +113,62 @@ def __init__( if credentials_file is not None: credentials, _ = auth.load_credentials_from_file( - credentials_file, scopes=self._scopes, quota_project_id=quota_project_id + credentials_file, **scopes_kwargs, quota_project_id=quota_project_id ) elif credentials is None: credentials, _ = auth.default( - scopes=self._scopes, quota_project_id=quota_project_id + **scopes_kwargs, quota_project_id=quota_project_id ) # Save the credentials. self._credentials = credentials + # TODO(busunkim): These two class methods are in the base transport + # to avoid duplicating code across the transport classes. These functions + # should be deleted once the minimum required versions of google-api-core + # and google-auth are increased. + + # TODO: Remove this function once google-auth >= 1.25.0 is required + @classmethod + def _get_scopes_kwargs( + cls, host: str, scopes: Optional[Sequence[str]] + ) -> Dict[str, Optional[Sequence[str]]]: + """Returns scopes kwargs to pass to google-auth methods depending on the google-auth version""" + + scopes_kwargs = {} + + if _GOOGLE_AUTH_VERSION and ( + packaging.version.parse(_GOOGLE_AUTH_VERSION) + >= packaging.version.parse("1.25.0") + ): + scopes_kwargs = {"scopes": scopes, "default_scopes": cls.AUTH_SCOPES} + else: + scopes_kwargs = {"scopes": scopes or cls.AUTH_SCOPES} + + return scopes_kwargs + + # TODO: Remove this function once google-api-core >= 1.26.0 is required + @classmethod + def _get_self_signed_jwt_kwargs( + cls, host: str, scopes: Optional[Sequence[str]] + ) -> Dict[str, Union[Optional[Sequence[str]], str]]: + """Returns kwargs to pass to grpc_helpers.create_channel depending on the google-api-core version""" + + self_signed_jwt_kwargs: Dict[str, Union[Optional[Sequence[str]], str]] = {} + + if _API_CORE_VERSION and ( + packaging.version.parse(_API_CORE_VERSION) + >= packaging.version.parse("1.26.0") + ): + self_signed_jwt_kwargs["default_scopes"] = cls.AUTH_SCOPES + self_signed_jwt_kwargs["scopes"] = scopes + self_signed_jwt_kwargs["default_host"] = cls.DEFAULT_HOST + else: + self_signed_jwt_kwargs["scopes"] = scopes or cls.AUTH_SCOPES + + return self_signed_jwt_kwargs + def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. self._wrapped_methods = { @@ -249,57 +309,51 @@ def _prep_wrapped_messages(self, client_info): @property def create_topic( self, - ) -> typing.Callable[ - [pubsub.Topic], typing.Union[pubsub.Topic, typing.Awaitable[pubsub.Topic]] - ]: + ) -> Callable[[pubsub.Topic], Union[pubsub.Topic, Awaitable[pubsub.Topic]]]: raise NotImplementedError() @property def update_topic( self, - ) -> typing.Callable[ - [pubsub.UpdateTopicRequest], - typing.Union[pubsub.Topic, typing.Awaitable[pubsub.Topic]], + ) -> Callable[ + [pubsub.UpdateTopicRequest], Union[pubsub.Topic, Awaitable[pubsub.Topic]] ]: raise NotImplementedError() @property def publish( self, - ) -> typing.Callable[ + ) -> Callable[ [pubsub.PublishRequest], - typing.Union[pubsub.PublishResponse, typing.Awaitable[pubsub.PublishResponse]], + Union[pubsub.PublishResponse, Awaitable[pubsub.PublishResponse]], ]: raise NotImplementedError() @property def get_topic( self, - ) -> typing.Callable[ - [pubsub.GetTopicRequest], - typing.Union[pubsub.Topic, typing.Awaitable[pubsub.Topic]], + ) -> Callable[ + [pubsub.GetTopicRequest], Union[pubsub.Topic, Awaitable[pubsub.Topic]] ]: raise NotImplementedError() @property def list_topics( self, - ) -> typing.Callable[ + ) -> Callable[ [pubsub.ListTopicsRequest], - typing.Union[ - pubsub.ListTopicsResponse, typing.Awaitable[pubsub.ListTopicsResponse] - ], + Union[pubsub.ListTopicsResponse, Awaitable[pubsub.ListTopicsResponse]], ]: raise NotImplementedError() @property def list_topic_subscriptions( self, - ) -> typing.Callable[ + ) -> Callable[ [pubsub.ListTopicSubscriptionsRequest], - typing.Union[ + Union[ pubsub.ListTopicSubscriptionsResponse, - typing.Awaitable[pubsub.ListTopicSubscriptionsResponse], + Awaitable[pubsub.ListTopicSubscriptionsResponse], ], ]: raise NotImplementedError() @@ -307,11 +361,11 @@ def list_topic_subscriptions( @property def list_topic_snapshots( self, - ) -> typing.Callable[ + ) -> Callable[ [pubsub.ListTopicSnapshotsRequest], - typing.Union[ + Union[ pubsub.ListTopicSnapshotsResponse, - typing.Awaitable[pubsub.ListTopicSnapshotsResponse], + Awaitable[pubsub.ListTopicSnapshotsResponse], ], ]: raise NotImplementedError() @@ -319,20 +373,19 @@ def list_topic_snapshots( @property def delete_topic( self, - ) -> typing.Callable[ - [pubsub.DeleteTopicRequest], - typing.Union[empty.Empty, typing.Awaitable[empty.Empty]], + ) -> Callable[ + [pubsub.DeleteTopicRequest], Union[empty.Empty, Awaitable[empty.Empty]] ]: raise NotImplementedError() @property def detach_subscription( self, - ) -> typing.Callable[ + ) -> Callable[ [pubsub.DetachSubscriptionRequest], - typing.Union[ + Union[ pubsub.DetachSubscriptionResponse, - typing.Awaitable[pubsub.DetachSubscriptionResponse], + Awaitable[pubsub.DetachSubscriptionResponse], ], ]: raise NotImplementedError() @@ -340,29 +393,29 @@ def detach_subscription( @property def set_iam_policy( self, - ) -> typing.Callable[ + ) -> Callable[ [iam_policy.SetIamPolicyRequest], - typing.Union[policy.Policy, typing.Awaitable[policy.Policy]], + Union[policy.Policy, Awaitable[policy.Policy]], ]: raise NotImplementedError() @property def get_iam_policy( self, - ) -> typing.Callable[ + ) -> Callable[ [iam_policy.GetIamPolicyRequest], - typing.Union[policy.Policy, typing.Awaitable[policy.Policy]], + Union[policy.Policy, Awaitable[policy.Policy]], ]: raise NotImplementedError() @property def test_iam_permissions( self, - ) -> typing.Callable[ + ) -> Callable[ [iam_policy.TestIamPermissionsRequest], - typing.Union[ + Union[ iam_policy.TestIamPermissionsResponse, - typing.Awaitable[iam_policy.TestIamPermissionsResponse], + Awaitable[iam_policy.TestIamPermissionsResponse], ], ]: raise NotImplementedError() diff --git a/google/pubsub_v1/services/publisher/transports/grpc.py b/google/pubsub_v1/services/publisher/transports/grpc.py index 0b9ddc8e2..2e6acea4d 100644 --- a/google/pubsub_v1/services/publisher/transports/grpc.py +++ b/google/pubsub_v1/services/publisher/transports/grpc.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,9 +13,8 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple +from typing import Callable, Dict, Optional, Sequence, Tuple, Union from google.api_core import grpc_helpers # type: ignore from google.api_core import gapic_v1 # type: ignore @@ -30,7 +28,6 @@ from google.iam.v1 import policy_pb2 as policy # type: ignore from google.protobuf import empty_pb2 as empty # type: ignore from google.pubsub_v1.types import pubsub - from .base import PublisherTransport, DEFAULT_CLIENT_INFO @@ -68,7 +65,8 @@ def __init__( """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + 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 @@ -210,13 +208,15 @@ def create_channel( google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` and ``credentials_file`` are passed. """ - scopes = scopes or cls.AUTH_SCOPES + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + return grpc_helpers.create_channel( host, credentials=credentials, credentials_file=credentials_file, - scopes=scopes, quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, **kwargs, ) @@ -228,7 +228,9 @@ def grpc_channel(self) -> grpc.Channel: @property def create_topic(self) -> Callable[[pubsub.Topic], pubsub.Topic]: - r"""Return a callable for the create topic method over gRPC. + r"""Return a callable for the + create topic + method over gRPC. Creates the given topic with the given name. See the [resource name rules] @@ -254,7 +256,9 @@ def create_topic(self) -> Callable[[pubsub.Topic], pubsub.Topic]: @property def update_topic(self) -> Callable[[pubsub.UpdateTopicRequest], pubsub.Topic]: - r"""Return a callable for the update topic method over gRPC. + 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. @@ -279,7 +283,9 @@ def update_topic(self) -> Callable[[pubsub.UpdateTopicRequest], pubsub.Topic]: @property def publish(self) -> Callable[[pubsub.PublishRequest], pubsub.PublishResponse]: - r"""Return a callable for the publish method over gRPC. + 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. @@ -304,7 +310,9 @@ def publish(self) -> Callable[[pubsub.PublishRequest], pubsub.PublishResponse]: @property def get_topic(self) -> Callable[[pubsub.GetTopicRequest], pubsub.Topic]: - r"""Return a callable for the get topic method over gRPC. + r"""Return a callable for the + get topic + method over gRPC. Gets the configuration of a topic. @@ -330,7 +338,9 @@ def get_topic(self) -> Callable[[pubsub.GetTopicRequest], pubsub.Topic]: def list_topics( self, ) -> Callable[[pubsub.ListTopicsRequest], pubsub.ListTopicsResponse]: - r"""Return a callable for the list topics method over gRPC. + r"""Return a callable for the + list topics + method over gRPC. Lists matching topics. @@ -358,7 +368,9 @@ def list_topic_subscriptions( ) -> Callable[ [pubsub.ListTopicSubscriptionsRequest], pubsub.ListTopicSubscriptionsResponse ]: - r"""Return a callable for the list topic subscriptions method over gRPC. + r"""Return a callable for the + list topic subscriptions + method over gRPC. Lists the names of the attached subscriptions on this topic. @@ -387,7 +399,9 @@ def list_topic_snapshots( ) -> Callable[ [pubsub.ListTopicSnapshotsRequest], pubsub.ListTopicSnapshotsResponse ]: - r"""Return a callable for the list topic snapshots method over gRPC. + 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 @@ -416,7 +430,9 @@ def list_topic_snapshots( @property def delete_topic(self) -> Callable[[pubsub.DeleteTopicRequest], empty.Empty]: - r"""Return a callable for the delete topic method over gRPC. + 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 @@ -449,7 +465,9 @@ def detach_subscription( ) -> Callable[ [pubsub.DetachSubscriptionRequest], pubsub.DetachSubscriptionResponse ]: - r"""Return a callable for the detach subscription method over gRPC. + 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 diff --git a/google/pubsub_v1/services/publisher/transports/grpc_asyncio.py b/google/pubsub_v1/services/publisher/transports/grpc_asyncio.py index 6a3a096f0..64250b7c3 100644 --- a/google/pubsub_v1/services/publisher/transports/grpc_asyncio.py +++ b/google/pubsub_v1/services/publisher/transports/grpc_asyncio.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,15 +13,15 @@ # 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 +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union from google.api_core import gapic_v1 # type: ignore from google.api_core import grpc_helpers_async # type: ignore from google import auth # type: ignore from google.auth import credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore +import packaging.version import grpc # type: ignore from grpc.experimental import aio # type: ignore @@ -31,7 +30,6 @@ from google.iam.v1 import policy_pb2 as policy # type: ignore from google.protobuf import empty_pb2 as empty # type: ignore from google.pubsub_v1.types import pubsub - from .base import PublisherTransport, DEFAULT_CLIENT_INFO from .grpc import PublisherGrpcTransport @@ -84,13 +82,15 @@ def create_channel( Returns: aio.Channel: A gRPC AsyncIO channel object. """ - scopes = scopes or cls.AUTH_SCOPES + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + return grpc_helpers_async.create_channel( host, credentials=credentials, credentials_file=credentials_file, - scopes=scopes, quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, **kwargs, ) @@ -112,7 +112,8 @@ def __init__( """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + 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 @@ -170,7 +171,6 @@ def __init__( # 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 @@ -232,7 +232,9 @@ def grpc_channel(self) -> aio.Channel: @property def create_topic(self) -> Callable[[pubsub.Topic], Awaitable[pubsub.Topic]]: - r"""Return a callable for the create topic method over gRPC. + r"""Return a callable for the + create topic + method over gRPC. Creates the given topic with the given name. See the [resource name rules] @@ -260,7 +262,9 @@ def create_topic(self) -> Callable[[pubsub.Topic], Awaitable[pubsub.Topic]]: def update_topic( self, ) -> Callable[[pubsub.UpdateTopicRequest], Awaitable[pubsub.Topic]]: - r"""Return a callable for the update topic method over gRPC. + 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. @@ -287,7 +291,9 @@ def update_topic( def publish( self, ) -> Callable[[pubsub.PublishRequest], Awaitable[pubsub.PublishResponse]]: - r"""Return a callable for the publish method over gRPC. + 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. @@ -312,7 +318,9 @@ def publish( @property def get_topic(self) -> Callable[[pubsub.GetTopicRequest], Awaitable[pubsub.Topic]]: - r"""Return a callable for the get topic method over gRPC. + r"""Return a callable for the + get topic + method over gRPC. Gets the configuration of a topic. @@ -338,7 +346,9 @@ def get_topic(self) -> Callable[[pubsub.GetTopicRequest], Awaitable[pubsub.Topic def list_topics( self, ) -> Callable[[pubsub.ListTopicsRequest], Awaitable[pubsub.ListTopicsResponse]]: - r"""Return a callable for the list topics method over gRPC. + r"""Return a callable for the + list topics + method over gRPC. Lists matching topics. @@ -367,7 +377,9 @@ def list_topic_subscriptions( [pubsub.ListTopicSubscriptionsRequest], Awaitable[pubsub.ListTopicSubscriptionsResponse], ]: - r"""Return a callable for the list topic subscriptions method over gRPC. + r"""Return a callable for the + list topic subscriptions + method over gRPC. Lists the names of the attached subscriptions on this topic. @@ -396,7 +408,9 @@ def list_topic_snapshots( ) -> Callable[ [pubsub.ListTopicSnapshotsRequest], Awaitable[pubsub.ListTopicSnapshotsResponse] ]: - r"""Return a callable for the list topic snapshots method over gRPC. + 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 @@ -427,7 +441,9 @@ def list_topic_snapshots( def delete_topic( self, ) -> Callable[[pubsub.DeleteTopicRequest], Awaitable[empty.Empty]]: - r"""Return a callable for the delete topic method over gRPC. + 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 @@ -460,7 +476,9 @@ def detach_subscription( ) -> Callable[ [pubsub.DetachSubscriptionRequest], Awaitable[pubsub.DetachSubscriptionResponse] ]: - r"""Return a callable for the detach subscription method over gRPC. + 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 diff --git a/google/pubsub_v1/services/schema_service/__init__.py b/google/pubsub_v1/services/schema_service/__init__.py index d93cff56f..523d5b5f5 100644 --- a/google/pubsub_v1/services/schema_service/__init__.py +++ b/google/pubsub_v1/services/schema_service/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from .client import SchemaServiceClient from .async_client import SchemaServiceAsyncClient diff --git a/google/pubsub_v1/services/schema_service/async_client.py b/google/pubsub_v1/services/schema_service/async_client.py index 9aeb62990..4cfc74e81 100644 --- a/google/pubsub_v1/services/schema_service/async_client.py +++ b/google/pubsub_v1/services/schema_service/async_client.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict import functools import re @@ -33,7 +31,6 @@ 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 @@ -49,31 +46,26 @@ class SchemaServiceAsyncClient: 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 @@ -164,7 +156,6 @@ def __init__( google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport creation failed for any reason. """ - self._client = SchemaServiceClient( credentials=credentials, transport=transport, @@ -187,7 +178,8 @@ async def create_schema( Args: request (:class:`google.pubsub_v1.types.CreateSchemaRequest`): - The request object. Request for the CreateSchema method. + 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}``. @@ -216,7 +208,6 @@ async def create_schema( 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. @@ -241,7 +232,6 @@ async def create_schema( # 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: @@ -282,7 +272,8 @@ async def get_schema( Args: request (:class:`google.pubsub_v1.types.GetSchemaRequest`): - The request object. Request for the GetSchema method. + 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}``. @@ -290,7 +281,6 @@ async def get_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. @@ -315,7 +305,6 @@ async def get_schema( # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -352,7 +341,8 @@ async def list_schemas( Args: request (:class:`google.pubsub_v1.types.ListSchemasRequest`): - The request object. Request for the `ListSchemas` + The request object. + Request for the `ListSchemas` method. parent (:class:`str`): Required. The name of the project in which to list @@ -361,7 +351,6 @@ async def list_schemas( 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. @@ -390,7 +379,6 @@ async def list_schemas( # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent @@ -433,7 +421,8 @@ async def delete_schema( Args: request (:class:`google.pubsub_v1.types.DeleteSchemaRequest`): - The request object. Request for the `DeleteSchema` + The request object. + Request for the `DeleteSchema` method. name (:class:`str`): Required. Name of the schema to delete. Format is @@ -442,7 +431,6 @@ async def delete_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. @@ -463,7 +451,6 @@ async def delete_schema( # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -500,7 +487,8 @@ async def validate_schema( Args: request (:class:`google.pubsub_v1.types.ValidateSchemaRequest`): - The request object. Request for the `ValidateSchema` + The request object. + Request for the `ValidateSchema` method. parent (:class:`str`): Required. The name of the project in which to validate @@ -516,7 +504,6 @@ async def validate_schema( 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. @@ -541,7 +528,6 @@ async def validate_schema( # 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: @@ -579,9 +565,9 @@ async def validate_message( Args: request (:class:`google.pubsub_v1.types.ValidateMessageRequest`): - The request object. Request for the `ValidateMessage` + 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. @@ -593,7 +579,6 @@ async def validate_message( Response for the ValidateMessage method. """ # Create or coerce a protobuf request object. - request = schema.ValidateMessageRequest(request) # Wrap the RPC method; this adds retry and timeout information, diff --git a/google/pubsub_v1/services/schema_service/client.py b/google/pubsub_v1/services/schema_service/client.py index 5f65a0388..cb85dbd51 100644 --- a/google/pubsub_v1/services/schema_service/client.py +++ b/google/pubsub_v1/services/schema_service/client.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from distutils import util import os @@ -37,7 +35,6 @@ 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 @@ -356,7 +353,8 @@ def create_schema( Args: request (google.pubsub_v1.types.CreateSchemaRequest): - The request object. Request for the CreateSchema method. + 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}``. @@ -385,7 +383,6 @@ def create_schema( 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. @@ -412,10 +409,8 @@ def create_schema( # 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: @@ -452,7 +447,8 @@ def get_schema( Args: request (google.pubsub_v1.types.GetSchemaRequest): - The request object. Request for the GetSchema method. + The request object. + Request for the GetSchema method. name (str): Required. The name of the schema to get. Format is ``projects/{project}/schemas/{schema}``. @@ -460,7 +456,6 @@ def get_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. @@ -487,10 +482,8 @@ def get_schema( # 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 @@ -523,7 +516,8 @@ def list_schemas( Args: request (google.pubsub_v1.types.ListSchemasRequest): - The request object. Request for the `ListSchemas` + The request object. + Request for the `ListSchemas` method. parent (str): Required. The name of the project in which to list @@ -532,7 +526,6 @@ def list_schemas( 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. @@ -563,10 +556,8 @@ def list_schemas( # 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 @@ -605,7 +596,8 @@ def delete_schema( Args: request (google.pubsub_v1.types.DeleteSchemaRequest): - The request object. Request for the `DeleteSchema` + The request object. + Request for the `DeleteSchema` method. name (str): Required. Name of the schema to delete. Format is @@ -614,7 +606,6 @@ def delete_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. @@ -637,10 +628,8 @@ def delete_schema( # 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 @@ -673,7 +662,8 @@ def validate_schema( Args: request (google.pubsub_v1.types.ValidateSchemaRequest): - The request object. Request for the `ValidateSchema` + The request object. + Request for the `ValidateSchema` method. parent (str): Required. The name of the project in which to validate @@ -689,7 +679,6 @@ def validate_schema( 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. @@ -716,10 +705,8 @@ def validate_schema( # 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: @@ -753,9 +740,9 @@ def validate_message( Args: request (google.pubsub_v1.types.ValidateMessageRequest): - The request object. Request for the `ValidateMessage` + 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. @@ -767,7 +754,6 @@ def validate_message( Response for the ValidateMessage method. """ # 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 diff --git a/google/pubsub_v1/services/schema_service/pagers.py b/google/pubsub_v1/services/schema_service/pagers.py index 2712f37c6..a6bf1ccc0 100644 --- a/google/pubsub_v1/services/schema_service/pagers.py +++ b/google/pubsub_v1/services/schema_service/pagers.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from typing import ( Any, AsyncIterable, diff --git a/google/pubsub_v1/services/schema_service/transports/__init__.py b/google/pubsub_v1/services/schema_service/transports/__init__.py index 015410d3d..81ebf8d1c 100644 --- a/google/pubsub_v1/services/schema_service/transports/__init__.py +++ b/google/pubsub_v1/services/schema_service/transports/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from typing import Dict, Type diff --git a/google/pubsub_v1/services/schema_service/transports/base.py b/google/pubsub_v1/services/schema_service/transports/base.py index fec2169ae..fa897ee68 100644 --- a/google/pubsub_v1/services/schema_service/transports/base.py +++ b/google/pubsub_v1/services/schema_service/transports/base.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,12 +13,13 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import abc -import typing +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union +import packaging.version import pkg_resources from google import auth # type: ignore +import google.api_core # type: ignore from google.api_core import exceptions # type: ignore from google.api_core import gapic_v1 # type: ignore from google.api_core import retry as retries # type: ignore @@ -31,7 +31,6 @@ 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( client_library_version=pkg_resources.get_distribution( @@ -41,6 +40,17 @@ except pkg_resources.DistributionNotFound: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() +try: + # google.auth.__version__ was added in 1.26.0 + _GOOGLE_AUTH_VERSION = auth.__version__ +except AttributeError: + try: # try pkg_resources if it is available + _GOOGLE_AUTH_VERSION = pkg_resources.get_distribution("google-auth").version + except pkg_resources.DistributionNotFound: # pragma: NO COVER + _GOOGLE_AUTH_VERSION = None + +_API_CORE_VERSION = google.api_core.__version__ + class SchemaServiceTransport(abc.ABC): """Abstract transport class for SchemaService.""" @@ -50,21 +60,24 @@ class SchemaServiceTransport(abc.ABC): "https://www.googleapis.com/auth/pubsub", ) + DEFAULT_HOST: str = "pubsub.googleapis.com" + def __init__( self, *, - host: str = "pubsub.googleapis.com", + host: str = DEFAULT_HOST, credentials: credentials.Credentials = None, - credentials_file: typing.Optional[str] = None, - scopes: typing.Optional[typing.Sequence[str]] = AUTH_SCOPES, - quota_project_id: typing.Optional[str] = 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, **kwargs, ) -> None: """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + 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 @@ -73,7 +86,7 @@ def __init__( 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. - scope (Optional[Sequence[str]]): A list of scopes. + 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): @@ -87,6 +100,8 @@ def __init__( host += ":443" self._host = host + scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) + # Save the scopes. self._scopes = scopes or self.AUTH_SCOPES @@ -99,17 +114,62 @@ def __init__( if credentials_file is not None: credentials, _ = auth.load_credentials_from_file( - credentials_file, scopes=self._scopes, quota_project_id=quota_project_id + credentials_file, **scopes_kwargs, quota_project_id=quota_project_id ) elif credentials is None: credentials, _ = auth.default( - scopes=self._scopes, quota_project_id=quota_project_id + **scopes_kwargs, quota_project_id=quota_project_id ) # Save the credentials. self._credentials = credentials + # TODO(busunkim): These two class methods are in the base transport + # to avoid duplicating code across the transport classes. These functions + # should be deleted once the minimum required versions of google-api-core + # and google-auth are increased. + + # TODO: Remove this function once google-auth >= 1.25.0 is required + @classmethod + def _get_scopes_kwargs( + cls, host: str, scopes: Optional[Sequence[str]] + ) -> Dict[str, Optional[Sequence[str]]]: + """Returns scopes kwargs to pass to google-auth methods depending on the google-auth version""" + + scopes_kwargs = {} + + if _GOOGLE_AUTH_VERSION and ( + packaging.version.parse(_GOOGLE_AUTH_VERSION) + >= packaging.version.parse("1.25.0") + ): + scopes_kwargs = {"scopes": scopes, "default_scopes": cls.AUTH_SCOPES} + else: + scopes_kwargs = {"scopes": scopes or cls.AUTH_SCOPES} + + return scopes_kwargs + + # TODO: Remove this function once google-api-core >= 1.26.0 is required + @classmethod + def _get_self_signed_jwt_kwargs( + cls, host: str, scopes: Optional[Sequence[str]] + ) -> Dict[str, Union[Optional[Sequence[str]], str]]: + """Returns kwargs to pass to grpc_helpers.create_channel depending on the google-api-core version""" + + self_signed_jwt_kwargs: Dict[str, Union[Optional[Sequence[str]], str]] = {} + + if _API_CORE_VERSION and ( + packaging.version.parse(_API_CORE_VERSION) + >= packaging.version.parse("1.26.0") + ): + self_signed_jwt_kwargs["default_scopes"] = cls.AUTH_SCOPES + self_signed_jwt_kwargs["scopes"] = scopes + self_signed_jwt_kwargs["default_host"] = cls.DEFAULT_HOST + else: + self_signed_jwt_kwargs["scopes"] = scopes or cls.AUTH_SCOPES + + return self_signed_jwt_kwargs + def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. self._wrapped_methods = { @@ -136,49 +196,45 @@ def _prep_wrapped_messages(self, client_info): @property def create_schema( self, - ) -> typing.Callable[ + ) -> Callable[ [gp_schema.CreateSchemaRequest], - typing.Union[gp_schema.Schema, typing.Awaitable[gp_schema.Schema]], + Union[gp_schema.Schema, Awaitable[gp_schema.Schema]], ]: raise NotImplementedError() @property def get_schema( self, - ) -> typing.Callable[ - [schema.GetSchemaRequest], - typing.Union[schema.Schema, typing.Awaitable[schema.Schema]], + ) -> Callable[ + [schema.GetSchemaRequest], Union[schema.Schema, Awaitable[schema.Schema]] ]: raise NotImplementedError() @property def list_schemas( self, - ) -> typing.Callable[ + ) -> Callable[ [schema.ListSchemasRequest], - typing.Union[ - schema.ListSchemasResponse, typing.Awaitable[schema.ListSchemasResponse] - ], + Union[schema.ListSchemasResponse, Awaitable[schema.ListSchemasResponse]], ]: raise NotImplementedError() @property def delete_schema( self, - ) -> typing.Callable[ - [schema.DeleteSchemaRequest], - typing.Union[empty.Empty, typing.Awaitable[empty.Empty]], + ) -> Callable[ + [schema.DeleteSchemaRequest], Union[empty.Empty, Awaitable[empty.Empty]] ]: raise NotImplementedError() @property def validate_schema( self, - ) -> typing.Callable[ + ) -> Callable[ [gp_schema.ValidateSchemaRequest], - typing.Union[ + Union[ gp_schema.ValidateSchemaResponse, - typing.Awaitable[gp_schema.ValidateSchemaResponse], + Awaitable[gp_schema.ValidateSchemaResponse], ], ]: raise NotImplementedError() @@ -186,11 +242,10 @@ def validate_schema( @property def validate_message( self, - ) -> typing.Callable[ + ) -> Callable[ [schema.ValidateMessageRequest], - typing.Union[ - schema.ValidateMessageResponse, - typing.Awaitable[schema.ValidateMessageResponse], + Union[ + schema.ValidateMessageResponse, Awaitable[schema.ValidateMessageResponse] ], ]: raise NotImplementedError() @@ -198,29 +253,29 @@ def validate_message( @property def set_iam_policy( self, - ) -> typing.Callable[ + ) -> Callable[ [iam_policy.SetIamPolicyRequest], - typing.Union[policy.Policy, typing.Awaitable[policy.Policy]], + Union[policy.Policy, Awaitable[policy.Policy]], ]: raise NotImplementedError() @property def get_iam_policy( self, - ) -> typing.Callable[ + ) -> Callable[ [iam_policy.GetIamPolicyRequest], - typing.Union[policy.Policy, typing.Awaitable[policy.Policy]], + Union[policy.Policy, Awaitable[policy.Policy]], ]: raise NotImplementedError() @property def test_iam_permissions( self, - ) -> typing.Callable[ + ) -> Callable[ [iam_policy.TestIamPermissionsRequest], - typing.Union[ + Union[ iam_policy.TestIamPermissionsResponse, - typing.Awaitable[iam_policy.TestIamPermissionsResponse], + Awaitable[iam_policy.TestIamPermissionsResponse], ], ]: raise NotImplementedError() diff --git a/google/pubsub_v1/services/schema_service/transports/grpc.py b/google/pubsub_v1/services/schema_service/transports/grpc.py index ed9822e01..55967e792 100644 --- a/google/pubsub_v1/services/schema_service/transports/grpc.py +++ b/google/pubsub_v1/services/schema_service/transports/grpc.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,9 +13,8 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple +from typing import Callable, Dict, Optional, Sequence, Tuple, Union from google.api_core import grpc_helpers # type: ignore from google.api_core import gapic_v1 # type: ignore @@ -31,7 +29,6 @@ from google.protobuf import empty_pb2 as empty # 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 @@ -68,7 +65,8 @@ def __init__( """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + 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 @@ -210,13 +208,15 @@ def create_channel( google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` and ``credentials_file`` are passed. """ - scopes = scopes or cls.AUTH_SCOPES + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + return grpc_helpers.create_channel( host, credentials=credentials, credentials_file=credentials_file, - scopes=scopes, quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, **kwargs, ) @@ -230,7 +230,9 @@ def grpc_channel(self) -> grpc.Channel: def create_schema( self, ) -> Callable[[gp_schema.CreateSchemaRequest], gp_schema.Schema]: - r"""Return a callable for the create schema method over gRPC. + r"""Return a callable for the + create schema + method over gRPC. Creates a schema. @@ -254,7 +256,9 @@ def create_schema( @property def get_schema(self) -> Callable[[schema.GetSchemaRequest], schema.Schema]: - r"""Return a callable for the get schema method over gRPC. + r"""Return a callable for the + get schema + method over gRPC. Gets a schema. @@ -280,7 +284,9 @@ def get_schema(self) -> Callable[[schema.GetSchemaRequest], schema.Schema]: def list_schemas( self, ) -> Callable[[schema.ListSchemasRequest], schema.ListSchemasResponse]: - r"""Return a callable for the list schemas method over gRPC. + r"""Return a callable for the + list schemas + method over gRPC. Lists schemas in a project. @@ -304,7 +310,9 @@ def list_schemas( @property def delete_schema(self) -> Callable[[schema.DeleteSchemaRequest], empty.Empty]: - r"""Return a callable for the delete schema method over gRPC. + r"""Return a callable for the + delete schema + method over gRPC. Deletes a schema. @@ -330,7 +338,9 @@ def delete_schema(self) -> Callable[[schema.DeleteSchemaRequest], empty.Empty]: def validate_schema( self, ) -> Callable[[gp_schema.ValidateSchemaRequest], gp_schema.ValidateSchemaResponse]: - r"""Return a callable for the validate schema method over gRPC. + r"""Return a callable for the + validate schema + method over gRPC. Validates a schema. @@ -356,7 +366,9 @@ def validate_schema( def validate_message( self, ) -> Callable[[schema.ValidateMessageRequest], schema.ValidateMessageResponse]: - r"""Return a callable for the validate message method over gRPC. + r"""Return a callable for the + validate message + method over gRPC. Validates a message against a schema. diff --git a/google/pubsub_v1/services/schema_service/transports/grpc_asyncio.py b/google/pubsub_v1/services/schema_service/transports/grpc_asyncio.py index c7cb3ac63..957b402d0 100644 --- a/google/pubsub_v1/services/schema_service/transports/grpc_asyncio.py +++ b/google/pubsub_v1/services/schema_service/transports/grpc_asyncio.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,15 +13,15 @@ # 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 +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union from google.api_core import gapic_v1 # type: ignore from google.api_core import grpc_helpers_async # type: ignore from google import auth # type: ignore from google.auth import credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore +import packaging.version import grpc # type: ignore from grpc.experimental import aio # type: ignore @@ -32,7 +31,6 @@ from google.protobuf import empty_pb2 as empty # 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 @@ -84,13 +82,15 @@ def create_channel( Returns: aio.Channel: A gRPC AsyncIO channel object. """ - scopes = scopes or cls.AUTH_SCOPES + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + return grpc_helpers_async.create_channel( host, credentials=credentials, credentials_file=credentials_file, - scopes=scopes, quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, **kwargs, ) @@ -112,7 +112,8 @@ def __init__( """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + 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 @@ -170,7 +171,6 @@ def __init__( # 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 @@ -234,7 +234,9 @@ def grpc_channel(self) -> aio.Channel: def create_schema( self, ) -> Callable[[gp_schema.CreateSchemaRequest], Awaitable[gp_schema.Schema]]: - r"""Return a callable for the create schema method over gRPC. + r"""Return a callable for the + create schema + method over gRPC. Creates a schema. @@ -260,7 +262,9 @@ def create_schema( def get_schema( self, ) -> Callable[[schema.GetSchemaRequest], Awaitable[schema.Schema]]: - r"""Return a callable for the get schema method over gRPC. + r"""Return a callable for the + get schema + method over gRPC. Gets a schema. @@ -286,7 +290,9 @@ def get_schema( def list_schemas( self, ) -> Callable[[schema.ListSchemasRequest], Awaitable[schema.ListSchemasResponse]]: - r"""Return a callable for the list schemas method over gRPC. + r"""Return a callable for the + list schemas + method over gRPC. Lists schemas in a project. @@ -312,7 +318,9 @@ def list_schemas( def delete_schema( self, ) -> Callable[[schema.DeleteSchemaRequest], Awaitable[empty.Empty]]: - r"""Return a callable for the delete schema method over gRPC. + r"""Return a callable for the + delete schema + method over gRPC. Deletes a schema. @@ -340,7 +348,9 @@ def validate_schema( ) -> Callable[ [gp_schema.ValidateSchemaRequest], Awaitable[gp_schema.ValidateSchemaResponse] ]: - r"""Return a callable for the validate schema method over gRPC. + r"""Return a callable for the + validate schema + method over gRPC. Validates a schema. @@ -368,7 +378,9 @@ def validate_message( ) -> Callable[ [schema.ValidateMessageRequest], Awaitable[schema.ValidateMessageResponse] ]: - r"""Return a callable for the validate message method over gRPC. + r"""Return a callable for the + validate message + method over gRPC. Validates a message against a schema. diff --git a/google/pubsub_v1/services/subscriber/__init__.py b/google/pubsub_v1/services/subscriber/__init__.py index 361085a5e..0961d69d1 100644 --- a/google/pubsub_v1/services/subscriber/__init__.py +++ b/google/pubsub_v1/services/subscriber/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from .client import SubscriberClient from .async_client import SubscriberAsyncClient diff --git a/google/pubsub_v1/services/subscriber/async_client.py b/google/pubsub_v1/services/subscriber/async_client.py index 7dbc3c5ed..781df6d4c 100644 --- a/google/pubsub_v1/services/subscriber/async_client.py +++ b/google/pubsub_v1/services/subscriber/async_client.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict import functools import re @@ -44,7 +42,6 @@ from google.protobuf import timestamp_pb2 as timestamp # 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 @@ -68,25 +65,20 @@ class SubscriberAsyncClient: 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 @@ -177,7 +169,6 @@ def __init__( google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport creation failed for any reason. """ - self._client = SubscriberClient( credentials=credentials, transport=transport, @@ -213,7 +204,8 @@ async def create_subscription( Args: request (:class:`google.pubsub_v1.types.Subscription`): - The request object. A subscription resource. + The request object. + A subscription resource. name (:class:`str`): Required. The name of the subscription. It must have the format @@ -276,7 +268,6 @@ async def create_subscription( 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. @@ -301,7 +292,6 @@ async def create_subscription( # 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: @@ -355,7 +345,8 @@ async def get_subscription( Args: request (:class:`google.pubsub_v1.types.GetSubscriptionRequest`): - The request object. Request for the GetSubscription + The request object. + Request for the GetSubscription method. subscription (:class:`str`): Required. The name of the subscription to get. Format is @@ -364,7 +355,6 @@ async def get_subscription( 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. @@ -389,7 +379,6 @@ async def get_subscription( # If we have keyword arguments corresponding to fields on the # request, apply these. - if subscription is not None: request.subscription = subscription @@ -440,9 +429,9 @@ async def update_subscription( Args: request (:class:`google.pubsub_v1.types.UpdateSubscriptionRequest`): - The request object. Request for the UpdateSubscription + 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. @@ -454,7 +443,6 @@ async def update_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, @@ -499,7 +487,8 @@ async def list_subscriptions( Args: request (:class:`google.pubsub_v1.types.ListSubscriptionsRequest`): - The request object. Request for the `ListSubscriptions` + The request object. + Request for the `ListSubscriptions` method. project (:class:`str`): Required. The name of the project in which to list @@ -508,7 +497,6 @@ async def list_subscriptions( 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. @@ -537,7 +525,6 @@ async def list_subscriptions( # If we have keyword arguments corresponding to fields on the # request, apply these. - if project is not None: request.project = project @@ -596,7 +583,8 @@ async def delete_subscription( Args: request (:class:`google.pubsub_v1.types.DeleteSubscriptionRequest`): - The request object. Request for the DeleteSubscription + The request object. + Request for the DeleteSubscription method. subscription (:class:`str`): Required. The subscription to delete. Format is @@ -605,7 +593,6 @@ async def delete_subscription( 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. @@ -626,7 +613,6 @@ async def delete_subscription( # If we have keyword arguments corresponding to fields on the # request, apply these. - if subscription is not None: request.subscription = subscription @@ -678,7 +664,8 @@ async def modify_ack_deadline( Args: request (:class:`google.pubsub_v1.types.ModifyAckDeadlineRequest`): - The request object. Request for the ModifyAckDeadline + The request object. + Request for the ModifyAckDeadline method. subscription (:class:`str`): Required. The name of the subscription. Format is @@ -708,7 +695,6 @@ async def modify_ack_deadline( 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. @@ -729,12 +715,10 @@ async def modify_ack_deadline( # 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) @@ -787,7 +771,8 @@ async def acknowledge( Args: request (:class:`google.pubsub_v1.types.AcknowledgeRequest`): - The request object. Request for the Acknowledge method. + The request object. + Request for the Acknowledge method. subscription (:class:`str`): Required. The subscription whose message is being acknowledged. Format is @@ -804,7 +789,6 @@ async def acknowledge( 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. @@ -825,10 +809,8 @@ async def acknowledge( # 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) @@ -877,7 +859,8 @@ async def pull( Args: request (:class:`google.pubsub_v1.types.PullRequest`): - The request object. Request for the `Pull` method. + The request object. + Request for the `Pull` method. subscription (:class:`str`): Required. The subscription from which messages should be pulled. Format is @@ -910,7 +893,6 @@ async def pull( 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. @@ -935,7 +917,6 @@ async def pull( # 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: @@ -1001,7 +982,8 @@ def streaming_pull( Args: requests (AsyncIterator[`google.pubsub_v1.types.StreamingPullRequest`]): - The request object AsyncIterator. Request for the `StreamingPull` + 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 @@ -1066,7 +1048,8 @@ async def modify_push_config( Args: request (:class:`google.pubsub_v1.types.ModifyPushConfigRequest`): - The request object. Request for the ModifyPushConfig + The request object. + Request for the ModifyPushConfig method. subscription (:class:`str`): Required. The name of the subscription. Format is @@ -1087,7 +1070,6 @@ async def modify_push_config( 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. @@ -1108,7 +1090,6 @@ async def modify_push_config( # 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: @@ -1161,7 +1142,8 @@ async def get_snapshot( Args: request (:class:`google.pubsub_v1.types.GetSnapshotRequest`): - The request object. Request for the GetSnapshot method. + 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}``. @@ -1169,7 +1151,6 @@ async def get_snapshot( 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. @@ -1200,7 +1181,6 @@ async def get_snapshot( # If we have keyword arguments corresponding to fields on the # request, apply these. - if snapshot is not None: request.snapshot = snapshot @@ -1252,7 +1232,8 @@ async def list_snapshots( Args: request (:class:`google.pubsub_v1.types.ListSnapshotsRequest`): - The request object. Request for the `ListSnapshots` + The request object. + Request for the `ListSnapshots` method. project (:class:`str`): Required. The name of the project in which to list @@ -1261,7 +1242,6 @@ async def list_snapshots( 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. @@ -1290,7 +1270,6 @@ async def list_snapshots( # If we have keyword arguments corresponding to fields on the # request, apply these. - if project is not None: request.project = project @@ -1363,7 +1342,8 @@ async def create_snapshot( Args: request (:class:`google.pubsub_v1.types.CreateSnapshotRequest`): - The request object. Request for the `CreateSnapshot` + The request object. + Request for the `CreateSnapshot` method. name (:class:`str`): Required. User-provided name for this snapshot. If the @@ -1392,7 +1372,6 @@ async def create_snapshot( 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. @@ -1423,7 +1402,6 @@ async def create_snapshot( # 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: @@ -1474,9 +1452,9 @@ async def update_snapshot( Args: request (:class:`google.pubsub_v1.types.UpdateSnapshotRequest`): - The request object. Request for the UpdateSnapshot + 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. @@ -1494,7 +1472,6 @@ async def update_snapshot( """ # Create or coerce a protobuf request object. - request = pubsub.UpdateSnapshotRequest(request) # Wrap the RPC method; this adds retry and timeout information, @@ -1548,7 +1525,8 @@ async def delete_snapshot( Args: request (:class:`google.pubsub_v1.types.DeleteSnapshotRequest`): - The request object. Request for the `DeleteSnapshot` + The request object. + Request for the `DeleteSnapshot` method. snapshot (:class:`str`): Required. The name of the snapshot to delete. Format is @@ -1557,7 +1535,6 @@ async def delete_snapshot( 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. @@ -1578,7 +1555,6 @@ async def delete_snapshot( # If we have keyword arguments corresponding to fields on the # request, apply these. - if snapshot is not None: request.snapshot = snapshot @@ -1628,8 +1604,8 @@ async def seek( Args: request (:class:`google.pubsub_v1.types.SeekRequest`): - The request object. Request for the `Seek` method. - + 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. @@ -1641,7 +1617,6 @@ async def seek( 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, diff --git a/google/pubsub_v1/services/subscriber/client.py b/google/pubsub_v1/services/subscriber/client.py index e2fbde711..b9c988159 100644 --- a/google/pubsub_v1/services/subscriber/client.py +++ b/google/pubsub_v1/services/subscriber/client.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from distutils import util import functools @@ -52,7 +50,6 @@ from google.pubsub_v1.types import pubsub import grpc - from .transports.base import SubscriberTransport, DEFAULT_CLIENT_INFO from .transports.grpc import SubscriberGrpcTransport from .transports.grpc_asyncio import SubscriberGrpcAsyncIOTransport @@ -439,7 +436,8 @@ def create_subscription( Args: request (google.pubsub_v1.types.Subscription): - The request object. A subscription resource. + The request object. + A subscription resource. name (str): Required. The name of the subscription. It must have the format @@ -502,7 +500,6 @@ def create_subscription( 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. @@ -529,10 +526,8 @@ def create_subscription( # 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: @@ -572,7 +567,8 @@ def get_subscription( Args: request (google.pubsub_v1.types.GetSubscriptionRequest): - The request object. Request for the GetSubscription + The request object. + Request for the GetSubscription method. subscription (str): Required. The name of the subscription to get. Format is @@ -581,7 +577,6 @@ def get_subscription( 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. @@ -608,10 +603,8 @@ def get_subscription( # 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 @@ -648,9 +641,9 @@ def update_subscription( Args: request (google.pubsub_v1.types.UpdateSubscriptionRequest): - The request object. Request for the UpdateSubscription + 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. @@ -662,7 +655,6 @@ def update_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 @@ -702,7 +694,8 @@ def list_subscriptions( Args: request (google.pubsub_v1.types.ListSubscriptionsRequest): - The request object. Request for the `ListSubscriptions` + The request object. + Request for the `ListSubscriptions` method. project (str): Required. The name of the project in which to list @@ -711,7 +704,6 @@ def list_subscriptions( 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. @@ -742,10 +734,8 @@ def list_subscriptions( # 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 @@ -790,7 +780,8 @@ def delete_subscription( Args: request (google.pubsub_v1.types.DeleteSubscriptionRequest): - The request object. Request for the DeleteSubscription + The request object. + Request for the DeleteSubscription method. subscription (str): Required. The subscription to delete. Format is @@ -799,7 +790,6 @@ def delete_subscription( 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. @@ -822,10 +812,8 @@ def delete_subscription( # 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 @@ -867,7 +855,8 @@ def modify_ack_deadline( Args: request (google.pubsub_v1.types.ModifyAckDeadlineRequest): - The request object. Request for the ModifyAckDeadline + The request object. + Request for the ModifyAckDeadline method. subscription (str): Required. The name of the subscription. Format is @@ -897,7 +886,6 @@ def modify_ack_deadline( 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. @@ -920,10 +908,8 @@ def modify_ack_deadline( # 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: @@ -970,7 +956,8 @@ def acknowledge( Args: request (google.pubsub_v1.types.AcknowledgeRequest): - The request object. Request for the Acknowledge method. + The request object. + Request for the Acknowledge method. subscription (str): Required. The subscription whose message is being acknowledged. Format is @@ -987,7 +974,6 @@ def acknowledge( 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. @@ -1010,10 +996,8 @@ def acknowledge( # 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: @@ -1054,7 +1038,8 @@ def pull( Args: request (google.pubsub_v1.types.PullRequest): - The request object. Request for the `Pull` method. + The request object. + Request for the `Pull` method. subscription (str): Required. The subscription from which messages should be pulled. Format is @@ -1087,7 +1072,6 @@ def pull( 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. @@ -1114,10 +1098,8 @@ def pull( # 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: @@ -1169,7 +1151,8 @@ def streaming_pull( Args: requests (Iterator[google.pubsub_v1.types.StreamingPullRequest]): - The request object iterator. Request for the `StreamingPull` + 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 @@ -1223,7 +1206,8 @@ def modify_push_config( Args: request (google.pubsub_v1.types.ModifyPushConfigRequest): - The request object. Request for the ModifyPushConfig + The request object. + Request for the ModifyPushConfig method. subscription (str): Required. The name of the subscription. Format is @@ -1244,7 +1228,6 @@ def modify_push_config( 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. @@ -1267,10 +1250,8 @@ def modify_push_config( # 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: @@ -1313,7 +1294,8 @@ def get_snapshot( Args: request (google.pubsub_v1.types.GetSnapshotRequest): - The request object. Request for the GetSnapshot method. + The request object. + Request for the GetSnapshot method. snapshot (str): Required. The name of the snapshot to get. Format is ``projects/{project}/snapshots/{snap}``. @@ -1321,7 +1303,6 @@ def get_snapshot( 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. @@ -1354,10 +1335,8 @@ def get_snapshot( # 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 @@ -1395,7 +1374,8 @@ def list_snapshots( Args: request (google.pubsub_v1.types.ListSnapshotsRequest): - The request object. Request for the `ListSnapshots` + The request object. + Request for the `ListSnapshots` method. project (str): Required. The name of the project in which to list @@ -1404,7 +1384,6 @@ def list_snapshots( 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. @@ -1435,10 +1414,8 @@ def list_snapshots( # 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 @@ -1497,7 +1474,8 @@ def create_snapshot( Args: request (google.pubsub_v1.types.CreateSnapshotRequest): - The request object. Request for the `CreateSnapshot` + The request object. + Request for the `CreateSnapshot` method. name (str): Required. User-provided name for this snapshot. If the @@ -1526,7 +1504,6 @@ def create_snapshot( 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. @@ -1559,10 +1536,8 @@ def create_snapshot( # 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: @@ -1603,9 +1578,9 @@ def update_snapshot( Args: request (google.pubsub_v1.types.UpdateSnapshotRequest): - The request object. Request for the UpdateSnapshot + 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. @@ -1623,7 +1598,6 @@ def update_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 @@ -1672,7 +1646,8 @@ def delete_snapshot( Args: request (google.pubsub_v1.types.DeleteSnapshotRequest): - The request object. Request for the `DeleteSnapshot` + The request object. + Request for the `DeleteSnapshot` method. snapshot (str): Required. The name of the snapshot to delete. Format is @@ -1681,7 +1656,6 @@ def delete_snapshot( 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. @@ -1704,10 +1678,8 @@ def delete_snapshot( # 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 @@ -1747,8 +1719,8 @@ def seek( Args: request (google.pubsub_v1.types.SeekRequest): - The request object. Request for the `Seek` method. - + 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. @@ -1760,7 +1732,6 @@ def seek( 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 diff --git a/google/pubsub_v1/services/subscriber/pagers.py b/google/pubsub_v1/services/subscriber/pagers.py index b7ec9f6e3..3e0de8ddc 100644 --- a/google/pubsub_v1/services/subscriber/pagers.py +++ b/google/pubsub_v1/services/subscriber/pagers.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from typing import ( Any, AsyncIterable, diff --git a/google/pubsub_v1/services/subscriber/transports/__init__.py b/google/pubsub_v1/services/subscriber/transports/__init__.py index 0246cfeca..023406c8f 100644 --- a/google/pubsub_v1/services/subscriber/transports/__init__.py +++ b/google/pubsub_v1/services/subscriber/transports/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from typing import Dict, Type diff --git a/google/pubsub_v1/services/subscriber/transports/base.py b/google/pubsub_v1/services/subscriber/transports/base.py index b8a1b97b3..d93d08e30 100644 --- a/google/pubsub_v1/services/subscriber/transports/base.py +++ b/google/pubsub_v1/services/subscriber/transports/base.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,12 +13,13 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import abc -import typing +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union +import packaging.version import pkg_resources from google import auth # type: ignore +import google.api_core # type: ignore from google.api_core import exceptions # type: ignore from google.api_core import gapic_v1 # type: ignore from google.api_core import retry as retries # type: ignore @@ -30,7 +30,6 @@ from google.protobuf import empty_pb2 as empty # type: ignore from google.pubsub_v1.types import pubsub - try: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( client_library_version=pkg_resources.get_distribution( @@ -40,6 +39,17 @@ except pkg_resources.DistributionNotFound: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() +try: + # google.auth.__version__ was added in 1.26.0 + _GOOGLE_AUTH_VERSION = auth.__version__ +except AttributeError: + try: # try pkg_resources if it is available + _GOOGLE_AUTH_VERSION = pkg_resources.get_distribution("google-auth").version + except pkg_resources.DistributionNotFound: # pragma: NO COVER + _GOOGLE_AUTH_VERSION = None + +_API_CORE_VERSION = google.api_core.__version__ + class SubscriberTransport(abc.ABC): """Abstract transport class for Subscriber.""" @@ -49,21 +59,24 @@ class SubscriberTransport(abc.ABC): "https://www.googleapis.com/auth/pubsub", ) + DEFAULT_HOST: str = "pubsub.googleapis.com" + def __init__( self, *, - host: str = "pubsub.googleapis.com", + host: str = DEFAULT_HOST, credentials: credentials.Credentials = None, - credentials_file: typing.Optional[str] = None, - scopes: typing.Optional[typing.Sequence[str]] = AUTH_SCOPES, - quota_project_id: typing.Optional[str] = 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, **kwargs, ) -> None: """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + 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 @@ -72,7 +85,7 @@ def __init__( 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. - scope (Optional[Sequence[str]]): A list of scopes. + 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): @@ -86,6 +99,8 @@ def __init__( host += ":443" self._host = host + scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) + # Save the scopes. self._scopes = scopes or self.AUTH_SCOPES @@ -98,17 +113,62 @@ def __init__( if credentials_file is not None: credentials, _ = auth.load_credentials_from_file( - credentials_file, scopes=self._scopes, quota_project_id=quota_project_id + credentials_file, **scopes_kwargs, quota_project_id=quota_project_id ) elif credentials is None: credentials, _ = auth.default( - scopes=self._scopes, quota_project_id=quota_project_id + **scopes_kwargs, quota_project_id=quota_project_id ) # Save the credentials. self._credentials = credentials + # TODO(busunkim): These two class methods are in the base transport + # to avoid duplicating code across the transport classes. These functions + # should be deleted once the minimum required versions of google-api-core + # and google-auth are increased. + + # TODO: Remove this function once google-auth >= 1.25.0 is required + @classmethod + def _get_scopes_kwargs( + cls, host: str, scopes: Optional[Sequence[str]] + ) -> Dict[str, Optional[Sequence[str]]]: + """Returns scopes kwargs to pass to google-auth methods depending on the google-auth version""" + + scopes_kwargs = {} + + if _GOOGLE_AUTH_VERSION and ( + packaging.version.parse(_GOOGLE_AUTH_VERSION) + >= packaging.version.parse("1.25.0") + ): + scopes_kwargs = {"scopes": scopes, "default_scopes": cls.AUTH_SCOPES} + else: + scopes_kwargs = {"scopes": scopes or cls.AUTH_SCOPES} + + return scopes_kwargs + + # TODO: Remove this function once google-api-core >= 1.26.0 is required + @classmethod + def _get_self_signed_jwt_kwargs( + cls, host: str, scopes: Optional[Sequence[str]] + ) -> Dict[str, Union[Optional[Sequence[str]], str]]: + """Returns kwargs to pass to grpc_helpers.create_channel depending on the google-api-core version""" + + self_signed_jwt_kwargs: Dict[str, Union[Optional[Sequence[str]], str]] = {} + + if _API_CORE_VERSION and ( + packaging.version.parse(_API_CORE_VERSION) + >= packaging.version.parse("1.26.0") + ): + self_signed_jwt_kwargs["default_scopes"] = cls.AUTH_SCOPES + self_signed_jwt_kwargs["scopes"] = scopes + self_signed_jwt_kwargs["default_host"] = cls.DEFAULT_HOST + else: + self_signed_jwt_kwargs["scopes"] = scopes or cls.AUTH_SCOPES + + return self_signed_jwt_kwargs + def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. self._wrapped_methods = { @@ -343,38 +403,38 @@ def _prep_wrapped_messages(self, client_info): @property def create_subscription( self, - ) -> typing.Callable[ + ) -> Callable[ [pubsub.Subscription], - typing.Union[pubsub.Subscription, typing.Awaitable[pubsub.Subscription]], + Union[pubsub.Subscription, Awaitable[pubsub.Subscription]], ]: raise NotImplementedError() @property def get_subscription( self, - ) -> typing.Callable[ + ) -> Callable[ [pubsub.GetSubscriptionRequest], - typing.Union[pubsub.Subscription, typing.Awaitable[pubsub.Subscription]], + Union[pubsub.Subscription, Awaitable[pubsub.Subscription]], ]: raise NotImplementedError() @property def update_subscription( self, - ) -> typing.Callable[ + ) -> Callable[ [pubsub.UpdateSubscriptionRequest], - typing.Union[pubsub.Subscription, typing.Awaitable[pubsub.Subscription]], + Union[pubsub.Subscription, Awaitable[pubsub.Subscription]], ]: raise NotImplementedError() @property def list_subscriptions( self, - ) -> typing.Callable[ + ) -> Callable[ [pubsub.ListSubscriptionsRequest], - typing.Union[ + Union[ pubsub.ListSubscriptionsResponse, - typing.Awaitable[pubsub.ListSubscriptionsResponse], + Awaitable[pubsub.ListSubscriptionsResponse], ], ]: raise NotImplementedError() @@ -382,141 +442,129 @@ def list_subscriptions( @property def delete_subscription( self, - ) -> typing.Callable[ - [pubsub.DeleteSubscriptionRequest], - typing.Union[empty.Empty, typing.Awaitable[empty.Empty]], + ) -> Callable[ + [pubsub.DeleteSubscriptionRequest], Union[empty.Empty, Awaitable[empty.Empty]] ]: raise NotImplementedError() @property def modify_ack_deadline( self, - ) -> typing.Callable[ - [pubsub.ModifyAckDeadlineRequest], - typing.Union[empty.Empty, typing.Awaitable[empty.Empty]], + ) -> Callable[ + [pubsub.ModifyAckDeadlineRequest], Union[empty.Empty, Awaitable[empty.Empty]] ]: raise NotImplementedError() @property def acknowledge( self, - ) -> typing.Callable[ - [pubsub.AcknowledgeRequest], - typing.Union[empty.Empty, typing.Awaitable[empty.Empty]], + ) -> Callable[ + [pubsub.AcknowledgeRequest], Union[empty.Empty, Awaitable[empty.Empty]] ]: raise NotImplementedError() @property def pull( self, - ) -> typing.Callable[ - [pubsub.PullRequest], - typing.Union[pubsub.PullResponse, typing.Awaitable[pubsub.PullResponse]], + ) -> Callable[ + [pubsub.PullRequest], Union[pubsub.PullResponse, Awaitable[pubsub.PullResponse]] ]: raise NotImplementedError() @property def streaming_pull( self, - ) -> typing.Callable[ + ) -> Callable[ [pubsub.StreamingPullRequest], - typing.Union[ - pubsub.StreamingPullResponse, typing.Awaitable[pubsub.StreamingPullResponse] - ], + Union[pubsub.StreamingPullResponse, Awaitable[pubsub.StreamingPullResponse]], ]: raise NotImplementedError() @property def modify_push_config( self, - ) -> typing.Callable[ - [pubsub.ModifyPushConfigRequest], - typing.Union[empty.Empty, typing.Awaitable[empty.Empty]], + ) -> Callable[ + [pubsub.ModifyPushConfigRequest], Union[empty.Empty, Awaitable[empty.Empty]] ]: raise NotImplementedError() @property def get_snapshot( self, - ) -> typing.Callable[ - [pubsub.GetSnapshotRequest], - typing.Union[pubsub.Snapshot, typing.Awaitable[pubsub.Snapshot]], + ) -> Callable[ + [pubsub.GetSnapshotRequest], Union[pubsub.Snapshot, Awaitable[pubsub.Snapshot]] ]: raise NotImplementedError() @property def list_snapshots( self, - ) -> typing.Callable[ + ) -> Callable[ [pubsub.ListSnapshotsRequest], - typing.Union[ - pubsub.ListSnapshotsResponse, typing.Awaitable[pubsub.ListSnapshotsResponse] - ], + Union[pubsub.ListSnapshotsResponse, Awaitable[pubsub.ListSnapshotsResponse]], ]: raise NotImplementedError() @property def create_snapshot( self, - ) -> typing.Callable[ + ) -> Callable[ [pubsub.CreateSnapshotRequest], - typing.Union[pubsub.Snapshot, typing.Awaitable[pubsub.Snapshot]], + Union[pubsub.Snapshot, Awaitable[pubsub.Snapshot]], ]: raise NotImplementedError() @property def update_snapshot( self, - ) -> typing.Callable[ + ) -> Callable[ [pubsub.UpdateSnapshotRequest], - typing.Union[pubsub.Snapshot, typing.Awaitable[pubsub.Snapshot]], + Union[pubsub.Snapshot, Awaitable[pubsub.Snapshot]], ]: raise NotImplementedError() @property def delete_snapshot( self, - ) -> typing.Callable[ - [pubsub.DeleteSnapshotRequest], - typing.Union[empty.Empty, typing.Awaitable[empty.Empty]], + ) -> Callable[ + [pubsub.DeleteSnapshotRequest], Union[empty.Empty, Awaitable[empty.Empty]] ]: raise NotImplementedError() @property def seek( self, - ) -> typing.Callable[ - [pubsub.SeekRequest], - typing.Union[pubsub.SeekResponse, typing.Awaitable[pubsub.SeekResponse]], + ) -> Callable[ + [pubsub.SeekRequest], Union[pubsub.SeekResponse, Awaitable[pubsub.SeekResponse]] ]: raise NotImplementedError() @property def set_iam_policy( self, - ) -> typing.Callable[ + ) -> Callable[ [iam_policy.SetIamPolicyRequest], - typing.Union[policy.Policy, typing.Awaitable[policy.Policy]], + Union[policy.Policy, Awaitable[policy.Policy]], ]: raise NotImplementedError() @property def get_iam_policy( self, - ) -> typing.Callable[ + ) -> Callable[ [iam_policy.GetIamPolicyRequest], - typing.Union[policy.Policy, typing.Awaitable[policy.Policy]], + Union[policy.Policy, Awaitable[policy.Policy]], ]: raise NotImplementedError() @property def test_iam_permissions( self, - ) -> typing.Callable[ + ) -> Callable[ [iam_policy.TestIamPermissionsRequest], - typing.Union[ + Union[ iam_policy.TestIamPermissionsResponse, - typing.Awaitable[iam_policy.TestIamPermissionsResponse], + Awaitable[iam_policy.TestIamPermissionsResponse], ], ]: raise NotImplementedError() diff --git a/google/pubsub_v1/services/subscriber/transports/grpc.py b/google/pubsub_v1/services/subscriber/transports/grpc.py index b3f26f1f0..adb7f9b7a 100644 --- a/google/pubsub_v1/services/subscriber/transports/grpc.py +++ b/google/pubsub_v1/services/subscriber/transports/grpc.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,9 +13,8 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple +from typing import Callable, Dict, Optional, Sequence, Tuple, Union from google.api_core import grpc_helpers # type: ignore from google.api_core import gapic_v1 # type: ignore @@ -30,7 +28,6 @@ from google.iam.v1 import policy_pb2 as policy # type: ignore from google.protobuf import empty_pb2 as empty # type: ignore from google.pubsub_v1.types import pubsub - from .base import SubscriberTransport, DEFAULT_CLIENT_INFO @@ -70,7 +67,8 @@ def __init__( """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + 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 @@ -212,13 +210,15 @@ def create_channel( google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` and ``credentials_file`` are passed. """ - scopes = scopes or cls.AUTH_SCOPES + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + return grpc_helpers.create_channel( host, credentials=credentials, credentials_file=credentials_file, - scopes=scopes, quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, **kwargs, ) @@ -232,7 +232,9 @@ def grpc_channel(self) -> grpc.Channel: def create_subscription( self, ) -> Callable[[pubsub.Subscription], pubsub.Subscription]: - r"""Return a callable for the create subscription method over gRPC. + r"""Return a callable for the + create subscription + method over gRPC. Creates a subscription to a given topic. See the [resource name rules] @@ -270,7 +272,9 @@ def create_subscription( def get_subscription( self, ) -> Callable[[pubsub.GetSubscriptionRequest], pubsub.Subscription]: - r"""Return a callable for the get subscription method over gRPC. + r"""Return a callable for the + get subscription + method over gRPC. Gets the configuration details of a subscription. @@ -296,7 +300,9 @@ def get_subscription( def update_subscription( self, ) -> Callable[[pubsub.UpdateSubscriptionRequest], pubsub.Subscription]: - r"""Return a callable for the update subscription method over gRPC. + 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 @@ -324,7 +330,9 @@ def update_subscription( def list_subscriptions( self, ) -> Callable[[pubsub.ListSubscriptionsRequest], pubsub.ListSubscriptionsResponse]: - r"""Return a callable for the list subscriptions method over gRPC. + r"""Return a callable for the + list subscriptions + method over gRPC. Lists matching subscriptions. @@ -350,7 +358,9 @@ def list_subscriptions( def delete_subscription( self, ) -> Callable[[pubsub.DeleteSubscriptionRequest], empty.Empty]: - r"""Return a callable for the delete subscription method over gRPC. + 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 @@ -381,7 +391,9 @@ def delete_subscription( def modify_ack_deadline( self, ) -> Callable[[pubsub.ModifyAckDeadlineRequest], empty.Empty]: - r"""Return a callable for the modify ack deadline method over gRPC. + 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 @@ -410,7 +422,9 @@ def modify_ack_deadline( @property def acknowledge(self) -> Callable[[pubsub.AcknowledgeRequest], empty.Empty]: - r"""Return a callable for the acknowledge method over gRPC. + 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 @@ -441,7 +455,9 @@ def acknowledge(self) -> Callable[[pubsub.AcknowledgeRequest], empty.Empty]: @property def pull(self) -> Callable[[pubsub.PullRequest], pubsub.PullResponse]: - r"""Return a callable for the pull method over gRPC. + 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 @@ -469,7 +485,9 @@ def pull(self) -> Callable[[pubsub.PullRequest], pubsub.PullResponse]: def streaming_pull( self, ) -> Callable[[pubsub.StreamingPullRequest], pubsub.StreamingPullResponse]: - r"""Return a callable for the streaming pull method over gRPC. + 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 @@ -502,7 +520,9 @@ def streaming_pull( def modify_push_config( self, ) -> Callable[[pubsub.ModifyPushConfigRequest], empty.Empty]: - r"""Return a callable for the modify push config method over gRPC. + r"""Return a callable for the + modify push config + method over gRPC. Modifies the ``PushConfig`` for a specified subscription. @@ -532,7 +552,9 @@ def modify_push_config( @property def get_snapshot(self) -> Callable[[pubsub.GetSnapshotRequest], pubsub.Snapshot]: - r"""Return a callable for the get snapshot method over gRPC. + r"""Return a callable for the + get snapshot + method over gRPC. Gets the configuration details of a snapshot. Snapshots are used in Callable[[pubsub.GetSnapshotRequest], pubsub.Snapshot] def list_snapshots( self, ) -> Callable[[pubsub.ListSnapshotsRequest], pubsub.ListSnapshotsResponse]: - r"""Return a callable for the list snapshots method over gRPC. + r"""Return a callable for the + list snapshots + method over gRPC. Lists the existing snapshots. Snapshots are used in `Seek `__ @@ -594,7 +618,9 @@ def list_snapshots( def create_snapshot( self, ) -> Callable[[pubsub.CreateSnapshotRequest], pubsub.Snapshot]: - r"""Return a callable for the create snapshot method over gRPC. + r"""Return a callable for the + create snapshot + method over gRPC. Creates a snapshot from the requested subscription. Snapshots are used in @@ -638,7 +664,9 @@ def create_snapshot( def update_snapshot( self, ) -> Callable[[pubsub.UpdateSnapshotRequest], pubsub.Snapshot]: - r"""Return a callable for the update snapshot method over gRPC. + r"""Return a callable for the + update snapshot + method over gRPC. Updates an existing snapshot. Snapshots are used in Callable[[pubsub.DeleteSnapshotRequest], empty.Empt @property def seek(self) -> Callable[[pubsub.SeekRequest], pubsub.SeekResponse]: - r"""Return a callable for the seek method over gRPC. + 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 diff --git a/google/pubsub_v1/services/subscriber/transports/grpc_asyncio.py b/google/pubsub_v1/services/subscriber/transports/grpc_asyncio.py index bc385d317..2f37070d7 100644 --- a/google/pubsub_v1/services/subscriber/transports/grpc_asyncio.py +++ b/google/pubsub_v1/services/subscriber/transports/grpc_asyncio.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,15 +13,15 @@ # 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 +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union from google.api_core import gapic_v1 # type: ignore from google.api_core import grpc_helpers_async # type: ignore from google import auth # type: ignore from google.auth import credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore +import packaging.version import grpc # type: ignore from grpc.experimental import aio # type: ignore @@ -31,7 +30,6 @@ from google.iam.v1 import policy_pb2 as policy # type: ignore from google.protobuf import empty_pb2 as empty # type: ignore from google.pubsub_v1.types import pubsub - from .base import SubscriberTransport, DEFAULT_CLIENT_INFO from .grpc import SubscriberGrpcTransport @@ -86,13 +84,15 @@ def create_channel( Returns: aio.Channel: A gRPC AsyncIO channel object. """ - scopes = scopes or cls.AUTH_SCOPES + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + return grpc_helpers_async.create_channel( host, credentials=credentials, credentials_file=credentials_file, - scopes=scopes, quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, **kwargs, ) @@ -114,7 +114,8 @@ def __init__( """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + 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 @@ -172,7 +173,6 @@ def __init__( # 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 @@ -236,7 +236,9 @@ def grpc_channel(self) -> aio.Channel: def create_subscription( self, ) -> Callable[[pubsub.Subscription], Awaitable[pubsub.Subscription]]: - r"""Return a callable for the create subscription method over gRPC. + r"""Return a callable for the + create subscription + method over gRPC. Creates a subscription to a given topic. See the [resource name rules] @@ -274,7 +276,9 @@ def create_subscription( def get_subscription( self, ) -> Callable[[pubsub.GetSubscriptionRequest], Awaitable[pubsub.Subscription]]: - r"""Return a callable for the get subscription method over gRPC. + r"""Return a callable for the + get subscription + method over gRPC. Gets the configuration details of a subscription. @@ -300,7 +304,9 @@ def get_subscription( def update_subscription( self, ) -> Callable[[pubsub.UpdateSubscriptionRequest], Awaitable[pubsub.Subscription]]: - r"""Return a callable for the update subscription method over gRPC. + 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 @@ -330,7 +336,9 @@ def list_subscriptions( ) -> Callable[ [pubsub.ListSubscriptionsRequest], Awaitable[pubsub.ListSubscriptionsResponse] ]: - r"""Return a callable for the list subscriptions method over gRPC. + r"""Return a callable for the + list subscriptions + method over gRPC. Lists matching subscriptions. @@ -356,7 +364,9 @@ def list_subscriptions( def delete_subscription( self, ) -> Callable[[pubsub.DeleteSubscriptionRequest], Awaitable[empty.Empty]]: - r"""Return a callable for the delete subscription method over gRPC. + 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 @@ -387,7 +397,9 @@ def delete_subscription( def modify_ack_deadline( self, ) -> Callable[[pubsub.ModifyAckDeadlineRequest], Awaitable[empty.Empty]]: - r"""Return a callable for the modify ack deadline method over gRPC. + 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 @@ -418,7 +430,9 @@ def modify_ack_deadline( def acknowledge( self, ) -> Callable[[pubsub.AcknowledgeRequest], Awaitable[empty.Empty]]: - r"""Return a callable for the acknowledge method over gRPC. + 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 @@ -449,7 +463,9 @@ def acknowledge( @property def pull(self) -> Callable[[pubsub.PullRequest], Awaitable[pubsub.PullResponse]]: - r"""Return a callable for the pull method over gRPC. + 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 @@ -479,7 +495,9 @@ def streaming_pull( ) -> Callable[ [pubsub.StreamingPullRequest], Awaitable[pubsub.StreamingPullResponse] ]: - r"""Return a callable for the streaming pull method over gRPC. + 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 @@ -512,7 +530,9 @@ def streaming_pull( def modify_push_config( self, ) -> Callable[[pubsub.ModifyPushConfigRequest], Awaitable[empty.Empty]]: - r"""Return a callable for the modify push config method over gRPC. + r"""Return a callable for the + modify push config + method over gRPC. Modifies the ``PushConfig`` for a specified subscription. @@ -544,7 +564,9 @@ def modify_push_config( def get_snapshot( self, ) -> Callable[[pubsub.GetSnapshotRequest], Awaitable[pubsub.Snapshot]]: - r"""Return a callable for the get snapshot method over gRPC. + r"""Return a callable for the + get snapshot + method over gRPC. Gets the configuration details of a snapshot. Snapshots are used in Callable[ [pubsub.ListSnapshotsRequest], Awaitable[pubsub.ListSnapshotsResponse] ]: - r"""Return a callable for the list snapshots method over gRPC. + r"""Return a callable for the + list snapshots + method over gRPC. Lists the existing snapshots. Snapshots are used in `Seek `__ @@ -608,7 +632,9 @@ def list_snapshots( def create_snapshot( self, ) -> Callable[[pubsub.CreateSnapshotRequest], Awaitable[pubsub.Snapshot]]: - r"""Return a callable for the create snapshot method over gRPC. + r"""Return a callable for the + create snapshot + method over gRPC. Creates a snapshot from the requested subscription. Snapshots are used in @@ -652,7 +678,9 @@ def create_snapshot( def update_snapshot( self, ) -> Callable[[pubsub.UpdateSnapshotRequest], Awaitable[pubsub.Snapshot]]: - r"""Return a callable for the update snapshot method over gRPC. + r"""Return a callable for the + update snapshot + method over gRPC. Updates an existing snapshot. Snapshots are used in Callable[[pubsub.SeekRequest], Awaitable[pubsub.SeekResponse]]: - r"""Return a callable for the seek method over gRPC. + 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 diff --git a/google/pubsub_v1/types/__init__.py b/google/pubsub_v1/types/__init__.py index 5203abfe7..ebc8b5399 100644 --- a/google/pubsub_v1/types/__init__.py +++ b/google/pubsub_v1/types/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from typing import Union from .pubsub import ( diff --git a/google/pubsub_v1/types/pubsub.py b/google/pubsub_v1/types/pubsub.py index 6fb73e8c9..d06aa8e7e 100644 --- a/google/pubsub_v1/types/pubsub.py +++ b/google/pubsub_v1/types/pubsub.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,10 +13,8 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import proto # type: ignore - from google.protobuf import duration_pb2 as duration # type: ignore from google.protobuf import field_mask_pb2 as field_mask # type: ignore from google.protobuf import timestamp_pb2 as timestamp # type: ignore @@ -91,12 +88,11 @@ class MessageStoragePolicy(proto.Message): not a valid configuration. """ - allowed_persistence_regions = proto.RepeatedField(proto.STRING, number=1) + 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 @@ -108,14 +104,12 @@ class SchemaSettings(proto.Message): The encoding of messages validated against ``schema``. """ - schema = proto.Field(proto.STRING, number=1) - + 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 @@ -149,19 +143,14 @@ class Topic(proto.Message): if it is set in any requests. """ - name = proto.Field(proto.STRING, number=1) - + 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) - + 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) + satisfies_pzs = proto.Field(proto.BOOL, number=7,) class PubsubMessage(proto.Message): @@ -207,32 +196,26 @@ class PubsubMessage(proto.Message): same ``ordering_key`` value. """ - data = proto.Field(proto.BYTES, number=1) - + data = proto.Field(proto.BYTES, number=1,) attributes = proto.MapField(proto.STRING, proto.STRING, number=2) - - message_id = proto.Field(proto.STRING, number=3) - + message_id = proto.Field(proto.STRING, number=3,) publish_time = proto.Field(proto.MESSAGE, number=4, message=timestamp.Timestamp,) - - ordering_key = proto.Field(proto.STRING, number=5) + 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) + 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. @@ -246,13 +229,11 @@ class UpdateTopicRequest(proto.Message): """ topic = proto.Field(proto.MESSAGE, number=1, message="Topic",) - update_mask = proto.Field(proto.MESSAGE, number=2, message=field_mask.FieldMask,) class PublishRequest(proto.Message): r"""Request for the Publish method. - Attributes: topic (str): Required. The messages in the request will be published on @@ -261,14 +242,12 @@ class PublishRequest(proto.Message): Required. The messages to publish. """ - topic = proto.Field(proto.STRING, number=1) - + 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 @@ -277,12 +256,11 @@ class PublishResponse(proto.Message): within the topic. """ - message_ids = proto.RepeatedField(proto.STRING, number=1) + 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. @@ -296,16 +274,13 @@ class ListTopicsRequest(proto.Message): 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) + 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. @@ -320,13 +295,11 @@ def raw_page(self): return self topics = proto.RepeatedField(proto.MESSAGE, number=1, message="Topic",) - - next_page_token = proto.Field(proto.STRING, number=2) + 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 @@ -342,16 +315,13 @@ class ListTopicSubscriptionsRequest(proto.Message): 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) + 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 @@ -366,14 +336,12 @@ class ListTopicSubscriptionsResponse(proto.Message): def raw_page(self): return self - subscriptions = proto.RepeatedField(proto.STRING, number=1) - - next_page_token = proto.Field(proto.STRING, number=2) + 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 @@ -387,16 +355,13 @@ class ListTopicSnapshotsRequest(proto.Message): 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) + 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 @@ -411,44 +376,40 @@ class ListTopicSnapshotsResponse(proto.Message): def raw_page(self): return self - snapshots = proto.RepeatedField(proto.STRING, number=1) - - next_page_token = proto.Field(proto.STRING, number=2) + 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) + 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) + 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 @@ -563,37 +524,25 @@ class Subscription(proto.Message): endpoint will not be made. """ - name = proto.Field(proto.STRING, number=1) - - topic = proto.Field(proto.STRING, number=2) - + 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) - + 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.Duration, ) - labels = proto.MapField(proto.STRING, proto.STRING, number=9) - - enable_message_ordering = proto.Field(proto.BOOL, number=10) - + 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) - + 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) + detached = proto.Field(proto.BOOL, number=15,) class RetryPolicy(proto.Message): @@ -624,7 +573,6 @@ class RetryPolicy(proto.Message): """ minimum_backoff = proto.Field(proto.MESSAGE, number=1, message=duration.Duration,) - maximum_backoff = proto.Field(proto.MESSAGE, number=2, message=duration.Duration,) @@ -667,9 +615,8 @@ class DeadLetterPolicy(proto.Message): 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) + dead_letter_topic = proto.Field(proto.STRING, number=1,) + max_delivery_attempts = proto.Field(proto.INT32, number=2,) class ExpirationPolicy(proto.Message): @@ -692,7 +639,6 @@ class ExpirationPolicy(proto.Message): class PushConfig(proto.Message): r"""Configuration for a push delivery endpoint. - Attributes: push_endpoint (str): A URL locating the endpoint to which messages should be @@ -759,14 +705,11 @@ class OidcToken(proto.Message): 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) + 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, ) @@ -774,7 +717,6 @@ class OidcToken(proto.Message): class ReceivedMessage(proto.Message): r"""A message and its corresponding acknowledgment ID. - Attributes: ack_id (str): This ID can be used to acknowledge the @@ -802,28 +744,24 @@ class ReceivedMessage(proto.Message): will be 0. """ - ack_id = proto.Field(proto.STRING, number=1) - + 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) + 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) + 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. @@ -834,13 +772,11 @@ class UpdateSubscriptionRequest(proto.Message): """ subscription = proto.Field(proto.MESSAGE, number=1, message="Subscription",) - update_mask = proto.Field(proto.MESSAGE, number=2, message=field_mask.FieldMask,) class ListSubscriptionsRequest(proto.Message): r"""Request for the ``ListSubscriptions`` method. - Attributes: project (str): Required. The name of the project in which to list @@ -854,16 +790,13 @@ class ListSubscriptionsRequest(proto.Message): 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) + 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. @@ -880,25 +813,22 @@ def raw_page(self): subscriptions = proto.RepeatedField( proto.MESSAGE, number=1, message="Subscription", ) - - next_page_token = proto.Field(proto.STRING, number=2) + 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) + 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 @@ -913,14 +843,12 @@ class ModifyPushConfigRequest(proto.Message): not called. """ - subscription = proto.Field(proto.STRING, number=1) - + 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 @@ -942,16 +870,13 @@ class PullRequest(proto.Message): 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) + 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 @@ -968,7 +893,6 @@ class PullResponse(proto.Message): class ModifyAckDeadlineRequest(proto.Message): r"""Request for the ModifyAckDeadline method. - Attributes: subscription (str): Required. The name of the subscription. Format is @@ -988,16 +912,13 @@ class ModifyAckDeadlineRequest(proto.Message): 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) + 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 @@ -1009,9 +930,8 @@ class AcknowledgeRequest(proto.Message): ``Pull`` response. Must not be empty. """ - subscription = proto.Field(proto.STRING, number=1) - - ack_ids = proto.RepeatedField(proto.STRING, number=2) + subscription = proto.Field(proto.STRING, number=1,) + ack_ids = proto.RepeatedField(proto.STRING, number=2,) class StreamingPullRequest(proto.Message): @@ -1098,21 +1018,14 @@ class StreamingPullRequest(proto.Message): ``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) + 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): @@ -1132,7 +1045,6 @@ class StreamingPullResponse(proto.Message): class CreateSnapshotRequest(proto.Message): r"""Request for the ``CreateSnapshot`` method. - Attributes: name (str): Required. User-provided name for this snapshot. If the name @@ -1158,16 +1070,13 @@ class CreateSnapshotRequest(proto.Message): Creating and managing labels. """ - name = proto.Field(proto.STRING, number=1) - - subscription = proto.Field(proto.STRING, number=2) - + 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. @@ -1178,7 +1087,6 @@ class UpdateSnapshotRequest(proto.Message): """ snapshot = proto.Field(proto.MESSAGE, number=1, message="Snapshot",) - update_mask = proto.Field(proto.MESSAGE, number=2, message=field_mask.FieldMask,) @@ -1214,30 +1122,25 @@ class Snapshot(proto.Message): (https://cloud.google.com/pubsub/docs/labels). """ - name = proto.Field(proto.STRING, number=1) - - topic = proto.Field(proto.STRING, number=2) - + name = proto.Field(proto.STRING, number=1,) + topic = proto.Field(proto.STRING, number=2,) expire_time = proto.Field(proto.MESSAGE, number=3, message=timestamp.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) + 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 @@ -1251,16 +1154,13 @@ class ListSnapshotsRequest(proto.Message): 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) + 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. @@ -1275,25 +1175,22 @@ def raw_page(self): return self snapshots = proto.RepeatedField(proto.MESSAGE, number=1, message="Snapshot",) - - next_page_token = proto.Field(proto.STRING, number=2) + 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) + snapshot = proto.Field(proto.STRING, number=1,) class SeekRequest(proto.Message): r"""Request for the ``Seek`` method. - Attributes: subscription (str): Required. The subscription to affect. @@ -1317,17 +1214,15 @@ class SeekRequest(proto.Message): ``projects/{project}/snapshots/{snap}``. """ - subscription = proto.Field(proto.STRING, number=1) - + subscription = proto.Field(proto.STRING, number=1,) time = proto.Field( proto.MESSAGE, number=2, oneof="target", message=timestamp.Timestamp, ) - - snapshot = proto.Field(proto.STRING, number=3, oneof="target") + snapshot = proto.Field(proto.STRING, number=3, oneof="target",) class SeekResponse(proto.Message): - r"""Response for the ``Seek`` method (this response is empty).""" + r"""Response for the ``Seek`` method (this response is empty). """ __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/pubsub_v1/types/schema.py b/google/pubsub_v1/types/schema.py index e4f71d132..d15837cbd 100644 --- a/google/pubsub_v1/types/schema.py +++ b/google/pubsub_v1/types/schema.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import proto # type: ignore @@ -55,7 +53,6 @@ class Encoding(proto.Enum): class Schema(proto.Message): r"""A schema resource. - Attributes: name (str): Required. Name of the schema. Format is @@ -74,16 +71,13 @@ class Type(proto.Enum): PROTOCOL_BUFFER = 1 AVRO = 2 - name = proto.Field(proto.STRING, number=1) - + name = proto.Field(proto.STRING, number=1,) type_ = proto.Field(proto.ENUM, number=2, enum=Type,) - - definition = proto.Field(proto.STRING, number=3) + 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 @@ -103,16 +97,13 @@ class CreateSchemaRequest(proto.Message): for resource name constraints. """ - parent = proto.Field(proto.STRING, number=1) - + parent = proto.Field(proto.STRING, number=1,) schema = proto.Field(proto.MESSAGE, number=2, message="Schema",) - - schema_id = proto.Field(proto.STRING, number=3) + 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 @@ -123,14 +114,12 @@ class GetSchemaRequest(proto.Message): ``definition``. Set to ``FULL`` to retrieve all fields. """ - name = proto.Field(proto.STRING, number=1) - + 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. @@ -148,18 +137,14 @@ class ListSchemasRequest(proto.Message): next page of data. """ - parent = proto.Field(proto.STRING, number=1) - + 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) + 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. @@ -174,25 +159,22 @@ def raw_page(self): return self schemas = proto.RepeatedField(proto.MESSAGE, number=1, message="Schema",) - - next_page_token = proto.Field(proto.STRING, number=2) + 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) + 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 @@ -201,18 +183,16 @@ class ValidateSchemaRequest(proto.Message): Required. The schema object to validate. """ - parent = proto.Field(proto.STRING, number=1) - + 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.""" + r"""Response for the ``ValidateSchema`` method. """ class ValidateMessageRequest(proto.Message): r"""Request for the ``ValidateMessage`` method. - Attributes: parent (str): Required. The name of the project in which to validate @@ -229,21 +209,17 @@ class ValidateMessageRequest(proto.Message): The encoding expected for messages """ - parent = proto.Field(proto.STRING, number=1) - - name = proto.Field(proto.STRING, number=2, oneof="schema_spec") - + 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) - + 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.""" + r"""Response for the ``ValidateMessage`` method. """ __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/scripts/fixup_pubsub_v1_keywords.py b/scripts/fixup_pubsub_v1_keywords.py index 071e3665f..7262e021e 100644 --- a/scripts/fixup_pubsub_v1_keywords.py +++ b/scripts/fixup_pubsub_v1_keywords.py @@ -1,6 +1,5 @@ #! /usr/bin/env python3 # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -15,7 +14,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import argparse import os import libcst as cst @@ -41,42 +39,40 @@ def partition( 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', ), - 'create_topic': ('name', 'labels', 'message_storage_policy', 'kms_key_name', 'schema_settings', 'satisfies_pzs', ), - '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', ), - + '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', ), + 'create_topic': ('name', 'labels', 'message_storage_policy', 'kms_key_name', 'schema_settings', 'satisfies_pzs', ), + '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: @@ -107,7 +103,7 @@ def leave_Call(self, original: cst.Call, updated: cst.Call) -> cst.CSTNode: value=cst.Dict([ cst.DictElement( cst.SimpleString("'{}'".format(name)), - cst.Element(value=arg.value) +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 diff --git a/synth.metadata b/synth.metadata index 7938695bf..3d70c7ba3 100644 --- a/synth.metadata +++ b/synth.metadata @@ -11,8 +11,8 @@ "git": { "name": "googleapis", "remote": "https://github.com/googleapis/googleapis.git", - "sha": "6598bb829c9e9a534be674649ffd1b4671a821f9", - "internalRef": "364449524" + "sha": "60e129d0672a1be2c70b41bf76aadc7ad1b1ca0f", + "internalRef": "370525906" } } ], @@ -98,6 +98,7 @@ "google/pubsub/__init__.py", "google/pubsub/py.typed", "google/pubsub_v1/__init__.py", + "google/pubsub_v1/gapic_metadata.json", "google/pubsub_v1/py.typed", "google/pubsub_v1/services/__init__.py", "google/pubsub_v1/services/publisher/__init__.py", @@ -143,6 +144,9 @@ "scripts/readme-gen/templates/install_portaudio.tmpl.rst", "setup.cfg", "testing/.gitignore", + "tests/__init__.py", + "tests/unit/__init__.py", + "tests/unit/gapic/__init__.py", "tests/unit/gapic/pubsub_v1/__init__.py", "tests/unit/gapic/pubsub_v1/test_publisher.py", "tests/unit/gapic/pubsub_v1/test_schema_service.py", diff --git a/tests/__init__.py b/tests/__init__.py new file mode 100644 index 000000000..4de65971c --- /dev/null +++ b/tests/__init__.py @@ -0,0 +1,15 @@ +# -*- 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/tests/unit/__init__.py b/tests/unit/__init__.py index e69de29bb..4de65971c 100644 --- a/tests/unit/__init__.py +++ b/tests/unit/__init__.py @@ -0,0 +1,15 @@ +# -*- 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/tests/unit/gapic/__init__.py b/tests/unit/gapic/__init__.py new file mode 100644 index 000000000..4de65971c --- /dev/null +++ b/tests/unit/gapic/__init__.py @@ -0,0 +1,15 @@ +# -*- 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/tests/unit/gapic/pubsub_v1/__init__.py b/tests/unit/gapic/pubsub_v1/__init__.py index 42ffdf2bc..4de65971c 100644 --- a/tests/unit/gapic/pubsub_v1/__init__.py +++ b/tests/unit/gapic/pubsub_v1/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); diff --git a/tests/unit/gapic/pubsub_v1/test_publisher.py b/tests/unit/gapic/pubsub_v1/test_publisher.py index 5434ae944..159f07af2 100644 --- a/tests/unit/gapic/pubsub_v1/test_publisher.py +++ b/tests/unit/gapic/pubsub_v1/test_publisher.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,9 +13,9 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import os import mock +import packaging.version import grpc from grpc.experimental import aio @@ -24,6 +23,7 @@ import pytest from proto.marshal.rules.dates import DurationRule, TimestampRule + from google import auth from google.api_core import client_options from google.api_core import exceptions @@ -42,10 +42,35 @@ 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.services.publisher.transports.base import _API_CORE_VERSION +from google.pubsub_v1.services.publisher.transports.base import _GOOGLE_AUTH_VERSION from google.pubsub_v1.types import pubsub from google.pubsub_v1.types import schema +# TODO(busunkim): Once google-api-core >= 1.26.0 is required: +# - Delete all the api-core and auth "less than" test cases +# - Delete these pytest markers (Make the "greater than or equal to" tests the default). +requires_google_auth_lt_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), + reason="This test requires google-auth < 1.25.0", +) +requires_google_auth_gte_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) < packaging.version.parse("1.25.0"), + reason="This test requires google-auth >= 1.25.0", +) + +requires_api_core_lt_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) >= packaging.version.parse("1.26.0"), + reason="This test requires google-api-core < 1.26.0", +) + +requires_api_core_gte_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) < packaging.version.parse("1.26.0"), + reason="This test requires google-api-core >= 1.26.0", +) + + def client_cert_source_callback(): return b"cert bytes", b"key bytes" @@ -446,23 +471,17 @@ def test_create_topic(transport: str = "grpc", request_type=pubsub.Topic): 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 @@ -482,7 +501,6 @@ def test_create_topic_empty_call(): client.create_topic() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == pubsub.Topic() @@ -508,22 +526,17 @@ async def test_create_topic_async( 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 @@ -538,12 +551,12 @@ def test_create_topic_field_headers(): # Any value 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. @@ -563,12 +576,12 @@ async def test_create_topic_field_headers_async(): # Any value 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. @@ -588,7 +601,6 @@ def test_create_topic_flattened(): 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",) @@ -597,7 +609,6 @@ def test_create_topic_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" @@ -630,7 +641,6 @@ async def test_create_topic_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" @@ -661,23 +671,17 @@ def test_update_topic(transport: str = "grpc", request_type=pubsub.UpdateTopicRe 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 @@ -697,7 +701,6 @@ def test_update_topic_empty_call(): client.update_topic() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == pubsub.UpdateTopicRequest() @@ -723,22 +726,17 @@ async def test_update_topic_async( 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 @@ -753,12 +751,12 @@ def test_update_topic_field_headers(): # Any value 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. @@ -778,12 +776,12 @@ async def test_update_topic_field_headers_async(): # Any value 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. @@ -809,19 +807,15 @@ def test_publish(transport: str = "grpc", request_type=pubsub.PublishRequest): 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"] @@ -841,7 +835,6 @@ def test_publish_empty_call(): client.publish() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == pubsub.PublishRequest() @@ -863,18 +856,15 @@ async def test_publish_async( 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"] @@ -889,12 +879,12 @@ def test_publish_field_headers(): # Any value 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. @@ -914,6 +904,7 @@ async def test_publish_field_headers_async(): # Any value 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. @@ -921,7 +912,6 @@ async def test_publish_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( pubsub.PublishResponse() ) - await client.publish(request) # Establish that the underlying gRPC stub method was called. @@ -941,7 +931,6 @@ def test_publish_flattened(): 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( @@ -952,9 +941,7 @@ def test_publish_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].topic == "topic_value" - assert args[0].messages == [pubsub.PubsubMessage(data=b"data_blob")] @@ -993,9 +980,7 @@ async def test_publish_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].topic == "topic_value" - assert args[0].messages == [pubsub.PubsubMessage(data=b"data_blob")] @@ -1028,23 +1013,17 @@ def test_get_topic(transport: str = "grpc", request_type=pubsub.GetTopicRequest) 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 @@ -1064,7 +1043,6 @@ def test_get_topic_empty_call(): client.get_topic() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == pubsub.GetTopicRequest() @@ -1090,22 +1068,17 @@ async def test_get_topic_async( 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 @@ -1120,12 +1093,12 @@ def test_get_topic_field_headers(): # Any value 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. @@ -1145,12 +1118,12 @@ async def test_get_topic_field_headers_async(): # Any value 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. @@ -1170,7 +1143,6 @@ def test_get_topic_flattened(): 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",) @@ -1179,7 +1151,6 @@ def test_get_topic_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].topic == "topic_value" @@ -1212,7 +1183,6 @@ async def test_get_topic_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].topic == "topic_value" @@ -1243,19 +1213,15 @@ def test_list_topics(transport: str = "grpc", request_type=pubsub.ListTopicsRequ 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" @@ -1275,7 +1241,6 @@ def test_list_topics_empty_call(): client.list_topics() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == pubsub.ListTopicsRequest() @@ -1297,18 +1262,15 @@ async def test_list_topics_async( 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" @@ -1323,12 +1285,12 @@ def test_list_topics_field_headers(): # Any value 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. @@ -1348,6 +1310,7 @@ async def test_list_topics_field_headers_async(): # Any value 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. @@ -1355,7 +1318,6 @@ async def test_list_topics_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( pubsub.ListTopicsResponse() ) - await client.list_topics(request) # Establish that the underlying gRPC stub method was called. @@ -1375,7 +1337,6 @@ def test_list_topics_flattened(): 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",) @@ -1384,7 +1345,6 @@ def test_list_topics_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].project == "project_value" @@ -1419,7 +1379,6 @@ async def test_list_topics_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].project == "project_value" @@ -1561,21 +1520,16 @@ def test_list_topic_subscriptions( 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" @@ -1597,7 +1551,6 @@ def test_list_topic_subscriptions_empty_call(): client.list_topic_subscriptions() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == pubsub.ListTopicSubscriptionsRequest() @@ -1624,20 +1577,16 @@ async def test_list_topic_subscriptions_async( 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" @@ -1652,6 +1601,7 @@ def test_list_topic_subscriptions_field_headers(): # Any value 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. @@ -1659,7 +1609,6 @@ def test_list_topic_subscriptions_field_headers(): 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. @@ -1679,6 +1628,7 @@ async def test_list_topic_subscriptions_field_headers_async(): # Any value 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. @@ -1688,7 +1638,6 @@ async def test_list_topic_subscriptions_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( pubsub.ListTopicSubscriptionsResponse() ) - await client.list_topic_subscriptions(request) # Establish that the underlying gRPC stub method was called. @@ -1710,7 +1659,6 @@ def test_list_topic_subscriptions_flattened(): ) 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",) @@ -1719,7 +1667,6 @@ def test_list_topic_subscriptions_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].topic == "topic_value" @@ -1756,7 +1703,6 @@ async def test_list_topic_subscriptions_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].topic == "topic_value" @@ -1917,21 +1863,16 @@ def test_list_topic_snapshots( 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" @@ -1953,7 +1894,6 @@ def test_list_topic_snapshots_empty_call(): client.list_topic_snapshots() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == pubsub.ListTopicSnapshotsRequest() @@ -1979,20 +1919,16 @@ async def test_list_topic_snapshots_async( 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" @@ -2007,6 +1943,7 @@ def test_list_topic_snapshots_field_headers(): # Any value 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. @@ -2014,7 +1951,6 @@ def test_list_topic_snapshots_field_headers(): 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. @@ -2034,6 +1970,7 @@ async def test_list_topic_snapshots_field_headers_async(): # Any value 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. @@ -2043,7 +1980,6 @@ async def test_list_topic_snapshots_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( pubsub.ListTopicSnapshotsResponse() ) - await client.list_topic_snapshots(request) # Establish that the underlying gRPC stub method was called. @@ -2065,7 +2001,6 @@ def test_list_topic_snapshots_flattened(): ) 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",) @@ -2074,7 +2009,6 @@ def test_list_topic_snapshots_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].topic == "topic_value" @@ -2111,7 +2045,6 @@ async def test_list_topic_snapshots_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].topic == "topic_value" @@ -2258,13 +2191,11 @@ def test_delete_topic(transport: str = "grpc", request_type=pubsub.DeleteTopicRe 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. @@ -2287,7 +2218,6 @@ def test_delete_topic_empty_call(): client.delete_topic() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == pubsub.DeleteTopicRequest() @@ -2307,13 +2237,11 @@ async def test_delete_topic_async( 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. @@ -2331,12 +2259,12 @@ def test_delete_topic_field_headers(): # Any value 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. @@ -2356,12 +2284,12 @@ async def test_delete_topic_field_headers_async(): # Any value 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. @@ -2381,7 +2309,6 @@ def test_delete_topic_flattened(): 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",) @@ -2390,7 +2317,6 @@ def test_delete_topic_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].topic == "topic_value" @@ -2423,7 +2349,6 @@ async def test_delete_topic_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].topic == "topic_value" @@ -2456,17 +2381,14 @@ def test_detach_subscription( ) 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) @@ -2488,7 +2410,6 @@ def test_detach_subscription_empty_call(): client.detach_subscription() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == pubsub.DetachSubscriptionRequest() @@ -2512,13 +2433,11 @@ async def test_detach_subscription_async( 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. @@ -2536,6 +2455,7 @@ def test_detach_subscription_field_headers(): # Any value 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. @@ -2543,7 +2463,6 @@ def test_detach_subscription_field_headers(): 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. @@ -2565,6 +2484,7 @@ async def test_detach_subscription_field_headers_async(): # Any value 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. @@ -2574,7 +2494,6 @@ async def test_detach_subscription_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( pubsub.DetachSubscriptionResponse() ) - await client.detach_subscription(request) # Establish that the underlying gRPC stub method was called. @@ -2701,10 +2620,35 @@ def test_publisher_base_transport(): getattr(transport, method)(request=object()) +@requires_google_auth_gte_1_25_0 def test_publisher_base_transport_with_credentials_file(): # Instantiate the base transport with a credentials file with mock.patch.object( - auth, "load_credentials_from_file" + 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 = (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", + ) + + +@requires_google_auth_lt_1_25_0 +def test_publisher_base_transport_with_credentials_file_old_google_auth(): + # Instantiate the base transport with a credentials file + with mock.patch.object( + auth, "load_credentials_from_file", autospec=True ) as load_creds, mock.patch( "google.pubsub_v1.services.publisher.transports.PublisherTransport._prep_wrapped_messages" ) as Transport: @@ -2725,7 +2669,7 @@ def test_publisher_base_transport_with_credentials_file(): def test_publisher_base_transport_with_adc(): # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(auth, "default") as adc, mock.patch( + with mock.patch.object(auth, "default", autospec=True) as adc, mock.patch( "google.pubsub_v1.services.publisher.transports.PublisherTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None @@ -2734,9 +2678,26 @@ def test_publisher_base_transport_with_adc(): adc.assert_called_once() +@requires_google_auth_gte_1_25_0 def test_publisher_auth_adc(): # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(auth, "default") as adc: + with mock.patch.object(auth, "default", autospec=True) as adc: + adc.return_value = (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, + ) + + +@requires_google_auth_lt_1_25_0 +def test_publisher_auth_adc_old_google_auth(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(auth, "default", autospec=True) as adc: adc.return_value = (credentials.AnonymousCredentials(), None) PublisherClient() adc.assert_called_once_with( @@ -2748,14 +2709,38 @@ def test_publisher_auth_adc(): ) -def test_publisher_transport_auth_adc(): +@pytest.mark.parametrize( + "transport_class", + [transports.PublisherGrpcTransport, transports.PublisherGrpcAsyncIOTransport,], +) +@requires_google_auth_gte_1_25_0 +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(auth, "default") as adc: + with mock.patch.object(auth, "default", autospec=True) as adc: adc.return_value = (credentials.AnonymousCredentials(), None) - transports.PublisherGrpcTransport( - host="squid.clam.whelk", quota_project_id="octopus" + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + adc.assert_called_once_with( + scopes=["1", "2"], + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/pubsub", + ), + quota_project_id="octopus", ) + + +@pytest.mark.parametrize( + "transport_class", + [transports.PublisherGrpcTransport, transports.PublisherGrpcAsyncIOTransport,], +) +@requires_google_auth_lt_1_25_0 +def test_publisher_transport_auth_adc_old_google_auth(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(auth, "default", autospec=True) as adc: + adc.return_value = (credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus") adc.assert_called_once_with( scopes=( "https://www.googleapis.com/auth/cloud-platform", @@ -2765,6 +2750,114 @@ def test_publisher_transport_auth_adc(): ) +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.PublisherGrpcTransport, grpc_helpers), + (transports.PublisherGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_gte_1_26_0 +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(auth, "default", autospec=True) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + + create_channel.assert_called_with( + "pubsub.googleapis.com", + 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), + ("grpc.keepalive_time_ms", 30000), + ], + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.PublisherGrpcTransport, grpc_helpers), + (transports.PublisherGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_publisher_transport_create_channel_old_api_core(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(auth, "default", autospec=True) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class(quota_project_id="octopus") + + create_channel.assert_called_with( + "pubsub.googleapis.com", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/pubsub", + ), + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ("grpc.keepalive_time_ms", 30000), + ], + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.PublisherGrpcTransport, grpc_helpers), + (transports.PublisherGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_publisher_transport_create_channel_user_scopes(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(auth, "default", autospec=True) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = credentials.AnonymousCredentials() + adc.return_value = (creds, None) + + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + + create_channel.assert_called_with( + "pubsub.googleapis.com", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + scopes=["1", "2"], + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ("grpc.keepalive_time_ms", 30000), + ], + ) + + @pytest.mark.parametrize( "transport_class", [transports.PublisherGrpcTransport, transports.PublisherGrpcAsyncIOTransport], @@ -2958,7 +3051,6 @@ def test_publisher_transport_channel_mtls_with_adc(transport_class): def test_schema_path(): project = "squid" schema = "clam" - expected = "projects/{project}/schemas/{schema}".format( project=project, schema=schema, ) @@ -2981,7 +3073,6 @@ def test_parse_schema_path(): def test_subscription_path(): project = "oyster" subscription = "nudibranch" - expected = "projects/{project}/subscriptions/{subscription}".format( project=project, subscription=subscription, ) @@ -3004,7 +3095,6 @@ def test_parse_subscription_path(): 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 @@ -3024,7 +3114,6 @@ def test_parse_topic_path(): def test_common_billing_account_path(): billing_account = "squid" - expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -3045,7 +3134,6 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): folder = "whelk" - expected = "folders/{folder}".format(folder=folder,) actual = PublisherClient.common_folder_path(folder) assert expected == actual @@ -3064,7 +3152,6 @@ def test_parse_common_folder_path(): def test_common_organization_path(): organization = "oyster" - expected = "organizations/{organization}".format(organization=organization,) actual = PublisherClient.common_organization_path(organization) assert expected == actual @@ -3083,7 +3170,6 @@ def test_parse_common_organization_path(): def test_common_project_path(): project = "cuttlefish" - expected = "projects/{project}".format(project=project,) actual = PublisherClient.common_project_path(project) assert expected == actual @@ -3103,7 +3189,6 @@ def test_parse_common_project_path(): def test_common_location_path(): project = "winkle" location = "nautilus" - expected = "projects/{project}/locations/{location}".format( project=project, location=location, ) diff --git a/tests/unit/gapic/pubsub_v1/test_schema_service.py b/tests/unit/gapic/pubsub_v1/test_schema_service.py index 62a3aa730..d3f206ea2 100644 --- a/tests/unit/gapic/pubsub_v1/test_schema_service.py +++ b/tests/unit/gapic/pubsub_v1/test_schema_service.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,9 +13,9 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import os import mock +import packaging.version import grpc from grpc.experimental import aio @@ -24,6 +23,7 @@ import pytest from proto.marshal.rules.dates import DurationRule, TimestampRule + from google import auth from google.api_core import client_options from google.api_core import exceptions @@ -40,10 +40,37 @@ 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.services.schema_service.transports.base import _API_CORE_VERSION +from google.pubsub_v1.services.schema_service.transports.base import ( + _GOOGLE_AUTH_VERSION, +) from google.pubsub_v1.types import schema from google.pubsub_v1.types import schema as gp_schema +# TODO(busunkim): Once google-api-core >= 1.26.0 is required: +# - Delete all the api-core and auth "less than" test cases +# - Delete these pytest markers (Make the "greater than or equal to" tests the default). +requires_google_auth_lt_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), + reason="This test requires google-auth < 1.25.0", +) +requires_google_auth_gte_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) < packaging.version.parse("1.25.0"), + reason="This test requires google-auth >= 1.25.0", +) + +requires_api_core_lt_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) >= packaging.version.parse("1.26.0"), + reason="This test requires google-api-core < 1.26.0", +) + +requires_api_core_gte_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) < packaging.version.parse("1.26.0"), + reason="This test requires google-api-core >= 1.26.0", +) + + def client_cert_source_callback(): return b"cert bytes", b"key bytes" @@ -465,23 +492,17 @@ def test_create_schema( 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" @@ -501,7 +522,6 @@ def test_create_schema_empty_call(): client.create_schema() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == gp_schema.CreateSchemaRequest() @@ -527,22 +547,17 @@ async def test_create_schema_async( 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" @@ -557,12 +572,12 @@ def test_create_schema_field_headers(): # Any value 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. @@ -582,12 +597,12 @@ async def test_create_schema_field_headers_async(): # Any value 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. @@ -607,7 +622,6 @@ def test_create_schema_flattened(): 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( @@ -620,11 +634,8 @@ def test_create_schema_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" - assert args[0].schema == gp_schema.Schema(name="name_value") - assert args[0].schema_id == "schema_id_value" @@ -664,11 +675,8 @@ async def test_create_schema_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" - assert args[0].schema == gp_schema.Schema(name="name_value") - assert args[0].schema_id == "schema_id_value" @@ -704,23 +712,17 @@ def test_get_schema(transport: str = "grpc", request_type=schema.GetSchemaReques 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" @@ -740,7 +742,6 @@ def test_get_schema_empty_call(): client.get_schema() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == schema.GetSchemaRequest() @@ -766,22 +767,17 @@ async def test_get_schema_async( 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" @@ -796,12 +792,12 @@ def test_get_schema_field_headers(): # Any value 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. @@ -821,12 +817,12 @@ async def test_get_schema_field_headers_async(): # Any value 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. @@ -846,7 +842,6 @@ def test_get_schema_flattened(): 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",) @@ -855,7 +850,6 @@ def test_get_schema_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" @@ -888,7 +882,6 @@ async def test_get_schema_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" @@ -919,19 +912,15 @@ def test_list_schemas(transport: str = "grpc", request_type=schema.ListSchemasRe 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" @@ -951,7 +940,6 @@ def test_list_schemas_empty_call(): client.list_schemas() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == schema.ListSchemasRequest() @@ -973,18 +961,15 @@ async def test_list_schemas_async( 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" @@ -999,12 +984,12 @@ def test_list_schemas_field_headers(): # Any value 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. @@ -1024,6 +1009,7 @@ async def test_list_schemas_field_headers_async(): # Any value 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. @@ -1031,7 +1017,6 @@ async def test_list_schemas_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( schema.ListSchemasResponse() ) - await client.list_schemas(request) # Establish that the underlying gRPC stub method was called. @@ -1051,7 +1036,6 @@ def test_list_schemas_flattened(): 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",) @@ -1060,7 +1044,6 @@ def test_list_schemas_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" @@ -1095,7 +1078,6 @@ async def test_list_schemas_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" @@ -1240,13 +1222,11 @@ def test_delete_schema( 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. @@ -1269,7 +1249,6 @@ def test_delete_schema_empty_call(): client.delete_schema() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == schema.DeleteSchemaRequest() @@ -1289,13 +1268,11 @@ async def test_delete_schema_async( 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. @@ -1313,12 +1290,12 @@ def test_delete_schema_field_headers(): # Any value 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. @@ -1338,12 +1315,12 @@ async def test_delete_schema_field_headers_async(): # Any value 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. @@ -1363,7 +1340,6 @@ def test_delete_schema_flattened(): 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",) @@ -1372,7 +1348,6 @@ def test_delete_schema_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" @@ -1405,7 +1380,6 @@ async def test_delete_schema_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" @@ -1436,17 +1410,14 @@ def test_validate_schema( 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) @@ -1466,7 +1437,6 @@ def test_validate_schema_empty_call(): client.validate_schema() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == gp_schema.ValidateSchemaRequest() @@ -1488,13 +1458,11 @@ async def test_validate_schema_async( 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. @@ -1512,12 +1480,12 @@ def test_validate_schema_field_headers(): # Any value 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. @@ -1537,6 +1505,7 @@ async def test_validate_schema_field_headers_async(): # Any value 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. @@ -1544,7 +1513,6 @@ async def test_validate_schema_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( gp_schema.ValidateSchemaResponse() ) - await client.validate_schema(request) # Establish that the underlying gRPC stub method was called. @@ -1564,7 +1532,6 @@ def test_validate_schema_flattened(): 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( @@ -1575,9 +1542,7 @@ def test_validate_schema_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" - assert args[0].schema == gp_schema.Schema(name="name_value") @@ -1616,9 +1581,7 @@ async def test_validate_schema_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" - assert args[0].schema == gp_schema.Schema(name="name_value") @@ -1651,17 +1614,14 @@ def test_validate_message( 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) @@ -1681,7 +1641,6 @@ def test_validate_message_empty_call(): client.validate_message() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == schema.ValidateMessageRequest() @@ -1703,13 +1662,11 @@ async def test_validate_message_async( 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. @@ -1727,12 +1684,12 @@ def test_validate_message_field_headers(): # Any value 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. @@ -1752,6 +1709,7 @@ async def test_validate_message_field_headers_async(): # Any value 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. @@ -1759,7 +1717,6 @@ async def test_validate_message_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( schema.ValidateMessageResponse() ) - await client.validate_message(request) # Establish that the underlying gRPC stub method was called. @@ -1884,10 +1841,35 @@ def test_schema_service_base_transport(): getattr(transport, method)(request=object()) +@requires_google_auth_gte_1_25_0 def test_schema_service_base_transport_with_credentials_file(): # Instantiate the base transport with a credentials file with mock.patch.object( - auth, "load_credentials_from_file" + 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 = (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", + ) + + +@requires_google_auth_lt_1_25_0 +def test_schema_service_base_transport_with_credentials_file_old_google_auth(): + # Instantiate the base transport with a credentials file + with mock.patch.object( + 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: @@ -1908,7 +1890,7 @@ def test_schema_service_base_transport_with_credentials_file(): 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(auth, "default") as adc, mock.patch( + with mock.patch.object(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 @@ -1917,9 +1899,26 @@ def test_schema_service_base_transport_with_adc(): adc.assert_called_once() +@requires_google_auth_gte_1_25_0 def test_schema_service_auth_adc(): # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(auth, "default") as adc: + with mock.patch.object(auth, "default", autospec=True) as adc: + adc.return_value = (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, + ) + + +@requires_google_auth_lt_1_25_0 +def test_schema_service_auth_adc_old_google_auth(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(auth, "default", autospec=True) as adc: adc.return_value = (credentials.AnonymousCredentials(), None) SchemaServiceClient() adc.assert_called_once_with( @@ -1931,14 +1930,44 @@ def test_schema_service_auth_adc(): ) -def test_schema_service_transport_auth_adc(): +@pytest.mark.parametrize( + "transport_class", + [ + transports.SchemaServiceGrpcTransport, + transports.SchemaServiceGrpcAsyncIOTransport, + ], +) +@requires_google_auth_gte_1_25_0 +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(auth, "default") as adc: + with mock.patch.object(auth, "default", autospec=True) as adc: adc.return_value = (credentials.AnonymousCredentials(), None) - transports.SchemaServiceGrpcTransport( - host="squid.clam.whelk", quota_project_id="octopus" + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + adc.assert_called_once_with( + scopes=["1", "2"], + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/pubsub", + ), + quota_project_id="octopus", ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.SchemaServiceGrpcTransport, + transports.SchemaServiceGrpcAsyncIOTransport, + ], +) +@requires_google_auth_lt_1_25_0 +def test_schema_service_transport_auth_adc_old_google_auth(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(auth, "default", autospec=True) as adc: + adc.return_value = (credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus") adc.assert_called_once_with( scopes=( "https://www.googleapis.com/auth/cloud-platform", @@ -1948,6 +1977,118 @@ def test_schema_service_transport_auth_adc(): ) +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.SchemaServiceGrpcTransport, grpc_helpers), + (transports.SchemaServiceGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_gte_1_26_0 +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(auth, "default", autospec=True) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + + create_channel.assert_called_with( + "pubsub.googleapis.com", + 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), + ("grpc.keepalive_time_ms", 30000), + ], + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.SchemaServiceGrpcTransport, grpc_helpers), + (transports.SchemaServiceGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_schema_service_transport_create_channel_old_api_core( + transport_class, grpc_helpers +): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(auth, "default", autospec=True) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class(quota_project_id="octopus") + + create_channel.assert_called_with( + "pubsub.googleapis.com", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/pubsub", + ), + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ("grpc.keepalive_time_ms", 30000), + ], + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.SchemaServiceGrpcTransport, grpc_helpers), + (transports.SchemaServiceGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_schema_service_transport_create_channel_user_scopes( + transport_class, grpc_helpers +): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(auth, "default", autospec=True) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = credentials.AnonymousCredentials() + adc.return_value = (creds, None) + + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + + create_channel.assert_called_with( + "pubsub.googleapis.com", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + scopes=["1", "2"], + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ("grpc.keepalive_time_ms", 30000), + ], + ) + + @pytest.mark.parametrize( "transport_class", [ @@ -2150,7 +2291,6 @@ def test_schema_service_transport_channel_mtls_with_adc(transport_class): def test_schema_path(): project = "squid" schema = "clam" - expected = "projects/{project}/schemas/{schema}".format( project=project, schema=schema, ) @@ -2172,7 +2312,6 @@ def test_parse_schema_path(): def test_common_billing_account_path(): billing_account = "oyster" - expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -2193,7 +2332,6 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): folder = "cuttlefish" - expected = "folders/{folder}".format(folder=folder,) actual = SchemaServiceClient.common_folder_path(folder) assert expected == actual @@ -2212,7 +2350,6 @@ def test_parse_common_folder_path(): def test_common_organization_path(): organization = "winkle" - expected = "organizations/{organization}".format(organization=organization,) actual = SchemaServiceClient.common_organization_path(organization) assert expected == actual @@ -2231,7 +2368,6 @@ def test_parse_common_organization_path(): def test_common_project_path(): project = "scallop" - expected = "projects/{project}".format(project=project,) actual = SchemaServiceClient.common_project_path(project) assert expected == actual @@ -2251,7 +2387,6 @@ def test_parse_common_project_path(): def test_common_location_path(): project = "squid" location = "clam" - expected = "projects/{project}/locations/{location}".format( project=project, location=location, ) diff --git a/tests/unit/gapic/pubsub_v1/test_subscriber.py b/tests/unit/gapic/pubsub_v1/test_subscriber.py index 96f03eb15..f83661f03 100644 --- a/tests/unit/gapic/pubsub_v1/test_subscriber.py +++ b/tests/unit/gapic/pubsub_v1/test_subscriber.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,10 +13,10 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import os import mock import warnings +import packaging.version import grpc from grpc.experimental import aio @@ -25,6 +24,7 @@ import pytest from proto.marshal.rules.dates import DurationRule, TimestampRule + from google import auth from google.api_core import client_options from google.api_core import exceptions @@ -44,9 +44,34 @@ 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.services.subscriber.transports.base import _API_CORE_VERSION +from google.pubsub_v1.services.subscriber.transports.base import _GOOGLE_AUTH_VERSION from google.pubsub_v1.types import pubsub +# TODO(busunkim): Once google-api-core >= 1.26.0 is required: +# - Delete all the api-core and auth "less than" test cases +# - Delete these pytest markers (Make the "greater than or equal to" tests the default). +requires_google_auth_lt_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), + reason="This test requires google-auth < 1.25.0", +) +requires_google_auth_gte_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) < packaging.version.parse("1.25.0"), + reason="This test requires google-auth >= 1.25.0", +) + +requires_api_core_lt_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) >= packaging.version.parse("1.26.0"), + reason="This test requires google-api-core < 1.26.0", +) + +requires_api_core_gte_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) < packaging.version.parse("1.26.0"), + reason="This test requires google-api-core >= 1.26.0", +) + + def client_cert_source_callback(): return b"cert bytes", b"key bytes" @@ -459,31 +484,21 @@ def test_create_subscription(transport: str = "grpc", request_type=pubsub.Subscr filter="filter_value", detached=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 @@ -505,7 +520,6 @@ def test_create_subscription_empty_call(): client.create_subscription() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == pubsub.Subscription() @@ -537,30 +551,21 @@ async def test_create_subscription_async( detached=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 @@ -575,6 +580,7 @@ def test_create_subscription_field_headers(): # Any value 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. @@ -582,7 +588,6 @@ def test_create_subscription_field_headers(): 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. @@ -602,6 +607,7 @@ async def test_create_subscription_field_headers_async(): # Any value 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. @@ -609,7 +615,6 @@ async def test_create_subscription_field_headers_async(): 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. @@ -631,7 +636,6 @@ def test_create_subscription_flattened(): ) 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( @@ -645,15 +649,11 @@ def test_create_subscription_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" - assert args[0].topic == "topic_value" - assert args[0].push_config == pubsub.PushConfig( push_endpoint="push_endpoint_value" ) - assert args[0].ack_deadline_seconds == 2066 @@ -697,15 +697,11 @@ async def test_create_subscription_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" - assert args[0].topic == "topic_value" - assert args[0].push_config == pubsub.PushConfig( push_endpoint="push_endpoint_value" ) - assert args[0].ack_deadline_seconds == 2066 @@ -748,31 +744,21 @@ def test_get_subscription( filter="filter_value", detached=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 @@ -792,7 +778,6 @@ def test_get_subscription_empty_call(): client.get_subscription() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == pubsub.GetSubscriptionRequest() @@ -822,30 +807,21 @@ async def test_get_subscription_async( detached=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 @@ -860,12 +836,12 @@ def test_get_subscription_field_headers(): # Any value 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. @@ -887,12 +863,12 @@ async def test_get_subscription_field_headers_async(): # Any value 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. @@ -914,7 +890,6 @@ def test_get_subscription_flattened(): 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",) @@ -923,7 +898,6 @@ def test_get_subscription_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].subscription == "subscription_value" @@ -956,7 +930,6 @@ async def test_get_subscription_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].subscription == "subscription_value" @@ -997,31 +970,21 @@ def test_update_subscription( filter="filter_value", detached=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 @@ -1043,7 +1006,6 @@ def test_update_subscription_empty_call(): client.update_subscription() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == pubsub.UpdateSubscriptionRequest() @@ -1075,30 +1037,21 @@ async def test_update_subscription_async( detached=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 @@ -1113,6 +1066,7 @@ def test_update_subscription_field_headers(): # Any value 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. @@ -1120,7 +1074,6 @@ def test_update_subscription_field_headers(): 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. @@ -1143,6 +1096,7 @@ async def test_update_subscription_field_headers_async(): # Any value 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. @@ -1150,7 +1104,6 @@ async def test_update_subscription_field_headers_async(): 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. @@ -1185,19 +1138,15 @@ def test_list_subscriptions( 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" @@ -1219,7 +1168,6 @@ def test_list_subscriptions_empty_call(): client.list_subscriptions() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == pubsub.ListSubscriptionsRequest() @@ -1243,18 +1191,15 @@ async def test_list_subscriptions_async( 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" @@ -1269,6 +1214,7 @@ def test_list_subscriptions_field_headers(): # Any value 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. @@ -1276,7 +1222,6 @@ def test_list_subscriptions_field_headers(): 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. @@ -1296,6 +1241,7 @@ async def test_list_subscriptions_field_headers_async(): # Any value 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. @@ -1305,7 +1251,6 @@ async def test_list_subscriptions_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( pubsub.ListSubscriptionsResponse() ) - await client.list_subscriptions(request) # Establish that the underlying gRPC stub method was called. @@ -1327,7 +1272,6 @@ def test_list_subscriptions_flattened(): ) 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",) @@ -1336,7 +1280,6 @@ def test_list_subscriptions_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].project == "project_value" @@ -1373,7 +1316,6 @@ async def test_list_subscriptions_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].project == "project_value" @@ -1552,13 +1494,11 @@ def test_delete_subscription( ) 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. @@ -1583,7 +1523,6 @@ def test_delete_subscription_empty_call(): client.delete_subscription() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == pubsub.DeleteSubscriptionRequest() @@ -1605,13 +1544,11 @@ async def test_delete_subscription_async( ) 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. @@ -1629,6 +1566,7 @@ def test_delete_subscription_field_headers(): # Any value 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. @@ -1636,7 +1574,6 @@ def test_delete_subscription_field_headers(): 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. @@ -1658,6 +1595,7 @@ async def test_delete_subscription_field_headers_async(): # Any value 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. @@ -1665,7 +1603,6 @@ async def test_delete_subscription_field_headers_async(): 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. @@ -1689,7 +1626,6 @@ def test_delete_subscription_flattened(): ) 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",) @@ -1698,7 +1634,6 @@ def test_delete_subscription_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].subscription == "subscription_value" @@ -1733,7 +1668,6 @@ async def test_delete_subscription_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].subscription == "subscription_value" @@ -1766,13 +1700,11 @@ def test_modify_ack_deadline( ) 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. @@ -1797,7 +1729,6 @@ def test_modify_ack_deadline_empty_call(): client.modify_ack_deadline() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == pubsub.ModifyAckDeadlineRequest() @@ -1819,13 +1750,11 @@ async def test_modify_ack_deadline_async( ) 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. @@ -1843,6 +1772,7 @@ def test_modify_ack_deadline_field_headers(): # Any value 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. @@ -1850,7 +1780,6 @@ def test_modify_ack_deadline_field_headers(): 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. @@ -1872,6 +1801,7 @@ async def test_modify_ack_deadline_field_headers_async(): # Any value 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. @@ -1879,7 +1809,6 @@ async def test_modify_ack_deadline_field_headers_async(): 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. @@ -1903,7 +1832,6 @@ def test_modify_ack_deadline_flattened(): ) 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( @@ -1916,11 +1844,8 @@ def test_modify_ack_deadline_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].subscription == "subscription_value" - assert args[0].ack_ids == ["ack_ids_value"] - assert args[0].ack_deadline_seconds == 2066 @@ -1962,11 +1887,8 @@ async def test_modify_ack_deadline_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].subscription == "subscription_value" - assert args[0].ack_ids == ["ack_ids_value"] - assert args[0].ack_deadline_seconds == 2066 @@ -1998,13 +1920,11 @@ def test_acknowledge(transport: str = "grpc", request_type=pubsub.AcknowledgeReq 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. @@ -2027,7 +1947,6 @@ def test_acknowledge_empty_call(): client.acknowledge() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == pubsub.AcknowledgeRequest() @@ -2047,13 +1966,11 @@ async def test_acknowledge_async( 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. @@ -2071,12 +1988,12 @@ def test_acknowledge_field_headers(): # Any value 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. @@ -2098,12 +2015,12 @@ async def test_acknowledge_field_headers_async(): # Any value 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. @@ -2125,7 +2042,6 @@ def test_acknowledge_flattened(): 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( @@ -2136,9 +2052,7 @@ def test_acknowledge_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].subscription == "subscription_value" - assert args[0].ack_ids == ["ack_ids_value"] @@ -2175,9 +2089,7 @@ async def test_acknowledge_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].subscription == "subscription_value" - assert args[0].ack_ids == ["ack_ids_value"] @@ -2208,17 +2120,14 @@ def test_pull(transport: str = "grpc", request_type=pubsub.PullRequest): 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) @@ -2238,7 +2147,6 @@ def test_pull_empty_call(): client.pull() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == pubsub.PullRequest() @@ -2258,13 +2166,11 @@ async def test_pull_async( 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. @@ -2282,12 +2188,12 @@ def test_pull_field_headers(): # Any value 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. @@ -2309,12 +2215,12 @@ async def test_pull_field_headers_async(): # Any value 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. @@ -2336,7 +2242,6 @@ def test_pull_flattened(): 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. with warnings.catch_warnings(): @@ -2351,11 +2256,8 @@ def test_pull_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].subscription == "subscription_value" - assert args[0].return_immediately == True - assert args[0].max_messages == 1277 @@ -2397,11 +2299,8 @@ async def test_pull_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].subscription == "subscription_value" - assert args[0].return_immediately == True - assert args[0].max_messages == 1277 @@ -2430,20 +2329,17 @@ def test_streaming_pull( # Everything is optional in proto3 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. @@ -2466,7 +2362,6 @@ async def test_streaming_pull_async( # Everything is optional in proto3 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. @@ -2476,13 +2371,11 @@ async def test_streaming_pull_async( 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. @@ -2512,13 +2405,11 @@ def test_modify_push_config( ) 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. @@ -2543,7 +2434,6 @@ def test_modify_push_config_empty_call(): client.modify_push_config() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == pubsub.ModifyPushConfigRequest() @@ -2565,13 +2455,11 @@ async def test_modify_push_config_async( ) 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. @@ -2589,6 +2477,7 @@ def test_modify_push_config_field_headers(): # Any value 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. @@ -2596,7 +2485,6 @@ def test_modify_push_config_field_headers(): 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. @@ -2618,6 +2506,7 @@ async def test_modify_push_config_field_headers_async(): # Any value 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. @@ -2625,7 +2514,6 @@ async def test_modify_push_config_field_headers_async(): 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. @@ -2649,7 +2537,6 @@ def test_modify_push_config_flattened(): ) 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( @@ -2661,9 +2548,7 @@ def test_modify_push_config_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].subscription == "subscription_value" - assert args[0].push_config == pubsub.PushConfig( push_endpoint="push_endpoint_value" ) @@ -2705,9 +2590,7 @@ async def test_modify_push_config_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].subscription == "subscription_value" - assert args[0].push_config == pubsub.PushConfig( push_endpoint="push_endpoint_value" ) @@ -2740,21 +2623,16 @@ def test_get_snapshot(transport: str = "grpc", request_type=pubsub.GetSnapshotRe 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" @@ -2774,7 +2652,6 @@ def test_get_snapshot_empty_call(): client.get_snapshot() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == pubsub.GetSnapshotRequest() @@ -2796,20 +2673,16 @@ async def test_get_snapshot_async( 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" @@ -2824,12 +2697,12 @@ def test_get_snapshot_field_headers(): # Any value 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. @@ -2849,12 +2722,12 @@ async def test_get_snapshot_field_headers_async(): # Any value 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. @@ -2874,7 +2747,6 @@ def test_get_snapshot_flattened(): 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",) @@ -2883,7 +2755,6 @@ def test_get_snapshot_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].snapshot == "snapshot_value" @@ -2916,7 +2787,6 @@ async def test_get_snapshot_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].snapshot == "snapshot_value" @@ -2949,19 +2819,15 @@ def test_list_snapshots( 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" @@ -2981,7 +2847,6 @@ def test_list_snapshots_empty_call(): client.list_snapshots() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == pubsub.ListSnapshotsRequest() @@ -3003,18 +2868,15 @@ async def test_list_snapshots_async( 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" @@ -3029,12 +2891,12 @@ def test_list_snapshots_field_headers(): # Any value 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. @@ -3054,6 +2916,7 @@ async def test_list_snapshots_field_headers_async(): # Any value 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. @@ -3061,7 +2924,6 @@ async def test_list_snapshots_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( pubsub.ListSnapshotsResponse() ) - await client.list_snapshots(request) # Establish that the underlying gRPC stub method was called. @@ -3081,7 +2943,6 @@ def test_list_snapshots_flattened(): 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",) @@ -3090,7 +2951,6 @@ def test_list_snapshots_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].project == "project_value" @@ -3125,7 +2985,6 @@ async def test_list_snapshots_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].project == "project_value" @@ -3278,21 +3137,16 @@ def test_create_snapshot( 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" @@ -3312,7 +3166,6 @@ def test_create_snapshot_empty_call(): client.create_snapshot() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == pubsub.CreateSnapshotRequest() @@ -3334,20 +3187,16 @@ async def test_create_snapshot_async( 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" @@ -3362,12 +3211,12 @@ def test_create_snapshot_field_headers(): # Any value 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. @@ -3387,12 +3236,12 @@ async def test_create_snapshot_field_headers_async(): # Any value 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. @@ -3412,7 +3261,6 @@ def test_create_snapshot_flattened(): 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( @@ -3423,9 +3271,7 @@ def test_create_snapshot_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" - assert args[0].subscription == "subscription_value" @@ -3462,9 +3308,7 @@ async def test_create_snapshot_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" - assert args[0].subscription == "subscription_value" @@ -3497,21 +3341,16 @@ def test_update_snapshot( 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" @@ -3531,7 +3370,6 @@ def test_update_snapshot_empty_call(): client.update_snapshot() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == pubsub.UpdateSnapshotRequest() @@ -3553,20 +3391,16 @@ async def test_update_snapshot_async( 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" @@ -3581,12 +3415,12 @@ def test_update_snapshot_field_headers(): # Any value 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. @@ -3608,12 +3442,12 @@ async def test_update_snapshot_field_headers_async(): # Any value 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. @@ -3643,13 +3477,11 @@ def test_delete_snapshot( 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. @@ -3672,7 +3504,6 @@ def test_delete_snapshot_empty_call(): client.delete_snapshot() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == pubsub.DeleteSnapshotRequest() @@ -3692,13 +3523,11 @@ async def test_delete_snapshot_async( 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. @@ -3716,12 +3545,12 @@ def test_delete_snapshot_field_headers(): # Any value 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. @@ -3741,12 +3570,12 @@ async def test_delete_snapshot_field_headers_async(): # Any value 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. @@ -3766,7 +3595,6 @@ def test_delete_snapshot_flattened(): 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",) @@ -3775,7 +3603,6 @@ def test_delete_snapshot_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].snapshot == "snapshot_value" @@ -3808,7 +3635,6 @@ async def test_delete_snapshot_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].snapshot == "snapshot_value" @@ -3837,17 +3663,14 @@ def test_seek(transport: str = "grpc", request_type=pubsub.SeekRequest): 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) @@ -3867,7 +3690,6 @@ def test_seek_empty_call(): client.seek() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == pubsub.SeekRequest() @@ -3887,13 +3709,11 @@ async def test_seek_async( 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. @@ -3911,12 +3731,12 @@ def test_seek_field_headers(): # Any value 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. @@ -3938,12 +3758,12 @@ async def test_seek_field_headers_async(): # Any value 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. @@ -4077,10 +3897,35 @@ def test_subscriber_base_transport(): getattr(transport, method)(request=object()) +@requires_google_auth_gte_1_25_0 def test_subscriber_base_transport_with_credentials_file(): # Instantiate the base transport with a credentials file with mock.patch.object( - auth, "load_credentials_from_file" + 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 = (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", + ) + + +@requires_google_auth_lt_1_25_0 +def test_subscriber_base_transport_with_credentials_file_old_google_auth(): + # Instantiate the base transport with a credentials file + with mock.patch.object( + auth, "load_credentials_from_file", autospec=True ) as load_creds, mock.patch( "google.pubsub_v1.services.subscriber.transports.SubscriberTransport._prep_wrapped_messages" ) as Transport: @@ -4101,7 +3946,7 @@ def test_subscriber_base_transport_with_credentials_file(): def test_subscriber_base_transport_with_adc(): # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(auth, "default") as adc, mock.patch( + with mock.patch.object(auth, "default", autospec=True) as adc, mock.patch( "google.pubsub_v1.services.subscriber.transports.SubscriberTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None @@ -4110,9 +3955,26 @@ def test_subscriber_base_transport_with_adc(): adc.assert_called_once() +@requires_google_auth_gte_1_25_0 def test_subscriber_auth_adc(): # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(auth, "default") as adc: + with mock.patch.object(auth, "default", autospec=True) as adc: + adc.return_value = (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, + ) + + +@requires_google_auth_lt_1_25_0 +def test_subscriber_auth_adc_old_google_auth(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(auth, "default", autospec=True) as adc: adc.return_value = (credentials.AnonymousCredentials(), None) SubscriberClient() adc.assert_called_once_with( @@ -4124,14 +3986,38 @@ def test_subscriber_auth_adc(): ) -def test_subscriber_transport_auth_adc(): +@pytest.mark.parametrize( + "transport_class", + [transports.SubscriberGrpcTransport, transports.SubscriberGrpcAsyncIOTransport,], +) +@requires_google_auth_gte_1_25_0 +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(auth, "default") as adc: + with mock.patch.object(auth, "default", autospec=True) as adc: adc.return_value = (credentials.AnonymousCredentials(), None) - transports.SubscriberGrpcTransport( - host="squid.clam.whelk", quota_project_id="octopus" + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + adc.assert_called_once_with( + scopes=["1", "2"], + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/pubsub", + ), + quota_project_id="octopus", ) + + +@pytest.mark.parametrize( + "transport_class", + [transports.SubscriberGrpcTransport, transports.SubscriberGrpcAsyncIOTransport,], +) +@requires_google_auth_lt_1_25_0 +def test_subscriber_transport_auth_adc_old_google_auth(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(auth, "default", autospec=True) as adc: + adc.return_value = (credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus") adc.assert_called_once_with( scopes=( "https://www.googleapis.com/auth/cloud-platform", @@ -4141,6 +4027,116 @@ def test_subscriber_transport_auth_adc(): ) +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.SubscriberGrpcTransport, grpc_helpers), + (transports.SubscriberGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_gte_1_26_0 +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(auth, "default", autospec=True) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + + create_channel.assert_called_with( + "pubsub.googleapis.com", + 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), + ("grpc.keepalive_time_ms", 30000), + ], + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.SubscriberGrpcTransport, grpc_helpers), + (transports.SubscriberGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_subscriber_transport_create_channel_old_api_core( + transport_class, grpc_helpers +): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(auth, "default", autospec=True) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class(quota_project_id="octopus") + + create_channel.assert_called_with( + "pubsub.googleapis.com", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/pubsub", + ), + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ("grpc.keepalive_time_ms", 30000), + ], + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.SubscriberGrpcTransport, grpc_helpers), + (transports.SubscriberGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_subscriber_transport_create_channel_user_scopes(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(auth, "default", autospec=True) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = credentials.AnonymousCredentials() + adc.return_value = (creds, None) + + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + + create_channel.assert_called_with( + "pubsub.googleapis.com", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + scopes=["1", "2"], + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ("grpc.keepalive_time_ms", 30000), + ], + ) + + @pytest.mark.parametrize( "transport_class", [transports.SubscriberGrpcTransport, transports.SubscriberGrpcAsyncIOTransport], @@ -4334,7 +4330,6 @@ def test_subscriber_transport_channel_mtls_with_adc(transport_class): def test_snapshot_path(): project = "squid" snapshot = "clam" - expected = "projects/{project}/snapshots/{snapshot}".format( project=project, snapshot=snapshot, ) @@ -4357,7 +4352,6 @@ def test_parse_snapshot_path(): def test_subscription_path(): project = "oyster" subscription = "nudibranch" - expected = "projects/{project}/subscriptions/{subscription}".format( project=project, subscription=subscription, ) @@ -4380,7 +4374,6 @@ def test_parse_subscription_path(): 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 @@ -4400,7 +4393,6 @@ def test_parse_topic_path(): def test_common_billing_account_path(): billing_account = "squid" - expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -4421,7 +4413,6 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): folder = "whelk" - expected = "folders/{folder}".format(folder=folder,) actual = SubscriberClient.common_folder_path(folder) assert expected == actual @@ -4440,7 +4431,6 @@ def test_parse_common_folder_path(): def test_common_organization_path(): organization = "oyster" - expected = "organizations/{organization}".format(organization=organization,) actual = SubscriberClient.common_organization_path(organization) assert expected == actual @@ -4459,7 +4449,6 @@ def test_parse_common_organization_path(): def test_common_project_path(): project = "cuttlefish" - expected = "projects/{project}".format(project=project,) actual = SubscriberClient.common_project_path(project) assert expected == actual @@ -4479,7 +4468,6 @@ def test_parse_common_project_path(): def test_common_location_path(): project = "winkle" location = "nautilus" - expected = "projects/{project}/locations/{location}".format( project=project, location=location, ) From 8403faac80eb301f6bf6cb61a64ac677b016f8ad Mon Sep 17 00:00:00 2001 From: yoshi-automation Date: Sun, 18 Jul 2021 04:47:50 +0000 Subject: [PATCH 03/18] chore: upgrade gapic-generator python to 0.44.1 PiperOrigin-RevId: 370926454 Source-Author: Google APIs Source-Date: Wed Apr 28 09:58:07 2021 -0700 Source-Repo: googleapis/googleapis Source-Sha: 382ed8de075e1ddc9baa4ebf8dbc5b2c257a77b8 Source-Link: https://github.com/googleapis/googleapis/commit/382ed8de075e1ddc9baa4ebf8dbc5b2c257a77b8 --- google/pubsub/__init__.py | 47 +++++++------- google/pubsub_v1/__init__.py | 34 +++++----- .../services/publisher/async_client.py | 27 +++----- google/pubsub_v1/services/publisher/client.py | 27 +++----- .../services/publisher/transports/grpc.py | 36 +++-------- .../publisher/transports/grpc_asyncio.py | 36 +++-------- .../services/schema_service/async_client.py | 18 ++---- .../services/schema_service/client.py | 18 ++---- .../schema_service/transports/grpc.py | 24 ++----- .../schema_service/transports/grpc_asyncio.py | 24 ++----- .../services/subscriber/async_client.py | 48 +++++--------- .../pubsub_v1/services/subscriber/client.py | 48 +++++--------- .../services/subscriber/transports/grpc.py | 64 +++++-------------- .../subscriber/transports/grpc_asyncio.py | 64 +++++-------------- google/pubsub_v1/types/pubsub.py | 12 ++-- synth.metadata | 4 +- tests/unit/gapic/pubsub_v1/test_publisher.py | 2 +- .../gapic/pubsub_v1/test_schema_service.py | 2 +- tests/unit/gapic/pubsub_v1/test_subscriber.py | 2 +- 19 files changed, 176 insertions(+), 361 deletions(-) diff --git a/google/pubsub/__init__.py b/google/pubsub/__init__.py index 5529b3ca6..dfa5c7e04 100644 --- a/google/pubsub/__init__.py +++ b/google/pubsub/__init__.py @@ -14,14 +14,15 @@ # limitations under the License. # -from google.pubsub_v1.services.publisher.async_client import PublisherAsyncClient 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.schema_service.client import SchemaServiceClient -from google.pubsub_v1.services.subscriber.async_client import SubscriberAsyncClient 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 @@ -40,10 +41,10 @@ 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 ListTopicSubscriptionsRequest -from google.pubsub_v1.types.pubsub import ListTopicSubscriptionsResponse 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 @@ -68,78 +69,78 @@ 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 Encoding 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 SchemaView 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", - "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", + "ListTopicSubscriptionsRequest", + "ListTopicSubscriptionsResponse", "MessageStoragePolicy", "ModifyAckDeadlineRequest", "ModifyPushConfigRequest", "PublishRequest", "PublishResponse", - "PublisherAsyncClient", - "PublisherClient", "PubsubMessage", "PullRequest", "PullResponse", "PushConfig", "ReceivedMessage", "RetryPolicy", - "Schema", - "SchemaServiceAsyncClient", - "SchemaServiceClient", "SchemaSettings", - "SchemaView", "SeekRequest", "SeekResponse", "Snapshot", "StreamingPullRequest", "StreamingPullResponse", - "SubscriberAsyncClient", - "SubscriberClient", "Subscription", "Topic", "UpdateSnapshotRequest", "UpdateSubscriptionRequest", "UpdateTopicRequest", + "CreateSchemaRequest", + "DeleteSchemaRequest", + "GetSchemaRequest", + "ListSchemasRequest", + "ListSchemasResponse", + "Schema", "ValidateMessageRequest", "ValidateMessageResponse", "ValidateSchemaRequest", "ValidateSchemaResponse", + "Encoding", + "SchemaView", ) diff --git a/google/pubsub_v1/__init__.py b/google/pubsub_v1/__init__.py index 33fca22fc..86592af86 100644 --- a/google/pubsub_v1/__init__.py +++ b/google/pubsub_v1/__init__.py @@ -36,10 +36,10 @@ from .types.pubsub import ListSubscriptionsResponse from .types.pubsub import ListTopicSnapshotsRequest from .types.pubsub import ListTopicSnapshotsResponse -from .types.pubsub import ListTopicSubscriptionsRequest -from .types.pubsub import ListTopicSubscriptionsResponse 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 @@ -64,46 +64,43 @@ from .types.pubsub import UpdateTopicRequest from .types.schema import CreateSchemaRequest from .types.schema import DeleteSchemaRequest -from .types.schema import Encoding from .types.schema import GetSchemaRequest from .types.schema import ListSchemasRequest from .types.schema import ListSchemasResponse from .types.schema import Schema -from .types.schema import SchemaView 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__ = ( + "PublisherClient", + "SchemaServiceClient", + "SubscriberClient", "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", + "ListTopicSubscriptionsRequest", + "ListTopicSubscriptionsResponse", "MessageStoragePolicy", "ModifyAckDeadlineRequest", "ModifyPushConfigRequest", @@ -115,24 +112,27 @@ "PushConfig", "ReceivedMessage", "RetryPolicy", - "Schema", - "SchemaServiceClient", "SchemaSettings", - "SchemaView", "SeekRequest", "SeekResponse", "Snapshot", "StreamingPullRequest", "StreamingPullResponse", - "SubscriberClient", "Subscription", "Topic", "UpdateSnapshotRequest", "UpdateSubscriptionRequest", "UpdateTopicRequest", + "CreateSchemaRequest", + "DeleteSchemaRequest", + "GetSchemaRequest", + "ListSchemasRequest", + "ListSchemasResponse", + "Schema", "ValidateMessageRequest", "ValidateMessageResponse", "ValidateSchemaRequest", "ValidateSchemaResponse", - "PublisherClient", + "Encoding", + "SchemaView", ) diff --git a/google/pubsub_v1/services/publisher/async_client.py b/google/pubsub_v1/services/publisher/async_client.py index 9311b05e4..2fc70ae1f 100644 --- a/google/pubsub_v1/services/publisher/async_client.py +++ b/google/pubsub_v1/services/publisher/async_client.py @@ -179,8 +179,7 @@ async def create_topic( Args: request (:class:`google.pubsub_v1.types.Topic`): - The request object. - A topic resource. + 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}`` @@ -262,8 +261,7 @@ async def update_topic( Args: request (:class:`google.pubsub_v1.types.UpdateTopicRequest`): - The request object. - Request for the UpdateTopic method. + The request object. Request for the UpdateTopic method. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (TimeoutType): @@ -322,8 +320,7 @@ async def publish( Args: request (:class:`google.pubsub_v1.types.PublishRequest`): - The request object. - Request for the Publish method. + 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 @@ -415,8 +412,7 @@ async def get_topic( Args: request (:class:`google.pubsub_v1.types.GetTopicRequest`): - The request object. - Request for the GetTopic method. + 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}``. @@ -496,8 +492,7 @@ async def list_topics( Args: request (:class:`google.pubsub_v1.types.ListTopicsRequest`): - The request object. - Request for the `ListTopics` method. + 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}``. @@ -588,8 +583,7 @@ async def list_topic_subscriptions( Args: request (:class:`google.pubsub_v1.types.ListTopicSubscriptionsRequest`): - The request object. - Request for the + The request object. Request for the `ListTopicSubscriptions` method. topic (:class:`str`): Required. The name of the topic that subscriptions are @@ -686,8 +680,7 @@ async def list_topic_snapshots( Args: request (:class:`google.pubsub_v1.types.ListTopicSnapshotsRequest`): - The request object. - Request for the `ListTopicSnapshots` + The request object. Request for the `ListTopicSnapshots` method. topic (:class:`str`): Required. The name of the topic that snapshots are @@ -784,8 +777,7 @@ async def delete_topic( Args: request (:class:`google.pubsub_v1.types.DeleteTopicRequest`): - The request object. - Request for the `DeleteTopic` + The request object. Request for the `DeleteTopic` method. topic (:class:`str`): Required. Name of the topic to delete. Format is @@ -860,8 +852,7 @@ async def detach_subscription( Args: request (:class:`google.pubsub_v1.types.DetachSubscriptionRequest`): - The request object. - Request for the DetachSubscription + The request object. Request for the DetachSubscription method. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. diff --git a/google/pubsub_v1/services/publisher/client.py b/google/pubsub_v1/services/publisher/client.py index 736f3e3ce..6a9df86cd 100644 --- a/google/pubsub_v1/services/publisher/client.py +++ b/google/pubsub_v1/services/publisher/client.py @@ -410,8 +410,7 @@ def create_topic( Args: request (google.pubsub_v1.types.Topic): - The request object. - A topic resource. + The request object. A topic resource. name (str): Required. The name of the topic. It must have the format ``"projects/{project}/topics/{topic}"``. ``{topic}`` @@ -487,8 +486,7 @@ def update_topic( Args: request (google.pubsub_v1.types.UpdateTopicRequest): - The request object. - Request for the UpdateTopic method. + The request object. Request for the UpdateTopic method. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (TimeoutType): @@ -542,8 +540,7 @@ def publish( Args: request (google.pubsub_v1.types.PublishRequest): - The request object. - Request for the Publish method. + The request object. Request for the Publish method. topic (str): Required. The messages in the request will be published on this topic. Format is @@ -621,8 +618,7 @@ def get_topic( Args: request (google.pubsub_v1.types.GetTopicRequest): - The request object. - Request for the GetTopic method. + The request object. Request for the GetTopic method. topic (str): Required. The name of the topic to get. Format is ``projects/{project}/topics/{topic}``. @@ -692,8 +688,7 @@ def list_topics( Args: request (google.pubsub_v1.types.ListTopicsRequest): - The request object. - Request for the `ListTopics` method. + 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}``. @@ -774,8 +769,7 @@ def list_topic_subscriptions( Args: request (google.pubsub_v1.types.ListTopicSubscriptionsRequest): - The request object. - Request for the + The request object. Request for the `ListTopicSubscriptions` method. topic (str): Required. The name of the topic that subscriptions are @@ -862,8 +856,7 @@ def list_topic_snapshots( Args: request (google.pubsub_v1.types.ListTopicSnapshotsRequest): - The request object. - Request for the `ListTopicSnapshots` + The request object. Request for the `ListTopicSnapshots` method. topic (str): Required. The name of the topic that snapshots are @@ -950,8 +943,7 @@ def delete_topic( Args: request (google.pubsub_v1.types.DeleteTopicRequest): - The request object. - Request for the `DeleteTopic` + The request object. Request for the `DeleteTopic` method. topic (str): Required. Name of the topic to delete. Format is @@ -1020,8 +1012,7 @@ def detach_subscription( Args: request (google.pubsub_v1.types.DetachSubscriptionRequest): - The request object. - Request for the DetachSubscription + The request object. Request for the DetachSubscription method. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. diff --git a/google/pubsub_v1/services/publisher/transports/grpc.py b/google/pubsub_v1/services/publisher/transports/grpc.py index 2e6acea4d..a0e5c8773 100644 --- a/google/pubsub_v1/services/publisher/transports/grpc.py +++ b/google/pubsub_v1/services/publisher/transports/grpc.py @@ -228,9 +228,7 @@ def grpc_channel(self) -> grpc.Channel: @property def create_topic(self) -> Callable[[pubsub.Topic], pubsub.Topic]: - r"""Return a callable for the - create topic - method over gRPC. + r"""Return a callable for the create topic method over gRPC. Creates the given topic with the given name. See the [resource name rules] @@ -256,9 +254,7 @@ def create_topic(self) -> Callable[[pubsub.Topic], pubsub.Topic]: @property def update_topic(self) -> Callable[[pubsub.UpdateTopicRequest], pubsub.Topic]: - r"""Return a callable for the - update topic - method over gRPC. + 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. @@ -283,9 +279,7 @@ def update_topic(self) -> Callable[[pubsub.UpdateTopicRequest], pubsub.Topic]: @property def publish(self) -> Callable[[pubsub.PublishRequest], pubsub.PublishResponse]: - r"""Return a callable for the - publish - method over gRPC. + 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. @@ -310,9 +304,7 @@ def publish(self) -> Callable[[pubsub.PublishRequest], pubsub.PublishResponse]: @property def get_topic(self) -> Callable[[pubsub.GetTopicRequest], pubsub.Topic]: - r"""Return a callable for the - get topic - method over gRPC. + r"""Return a callable for the get topic method over gRPC. Gets the configuration of a topic. @@ -338,9 +330,7 @@ def get_topic(self) -> Callable[[pubsub.GetTopicRequest], pubsub.Topic]: def list_topics( self, ) -> Callable[[pubsub.ListTopicsRequest], pubsub.ListTopicsResponse]: - r"""Return a callable for the - list topics - method over gRPC. + r"""Return a callable for the list topics method over gRPC. Lists matching topics. @@ -368,9 +358,7 @@ def list_topic_subscriptions( ) -> Callable[ [pubsub.ListTopicSubscriptionsRequest], pubsub.ListTopicSubscriptionsResponse ]: - r"""Return a callable for the - list topic subscriptions - method over gRPC. + r"""Return a callable for the list topic subscriptions method over gRPC. Lists the names of the attached subscriptions on this topic. @@ -399,9 +387,7 @@ def list_topic_snapshots( ) -> Callable[ [pubsub.ListTopicSnapshotsRequest], pubsub.ListTopicSnapshotsResponse ]: - r"""Return a callable for the - list topic snapshots - method over gRPC. + 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 @@ -430,9 +416,7 @@ def list_topic_snapshots( @property def delete_topic(self) -> Callable[[pubsub.DeleteTopicRequest], empty.Empty]: - r"""Return a callable for the - delete topic - method over gRPC. + 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 @@ -465,9 +449,7 @@ def detach_subscription( ) -> Callable[ [pubsub.DetachSubscriptionRequest], pubsub.DetachSubscriptionResponse ]: - r"""Return a callable for the - detach subscription - method over gRPC. + 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 diff --git a/google/pubsub_v1/services/publisher/transports/grpc_asyncio.py b/google/pubsub_v1/services/publisher/transports/grpc_asyncio.py index 64250b7c3..626bdd93a 100644 --- a/google/pubsub_v1/services/publisher/transports/grpc_asyncio.py +++ b/google/pubsub_v1/services/publisher/transports/grpc_asyncio.py @@ -232,9 +232,7 @@ def grpc_channel(self) -> aio.Channel: @property def create_topic(self) -> Callable[[pubsub.Topic], Awaitable[pubsub.Topic]]: - r"""Return a callable for the - create topic - method over gRPC. + r"""Return a callable for the create topic method over gRPC. Creates the given topic with the given name. See the [resource name rules] @@ -262,9 +260,7 @@ def create_topic(self) -> Callable[[pubsub.Topic], Awaitable[pubsub.Topic]]: def update_topic( self, ) -> Callable[[pubsub.UpdateTopicRequest], Awaitable[pubsub.Topic]]: - r"""Return a callable for the - update topic - method over gRPC. + 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. @@ -291,9 +287,7 @@ def update_topic( def publish( self, ) -> Callable[[pubsub.PublishRequest], Awaitable[pubsub.PublishResponse]]: - r"""Return a callable for the - publish - method over gRPC. + 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. @@ -318,9 +312,7 @@ def publish( @property def get_topic(self) -> Callable[[pubsub.GetTopicRequest], Awaitable[pubsub.Topic]]: - r"""Return a callable for the - get topic - method over gRPC. + r"""Return a callable for the get topic method over gRPC. Gets the configuration of a topic. @@ -346,9 +338,7 @@ def get_topic(self) -> Callable[[pubsub.GetTopicRequest], Awaitable[pubsub.Topic def list_topics( self, ) -> Callable[[pubsub.ListTopicsRequest], Awaitable[pubsub.ListTopicsResponse]]: - r"""Return a callable for the - list topics - method over gRPC. + r"""Return a callable for the list topics method over gRPC. Lists matching topics. @@ -377,9 +367,7 @@ def list_topic_subscriptions( [pubsub.ListTopicSubscriptionsRequest], Awaitable[pubsub.ListTopicSubscriptionsResponse], ]: - r"""Return a callable for the - list topic subscriptions - method over gRPC. + r"""Return a callable for the list topic subscriptions method over gRPC. Lists the names of the attached subscriptions on this topic. @@ -408,9 +396,7 @@ def list_topic_snapshots( ) -> Callable[ [pubsub.ListTopicSnapshotsRequest], Awaitable[pubsub.ListTopicSnapshotsResponse] ]: - r"""Return a callable for the - list topic snapshots - method over gRPC. + 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 @@ -441,9 +427,7 @@ def list_topic_snapshots( def delete_topic( self, ) -> Callable[[pubsub.DeleteTopicRequest], Awaitable[empty.Empty]]: - r"""Return a callable for the - delete topic - method over gRPC. + 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 @@ -476,9 +460,7 @@ def detach_subscription( ) -> Callable[ [pubsub.DetachSubscriptionRequest], Awaitable[pubsub.DetachSubscriptionResponse] ]: - r"""Return a callable for the - detach subscription - method over gRPC. + 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 diff --git a/google/pubsub_v1/services/schema_service/async_client.py b/google/pubsub_v1/services/schema_service/async_client.py index 4cfc74e81..43c8139f5 100644 --- a/google/pubsub_v1/services/schema_service/async_client.py +++ b/google/pubsub_v1/services/schema_service/async_client.py @@ -178,8 +178,7 @@ async def create_schema( Args: request (:class:`google.pubsub_v1.types.CreateSchemaRequest`): - The request object. - Request for the CreateSchema method. + 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}``. @@ -272,8 +271,7 @@ async def get_schema( Args: request (:class:`google.pubsub_v1.types.GetSchemaRequest`): - The request object. - Request for the GetSchema method. + 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}``. @@ -341,8 +339,7 @@ async def list_schemas( Args: request (:class:`google.pubsub_v1.types.ListSchemasRequest`): - The request object. - Request for the `ListSchemas` + The request object. Request for the `ListSchemas` method. parent (:class:`str`): Required. The name of the project in which to list @@ -421,8 +418,7 @@ async def delete_schema( Args: request (:class:`google.pubsub_v1.types.DeleteSchemaRequest`): - The request object. - Request for the `DeleteSchema` + The request object. Request for the `DeleteSchema` method. name (:class:`str`): Required. Name of the schema to delete. Format is @@ -487,8 +483,7 @@ async def validate_schema( Args: request (:class:`google.pubsub_v1.types.ValidateSchemaRequest`): - The request object. - Request for the `ValidateSchema` + The request object. Request for the `ValidateSchema` method. parent (:class:`str`): Required. The name of the project in which to validate @@ -565,8 +560,7 @@ async def validate_message( Args: request (:class:`google.pubsub_v1.types.ValidateMessageRequest`): - The request object. - Request for the `ValidateMessage` + The request object. Request for the `ValidateMessage` method. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. diff --git a/google/pubsub_v1/services/schema_service/client.py b/google/pubsub_v1/services/schema_service/client.py index cb85dbd51..fc735a4e1 100644 --- a/google/pubsub_v1/services/schema_service/client.py +++ b/google/pubsub_v1/services/schema_service/client.py @@ -353,8 +353,7 @@ def create_schema( Args: request (google.pubsub_v1.types.CreateSchemaRequest): - The request object. - Request for the CreateSchema method. + 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}``. @@ -447,8 +446,7 @@ def get_schema( Args: request (google.pubsub_v1.types.GetSchemaRequest): - The request object. - Request for the GetSchema method. + The request object. Request for the GetSchema method. name (str): Required. The name of the schema to get. Format is ``projects/{project}/schemas/{schema}``. @@ -516,8 +514,7 @@ def list_schemas( Args: request (google.pubsub_v1.types.ListSchemasRequest): - The request object. - Request for the `ListSchemas` + The request object. Request for the `ListSchemas` method. parent (str): Required. The name of the project in which to list @@ -596,8 +593,7 @@ def delete_schema( Args: request (google.pubsub_v1.types.DeleteSchemaRequest): - The request object. - Request for the `DeleteSchema` + The request object. Request for the `DeleteSchema` method. name (str): Required. Name of the schema to delete. Format is @@ -662,8 +658,7 @@ def validate_schema( Args: request (google.pubsub_v1.types.ValidateSchemaRequest): - The request object. - Request for the `ValidateSchema` + The request object. Request for the `ValidateSchema` method. parent (str): Required. The name of the project in which to validate @@ -740,8 +735,7 @@ def validate_message( Args: request (google.pubsub_v1.types.ValidateMessageRequest): - The request object. - Request for the `ValidateMessage` + The request object. Request for the `ValidateMessage` method. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. diff --git a/google/pubsub_v1/services/schema_service/transports/grpc.py b/google/pubsub_v1/services/schema_service/transports/grpc.py index 55967e792..f6eb42dce 100644 --- a/google/pubsub_v1/services/schema_service/transports/grpc.py +++ b/google/pubsub_v1/services/schema_service/transports/grpc.py @@ -230,9 +230,7 @@ def grpc_channel(self) -> grpc.Channel: def create_schema( self, ) -> Callable[[gp_schema.CreateSchemaRequest], gp_schema.Schema]: - r"""Return a callable for the - create schema - method over gRPC. + r"""Return a callable for the create schema method over gRPC. Creates a schema. @@ -256,9 +254,7 @@ def create_schema( @property def get_schema(self) -> Callable[[schema.GetSchemaRequest], schema.Schema]: - r"""Return a callable for the - get schema - method over gRPC. + r"""Return a callable for the get schema method over gRPC. Gets a schema. @@ -284,9 +280,7 @@ def get_schema(self) -> Callable[[schema.GetSchemaRequest], schema.Schema]: def list_schemas( self, ) -> Callable[[schema.ListSchemasRequest], schema.ListSchemasResponse]: - r"""Return a callable for the - list schemas - method over gRPC. + r"""Return a callable for the list schemas method over gRPC. Lists schemas in a project. @@ -310,9 +304,7 @@ def list_schemas( @property def delete_schema(self) -> Callable[[schema.DeleteSchemaRequest], empty.Empty]: - r"""Return a callable for the - delete schema - method over gRPC. + r"""Return a callable for the delete schema method over gRPC. Deletes a schema. @@ -338,9 +330,7 @@ def delete_schema(self) -> Callable[[schema.DeleteSchemaRequest], empty.Empty]: def validate_schema( self, ) -> Callable[[gp_schema.ValidateSchemaRequest], gp_schema.ValidateSchemaResponse]: - r"""Return a callable for the - validate schema - method over gRPC. + r"""Return a callable for the validate schema method over gRPC. Validates a schema. @@ -366,9 +356,7 @@ def validate_schema( def validate_message( self, ) -> Callable[[schema.ValidateMessageRequest], schema.ValidateMessageResponse]: - r"""Return a callable for the - validate message - method over gRPC. + r"""Return a callable for the validate message method over gRPC. Validates a message against a schema. diff --git a/google/pubsub_v1/services/schema_service/transports/grpc_asyncio.py b/google/pubsub_v1/services/schema_service/transports/grpc_asyncio.py index 957b402d0..8e8fc22ce 100644 --- a/google/pubsub_v1/services/schema_service/transports/grpc_asyncio.py +++ b/google/pubsub_v1/services/schema_service/transports/grpc_asyncio.py @@ -234,9 +234,7 @@ def grpc_channel(self) -> aio.Channel: def create_schema( self, ) -> Callable[[gp_schema.CreateSchemaRequest], Awaitable[gp_schema.Schema]]: - r"""Return a callable for the - create schema - method over gRPC. + r"""Return a callable for the create schema method over gRPC. Creates a schema. @@ -262,9 +260,7 @@ def create_schema( def get_schema( self, ) -> Callable[[schema.GetSchemaRequest], Awaitable[schema.Schema]]: - r"""Return a callable for the - get schema - method over gRPC. + r"""Return a callable for the get schema method over gRPC. Gets a schema. @@ -290,9 +286,7 @@ def get_schema( def list_schemas( self, ) -> Callable[[schema.ListSchemasRequest], Awaitable[schema.ListSchemasResponse]]: - r"""Return a callable for the - list schemas - method over gRPC. + r"""Return a callable for the list schemas method over gRPC. Lists schemas in a project. @@ -318,9 +312,7 @@ def list_schemas( def delete_schema( self, ) -> Callable[[schema.DeleteSchemaRequest], Awaitable[empty.Empty]]: - r"""Return a callable for the - delete schema - method over gRPC. + r"""Return a callable for the delete schema method over gRPC. Deletes a schema. @@ -348,9 +340,7 @@ def validate_schema( ) -> Callable[ [gp_schema.ValidateSchemaRequest], Awaitable[gp_schema.ValidateSchemaResponse] ]: - r"""Return a callable for the - validate schema - method over gRPC. + r"""Return a callable for the validate schema method over gRPC. Validates a schema. @@ -378,9 +368,7 @@ def validate_message( ) -> Callable[ [schema.ValidateMessageRequest], Awaitable[schema.ValidateMessageResponse] ]: - r"""Return a callable for the - validate message - method over gRPC. + r"""Return a callable for the validate message method over gRPC. Validates a message against a schema. diff --git a/google/pubsub_v1/services/subscriber/async_client.py b/google/pubsub_v1/services/subscriber/async_client.py index 781df6d4c..1a6b0cfbf 100644 --- a/google/pubsub_v1/services/subscriber/async_client.py +++ b/google/pubsub_v1/services/subscriber/async_client.py @@ -204,8 +204,7 @@ async def create_subscription( Args: request (:class:`google.pubsub_v1.types.Subscription`): - The request object. - A subscription resource. + The request object. A subscription resource. name (:class:`str`): Required. The name of the subscription. It must have the format @@ -345,8 +344,7 @@ async def get_subscription( Args: request (:class:`google.pubsub_v1.types.GetSubscriptionRequest`): - The request object. - Request for the GetSubscription + The request object. Request for the GetSubscription method. subscription (:class:`str`): Required. The name of the subscription to get. Format is @@ -429,8 +427,7 @@ async def update_subscription( Args: request (:class:`google.pubsub_v1.types.UpdateSubscriptionRequest`): - The request object. - Request for the UpdateSubscription + The request object. Request for the UpdateSubscription method. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. @@ -487,8 +484,7 @@ async def list_subscriptions( Args: request (:class:`google.pubsub_v1.types.ListSubscriptionsRequest`): - The request object. - Request for the `ListSubscriptions` + The request object. Request for the `ListSubscriptions` method. project (:class:`str`): Required. The name of the project in which to list @@ -583,8 +579,7 @@ async def delete_subscription( Args: request (:class:`google.pubsub_v1.types.DeleteSubscriptionRequest`): - The request object. - Request for the DeleteSubscription + The request object. Request for the DeleteSubscription method. subscription (:class:`str`): Required. The subscription to delete. Format is @@ -664,8 +659,7 @@ async def modify_ack_deadline( Args: request (:class:`google.pubsub_v1.types.ModifyAckDeadlineRequest`): - The request object. - Request for the ModifyAckDeadline + The request object. Request for the ModifyAckDeadline method. subscription (:class:`str`): Required. The name of the subscription. Format is @@ -771,8 +765,7 @@ async def acknowledge( Args: request (:class:`google.pubsub_v1.types.AcknowledgeRequest`): - The request object. - Request for the Acknowledge method. + The request object. Request for the Acknowledge method. subscription (:class:`str`): Required. The subscription whose message is being acknowledged. Format is @@ -859,8 +852,7 @@ async def pull( Args: request (:class:`google.pubsub_v1.types.PullRequest`): - The request object. - Request for the `Pull` method. + The request object. Request for the `Pull` method. subscription (:class:`str`): Required. The subscription from which messages should be pulled. Format is @@ -982,8 +974,7 @@ def streaming_pull( Args: requests (AsyncIterator[`google.pubsub_v1.types.StreamingPullRequest`]): - The request object AsyncIterator. - Request for the `StreamingPull` + 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 @@ -1048,8 +1039,7 @@ async def modify_push_config( Args: request (:class:`google.pubsub_v1.types.ModifyPushConfigRequest`): - The request object. - Request for the ModifyPushConfig + The request object. Request for the ModifyPushConfig method. subscription (:class:`str`): Required. The name of the subscription. Format is @@ -1142,8 +1132,7 @@ async def get_snapshot( Args: request (:class:`google.pubsub_v1.types.GetSnapshotRequest`): - The request object. - Request for the GetSnapshot method. + 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}``. @@ -1232,8 +1221,7 @@ async def list_snapshots( Args: request (:class:`google.pubsub_v1.types.ListSnapshotsRequest`): - The request object. - Request for the `ListSnapshots` + The request object. Request for the `ListSnapshots` method. project (:class:`str`): Required. The name of the project in which to list @@ -1342,8 +1330,7 @@ async def create_snapshot( Args: request (:class:`google.pubsub_v1.types.CreateSnapshotRequest`): - The request object. - Request for the `CreateSnapshot` + The request object. Request for the `CreateSnapshot` method. name (:class:`str`): Required. User-provided name for this snapshot. If the @@ -1452,8 +1439,7 @@ async def update_snapshot( Args: request (:class:`google.pubsub_v1.types.UpdateSnapshotRequest`): - The request object. - Request for the UpdateSnapshot + The request object. Request for the UpdateSnapshot method. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. @@ -1525,8 +1511,7 @@ async def delete_snapshot( Args: request (:class:`google.pubsub_v1.types.DeleteSnapshotRequest`): - The request object. - Request for the `DeleteSnapshot` + The request object. Request for the `DeleteSnapshot` method. snapshot (:class:`str`): Required. The name of the snapshot to delete. Format is @@ -1604,8 +1589,7 @@ async def seek( Args: request (:class:`google.pubsub_v1.types.SeekRequest`): - The request object. - Request for the `Seek` method. + 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. diff --git a/google/pubsub_v1/services/subscriber/client.py b/google/pubsub_v1/services/subscriber/client.py index b9c988159..3c8899352 100644 --- a/google/pubsub_v1/services/subscriber/client.py +++ b/google/pubsub_v1/services/subscriber/client.py @@ -436,8 +436,7 @@ def create_subscription( Args: request (google.pubsub_v1.types.Subscription): - The request object. - A subscription resource. + The request object. A subscription resource. name (str): Required. The name of the subscription. It must have the format @@ -567,8 +566,7 @@ def get_subscription( Args: request (google.pubsub_v1.types.GetSubscriptionRequest): - The request object. - Request for the GetSubscription + The request object. Request for the GetSubscription method. subscription (str): Required. The name of the subscription to get. Format is @@ -641,8 +639,7 @@ def update_subscription( Args: request (google.pubsub_v1.types.UpdateSubscriptionRequest): - The request object. - Request for the UpdateSubscription + The request object. Request for the UpdateSubscription method. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. @@ -694,8 +691,7 @@ def list_subscriptions( Args: request (google.pubsub_v1.types.ListSubscriptionsRequest): - The request object. - Request for the `ListSubscriptions` + The request object. Request for the `ListSubscriptions` method. project (str): Required. The name of the project in which to list @@ -780,8 +776,7 @@ def delete_subscription( Args: request (google.pubsub_v1.types.DeleteSubscriptionRequest): - The request object. - Request for the DeleteSubscription + The request object. Request for the DeleteSubscription method. subscription (str): Required. The subscription to delete. Format is @@ -855,8 +850,7 @@ def modify_ack_deadline( Args: request (google.pubsub_v1.types.ModifyAckDeadlineRequest): - The request object. - Request for the ModifyAckDeadline + The request object. Request for the ModifyAckDeadline method. subscription (str): Required. The name of the subscription. Format is @@ -956,8 +950,7 @@ def acknowledge( Args: request (google.pubsub_v1.types.AcknowledgeRequest): - The request object. - Request for the Acknowledge method. + The request object. Request for the Acknowledge method. subscription (str): Required. The subscription whose message is being acknowledged. Format is @@ -1038,8 +1031,7 @@ def pull( Args: request (google.pubsub_v1.types.PullRequest): - The request object. - Request for the `Pull` method. + The request object. Request for the `Pull` method. subscription (str): Required. The subscription from which messages should be pulled. Format is @@ -1151,8 +1143,7 @@ def streaming_pull( Args: requests (Iterator[google.pubsub_v1.types.StreamingPullRequest]): - The request object iterator. - Request for the `StreamingPull` + 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 @@ -1206,8 +1197,7 @@ def modify_push_config( Args: request (google.pubsub_v1.types.ModifyPushConfigRequest): - The request object. - Request for the ModifyPushConfig + The request object. Request for the ModifyPushConfig method. subscription (str): Required. The name of the subscription. Format is @@ -1294,8 +1284,7 @@ def get_snapshot( Args: request (google.pubsub_v1.types.GetSnapshotRequest): - The request object. - Request for the GetSnapshot method. + The request object. Request for the GetSnapshot method. snapshot (str): Required. The name of the snapshot to get. Format is ``projects/{project}/snapshots/{snap}``. @@ -1374,8 +1363,7 @@ def list_snapshots( Args: request (google.pubsub_v1.types.ListSnapshotsRequest): - The request object. - Request for the `ListSnapshots` + The request object. Request for the `ListSnapshots` method. project (str): Required. The name of the project in which to list @@ -1474,8 +1462,7 @@ def create_snapshot( Args: request (google.pubsub_v1.types.CreateSnapshotRequest): - The request object. - Request for the `CreateSnapshot` + The request object. Request for the `CreateSnapshot` method. name (str): Required. User-provided name for this snapshot. If the @@ -1578,8 +1565,7 @@ def update_snapshot( Args: request (google.pubsub_v1.types.UpdateSnapshotRequest): - The request object. - Request for the UpdateSnapshot + The request object. Request for the UpdateSnapshot method. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. @@ -1646,8 +1632,7 @@ def delete_snapshot( Args: request (google.pubsub_v1.types.DeleteSnapshotRequest): - The request object. - Request for the `DeleteSnapshot` + The request object. Request for the `DeleteSnapshot` method. snapshot (str): Required. The name of the snapshot to delete. Format is @@ -1719,8 +1704,7 @@ def seek( Args: request (google.pubsub_v1.types.SeekRequest): - The request object. - Request for the `Seek` method. + 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. diff --git a/google/pubsub_v1/services/subscriber/transports/grpc.py b/google/pubsub_v1/services/subscriber/transports/grpc.py index adb7f9b7a..c0e7f69e7 100644 --- a/google/pubsub_v1/services/subscriber/transports/grpc.py +++ b/google/pubsub_v1/services/subscriber/transports/grpc.py @@ -232,9 +232,7 @@ def grpc_channel(self) -> grpc.Channel: def create_subscription( self, ) -> Callable[[pubsub.Subscription], pubsub.Subscription]: - r"""Return a callable for the - create subscription - method over gRPC. + r"""Return a callable for the create subscription method over gRPC. Creates a subscription to a given topic. See the [resource name rules] @@ -272,9 +270,7 @@ def create_subscription( def get_subscription( self, ) -> Callable[[pubsub.GetSubscriptionRequest], pubsub.Subscription]: - r"""Return a callable for the - get subscription - method over gRPC. + r"""Return a callable for the get subscription method over gRPC. Gets the configuration details of a subscription. @@ -300,9 +296,7 @@ def get_subscription( def update_subscription( self, ) -> Callable[[pubsub.UpdateSubscriptionRequest], pubsub.Subscription]: - r"""Return a callable for the - update subscription - method over gRPC. + 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 @@ -330,9 +324,7 @@ def update_subscription( def list_subscriptions( self, ) -> Callable[[pubsub.ListSubscriptionsRequest], pubsub.ListSubscriptionsResponse]: - r"""Return a callable for the - list subscriptions - method over gRPC. + r"""Return a callable for the list subscriptions method over gRPC. Lists matching subscriptions. @@ -358,9 +350,7 @@ def list_subscriptions( def delete_subscription( self, ) -> Callable[[pubsub.DeleteSubscriptionRequest], empty.Empty]: - r"""Return a callable for the - delete subscription - method over gRPC. + 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 @@ -391,9 +381,7 @@ def delete_subscription( def modify_ack_deadline( self, ) -> Callable[[pubsub.ModifyAckDeadlineRequest], empty.Empty]: - r"""Return a callable for the - modify ack deadline - method over gRPC. + 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 @@ -422,9 +410,7 @@ def modify_ack_deadline( @property def acknowledge(self) -> Callable[[pubsub.AcknowledgeRequest], empty.Empty]: - r"""Return a callable for the - acknowledge - method over gRPC. + 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 @@ -455,9 +441,7 @@ def acknowledge(self) -> Callable[[pubsub.AcknowledgeRequest], empty.Empty]: @property def pull(self) -> Callable[[pubsub.PullRequest], pubsub.PullResponse]: - r"""Return a callable for the - pull - method over gRPC. + 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 @@ -485,9 +469,7 @@ def pull(self) -> Callable[[pubsub.PullRequest], pubsub.PullResponse]: def streaming_pull( self, ) -> Callable[[pubsub.StreamingPullRequest], pubsub.StreamingPullResponse]: - r"""Return a callable for the - streaming pull - method over gRPC. + 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 @@ -520,9 +502,7 @@ def streaming_pull( def modify_push_config( self, ) -> Callable[[pubsub.ModifyPushConfigRequest], empty.Empty]: - r"""Return a callable for the - modify push config - method over gRPC. + r"""Return a callable for the modify push config method over gRPC. Modifies the ``PushConfig`` for a specified subscription. @@ -552,9 +532,7 @@ def modify_push_config( @property def get_snapshot(self) -> Callable[[pubsub.GetSnapshotRequest], pubsub.Snapshot]: - r"""Return a callable for the - get snapshot - method over gRPC. + r"""Return a callable for the get snapshot method over gRPC. Gets the configuration details of a snapshot. Snapshots are used in Callable[[pubsub.GetSnapshotRequest], pubsub.Snapshot] def list_snapshots( self, ) -> Callable[[pubsub.ListSnapshotsRequest], pubsub.ListSnapshotsResponse]: - r"""Return a callable for the - list snapshots - method over gRPC. + r"""Return a callable for the list snapshots method over gRPC. Lists the existing snapshots. Snapshots are used in `Seek `__ @@ -618,9 +594,7 @@ def list_snapshots( def create_snapshot( self, ) -> Callable[[pubsub.CreateSnapshotRequest], pubsub.Snapshot]: - r"""Return a callable for the - create snapshot - method over gRPC. + r"""Return a callable for the create snapshot method over gRPC. Creates a snapshot from the requested subscription. Snapshots are used in @@ -664,9 +638,7 @@ def create_snapshot( def update_snapshot( self, ) -> Callable[[pubsub.UpdateSnapshotRequest], pubsub.Snapshot]: - r"""Return a callable for the - update snapshot - method over gRPC. + r"""Return a callable for the update snapshot method over gRPC. Updates an existing snapshot. Snapshots are used in Callable[[pubsub.DeleteSnapshotRequest], empty.Empt @property def seek(self) -> Callable[[pubsub.SeekRequest], pubsub.SeekResponse]: - r"""Return a callable for the - seek - method over gRPC. + 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 diff --git a/google/pubsub_v1/services/subscriber/transports/grpc_asyncio.py b/google/pubsub_v1/services/subscriber/transports/grpc_asyncio.py index 2f37070d7..64298b4ef 100644 --- a/google/pubsub_v1/services/subscriber/transports/grpc_asyncio.py +++ b/google/pubsub_v1/services/subscriber/transports/grpc_asyncio.py @@ -236,9 +236,7 @@ def grpc_channel(self) -> aio.Channel: def create_subscription( self, ) -> Callable[[pubsub.Subscription], Awaitable[pubsub.Subscription]]: - r"""Return a callable for the - create subscription - method over gRPC. + r"""Return a callable for the create subscription method over gRPC. Creates a subscription to a given topic. See the [resource name rules] @@ -276,9 +274,7 @@ def create_subscription( def get_subscription( self, ) -> Callable[[pubsub.GetSubscriptionRequest], Awaitable[pubsub.Subscription]]: - r"""Return a callable for the - get subscription - method over gRPC. + r"""Return a callable for the get subscription method over gRPC. Gets the configuration details of a subscription. @@ -304,9 +300,7 @@ def get_subscription( def update_subscription( self, ) -> Callable[[pubsub.UpdateSubscriptionRequest], Awaitable[pubsub.Subscription]]: - r"""Return a callable for the - update subscription - method over gRPC. + 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 @@ -336,9 +330,7 @@ def list_subscriptions( ) -> Callable[ [pubsub.ListSubscriptionsRequest], Awaitable[pubsub.ListSubscriptionsResponse] ]: - r"""Return a callable for the - list subscriptions - method over gRPC. + r"""Return a callable for the list subscriptions method over gRPC. Lists matching subscriptions. @@ -364,9 +356,7 @@ def list_subscriptions( def delete_subscription( self, ) -> Callable[[pubsub.DeleteSubscriptionRequest], Awaitable[empty.Empty]]: - r"""Return a callable for the - delete subscription - method over gRPC. + 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 @@ -397,9 +387,7 @@ def delete_subscription( def modify_ack_deadline( self, ) -> Callable[[pubsub.ModifyAckDeadlineRequest], Awaitable[empty.Empty]]: - r"""Return a callable for the - modify ack deadline - method over gRPC. + 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 @@ -430,9 +418,7 @@ def modify_ack_deadline( def acknowledge( self, ) -> Callable[[pubsub.AcknowledgeRequest], Awaitable[empty.Empty]]: - r"""Return a callable for the - acknowledge - method over gRPC. + 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 @@ -463,9 +449,7 @@ def acknowledge( @property def pull(self) -> Callable[[pubsub.PullRequest], Awaitable[pubsub.PullResponse]]: - r"""Return a callable for the - pull - method over gRPC. + 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 @@ -495,9 +479,7 @@ def streaming_pull( ) -> Callable[ [pubsub.StreamingPullRequest], Awaitable[pubsub.StreamingPullResponse] ]: - r"""Return a callable for the - streaming pull - method over gRPC. + 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 @@ -530,9 +512,7 @@ def streaming_pull( def modify_push_config( self, ) -> Callable[[pubsub.ModifyPushConfigRequest], Awaitable[empty.Empty]]: - r"""Return a callable for the - modify push config - method over gRPC. + r"""Return a callable for the modify push config method over gRPC. Modifies the ``PushConfig`` for a specified subscription. @@ -564,9 +544,7 @@ def modify_push_config( def get_snapshot( self, ) -> Callable[[pubsub.GetSnapshotRequest], Awaitable[pubsub.Snapshot]]: - r"""Return a callable for the - get snapshot - method over gRPC. + r"""Return a callable for the get snapshot method over gRPC. Gets the configuration details of a snapshot. Snapshots are used in Callable[ [pubsub.ListSnapshotsRequest], Awaitable[pubsub.ListSnapshotsResponse] ]: - r"""Return a callable for the - list snapshots - method over gRPC. + r"""Return a callable for the list snapshots method over gRPC. Lists the existing snapshots. Snapshots are used in `Seek `__ @@ -632,9 +608,7 @@ def list_snapshots( def create_snapshot( self, ) -> Callable[[pubsub.CreateSnapshotRequest], Awaitable[pubsub.Snapshot]]: - r"""Return a callable for the - create snapshot - method over gRPC. + r"""Return a callable for the create snapshot method over gRPC. Creates a snapshot from the requested subscription. Snapshots are used in @@ -678,9 +652,7 @@ def create_snapshot( def update_snapshot( self, ) -> Callable[[pubsub.UpdateSnapshotRequest], Awaitable[pubsub.Snapshot]]: - r"""Return a callable for the - update snapshot - method over gRPC. + r"""Return a callable for the update snapshot method over gRPC. Updates an existing snapshot. Snapshots are used in Callable[[pubsub.SeekRequest], Awaitable[pubsub.SeekResponse]]: - r"""Return a callable for the - seek - method over gRPC. + 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 diff --git a/google/pubsub_v1/types/pubsub.py b/google/pubsub_v1/types/pubsub.py index d06aa8e7e..51da28e86 100644 --- a/google/pubsub_v1/types/pubsub.py +++ b/google/pubsub_v1/types/pubsub.py @@ -144,7 +144,7 @@ class Topic(proto.Message): """ name = proto.Field(proto.STRING, number=1,) - labels = proto.MapField(proto.STRING, proto.STRING, number=2) + labels = proto.MapField(proto.STRING, proto.STRING, number=2,) message_storage_policy = proto.Field( proto.MESSAGE, number=3, message="MessageStoragePolicy", ) @@ -197,7 +197,7 @@ class PubsubMessage(proto.Message): """ data = proto.Field(proto.BYTES, number=1,) - attributes = proto.MapField(proto.STRING, proto.STRING, number=2) + 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.Timestamp,) ordering_key = proto.Field(proto.STRING, number=5,) @@ -532,7 +532,7 @@ class Subscription(proto.Message): message_retention_duration = proto.Field( proto.MESSAGE, number=8, message=duration.Duration, ) - labels = proto.MapField(proto.STRING, proto.STRING, number=9) + 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", @@ -709,7 +709,7 @@ class OidcToken(proto.Message): audience = proto.Field(proto.STRING, number=2,) push_endpoint = proto.Field(proto.STRING, number=1,) - attributes = proto.MapField(proto.STRING, proto.STRING, number=2) + attributes = proto.MapField(proto.STRING, proto.STRING, number=2,) oidc_token = proto.Field( proto.MESSAGE, number=3, oneof="authentication_method", message=OidcToken, ) @@ -1072,7 +1072,7 @@ class CreateSnapshotRequest(proto.Message): name = proto.Field(proto.STRING, number=1,) subscription = proto.Field(proto.STRING, number=2,) - labels = proto.MapField(proto.STRING, proto.STRING, number=3) + labels = proto.MapField(proto.STRING, proto.STRING, number=3,) class UpdateSnapshotRequest(proto.Message): @@ -1125,7 +1125,7 @@ class Snapshot(proto.Message): name = proto.Field(proto.STRING, number=1,) topic = proto.Field(proto.STRING, number=2,) expire_time = proto.Field(proto.MESSAGE, number=3, message=timestamp.Timestamp,) - labels = proto.MapField(proto.STRING, proto.STRING, number=4) + labels = proto.MapField(proto.STRING, proto.STRING, number=4,) class GetSnapshotRequest(proto.Message): diff --git a/synth.metadata b/synth.metadata index 3d70c7ba3..b53578ba5 100644 --- a/synth.metadata +++ b/synth.metadata @@ -11,8 +11,8 @@ "git": { "name": "googleapis", "remote": "https://github.com/googleapis/googleapis.git", - "sha": "60e129d0672a1be2c70b41bf76aadc7ad1b1ca0f", - "internalRef": "370525906" + "sha": "382ed8de075e1ddc9baa4ebf8dbc5b2c257a77b8", + "internalRef": "370926454" } } ], diff --git a/tests/unit/gapic/pubsub_v1/test_publisher.py b/tests/unit/gapic/pubsub_v1/test_publisher.py index 159f07af2..c550d6186 100644 --- a/tests/unit/gapic/pubsub_v1/test_publisher.py +++ b/tests/unit/gapic/pubsub_v1/test_publisher.py @@ -2769,7 +2769,7 @@ def test_publisher_transport_create_channel(transport_class, grpc_helpers): transport_class(quota_project_id="octopus", scopes=["1", "2"]) create_channel.assert_called_with( - "pubsub.googleapis.com", + "pubsub.googleapis.com:443", credentials=creds, credentials_file=None, quota_project_id="octopus", diff --git a/tests/unit/gapic/pubsub_v1/test_schema_service.py b/tests/unit/gapic/pubsub_v1/test_schema_service.py index d3f206ea2..1c1610f66 100644 --- a/tests/unit/gapic/pubsub_v1/test_schema_service.py +++ b/tests/unit/gapic/pubsub_v1/test_schema_service.py @@ -1996,7 +1996,7 @@ def test_schema_service_transport_create_channel(transport_class, grpc_helpers): transport_class(quota_project_id="octopus", scopes=["1", "2"]) create_channel.assert_called_with( - "pubsub.googleapis.com", + "pubsub.googleapis.com:443", credentials=creds, credentials_file=None, quota_project_id="octopus", diff --git a/tests/unit/gapic/pubsub_v1/test_subscriber.py b/tests/unit/gapic/pubsub_v1/test_subscriber.py index f83661f03..eb4acac24 100644 --- a/tests/unit/gapic/pubsub_v1/test_subscriber.py +++ b/tests/unit/gapic/pubsub_v1/test_subscriber.py @@ -4046,7 +4046,7 @@ def test_subscriber_transport_create_channel(transport_class, grpc_helpers): transport_class(quota_project_id="octopus", scopes=["1", "2"]) create_channel.assert_called_with( - "pubsub.googleapis.com", + "pubsub.googleapis.com:443", credentials=creds, credentials_file=None, quota_project_id="octopus", From b2a7a66af8ea1997ddbd4c4819cd5e26217279eb Mon Sep 17 00:00:00 2001 From: yoshi-automation Date: Sun, 18 Jul 2021 04:49:59 +0000 Subject: [PATCH 04/18] chore: upgrade gapic-generator python to 0.44.1 PiperOrigin-RevId: 370989216 Source-Author: Google APIs Source-Date: Wed Apr 28 14:42:12 2021 -0700 Source-Repo: googleapis/googleapis Source-Sha: 4e825559e5ab242c4d1aafca19c83c4d1bac743e Source-Link: https://github.com/googleapis/googleapis/commit/4e825559e5ab242c4d1aafca19c83c4d1bac743e --- google/pubsub/__init__.py | 47 +++++++------- google/pubsub_v1/__init__.py | 34 +++++----- .../services/publisher/async_client.py | 27 +++++--- google/pubsub_v1/services/publisher/client.py | 27 +++++--- .../services/publisher/transports/grpc.py | 36 ++++++++--- .../publisher/transports/grpc_asyncio.py | 36 ++++++++--- .../services/schema_service/async_client.py | 18 ++++-- .../services/schema_service/client.py | 18 ++++-- .../schema_service/transports/grpc.py | 24 +++++-- .../schema_service/transports/grpc_asyncio.py | 24 +++++-- .../services/subscriber/async_client.py | 48 +++++++++----- .../pubsub_v1/services/subscriber/client.py | 48 +++++++++----- .../services/subscriber/transports/grpc.py | 64 ++++++++++++++----- .../subscriber/transports/grpc_asyncio.py | 64 ++++++++++++++----- google/pubsub_v1/types/pubsub.py | 12 ++-- synth.metadata | 4 +- tests/unit/gapic/pubsub_v1/test_publisher.py | 2 +- .../gapic/pubsub_v1/test_schema_service.py | 2 +- tests/unit/gapic/pubsub_v1/test_subscriber.py | 2 +- 19 files changed, 361 insertions(+), 176 deletions(-) diff --git a/google/pubsub/__init__.py b/google/pubsub/__init__.py index dfa5c7e04..5529b3ca6 100644 --- a/google/pubsub/__init__.py +++ b/google/pubsub/__init__.py @@ -14,15 +14,14 @@ # 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.publisher.client import PublisherClient 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.schema_service.client import SchemaServiceClient from google.pubsub_v1.services.subscriber.async_client import SubscriberAsyncClient - +from google.pubsub_v1.services.subscriber.client import SubscriberClient from google.pubsub_v1.types.pubsub import AcknowledgeRequest from google.pubsub_v1.types.pubsub import CreateSnapshotRequest from google.pubsub_v1.types.pubsub import DeadLetterPolicy @@ -41,10 +40,10 @@ 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 ListTopicsRequest +from google.pubsub_v1.types.pubsub import ListTopicsResponse from google.pubsub_v1.types.pubsub import MessageStoragePolicy from google.pubsub_v1.types.pubsub import ModifyAckDeadlineRequest from google.pubsub_v1.types.pubsub import ModifyPushConfigRequest @@ -69,78 +68,78 @@ 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 Encoding 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 SchemaView 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", + "CreateSchemaRequest", "CreateSnapshotRequest", "DeadLetterPolicy", + "DeleteSchemaRequest", "DeleteSnapshotRequest", "DeleteSubscriptionRequest", "DeleteTopicRequest", "DetachSubscriptionRequest", "DetachSubscriptionResponse", + "Encoding", "ExpirationPolicy", + "GetSchemaRequest", "GetSnapshotRequest", "GetSubscriptionRequest", "GetTopicRequest", + "ListSchemasRequest", + "ListSchemasResponse", "ListSnapshotsRequest", "ListSnapshotsResponse", "ListSubscriptionsRequest", "ListSubscriptionsResponse", "ListTopicSnapshotsRequest", "ListTopicSnapshotsResponse", - "ListTopicsRequest", - "ListTopicsResponse", "ListTopicSubscriptionsRequest", "ListTopicSubscriptionsResponse", + "ListTopicsRequest", + "ListTopicsResponse", "MessageStoragePolicy", "ModifyAckDeadlineRequest", "ModifyPushConfigRequest", "PublishRequest", "PublishResponse", + "PublisherAsyncClient", + "PublisherClient", "PubsubMessage", "PullRequest", "PullResponse", "PushConfig", "ReceivedMessage", "RetryPolicy", + "Schema", + "SchemaServiceAsyncClient", + "SchemaServiceClient", "SchemaSettings", + "SchemaView", "SeekRequest", "SeekResponse", "Snapshot", "StreamingPullRequest", "StreamingPullResponse", + "SubscriberAsyncClient", + "SubscriberClient", "Subscription", "Topic", "UpdateSnapshotRequest", "UpdateSubscriptionRequest", "UpdateTopicRequest", - "CreateSchemaRequest", - "DeleteSchemaRequest", - "GetSchemaRequest", - "ListSchemasRequest", - "ListSchemasResponse", - "Schema", "ValidateMessageRequest", "ValidateMessageResponse", "ValidateSchemaRequest", "ValidateSchemaResponse", - "Encoding", - "SchemaView", ) diff --git a/google/pubsub_v1/__init__.py b/google/pubsub_v1/__init__.py index 86592af86..33fca22fc 100644 --- a/google/pubsub_v1/__init__.py +++ b/google/pubsub_v1/__init__.py @@ -36,10 +36,10 @@ 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 ListTopicsRequest +from .types.pubsub import ListTopicsResponse from .types.pubsub import MessageStoragePolicy from .types.pubsub import ModifyAckDeadlineRequest from .types.pubsub import ModifyPushConfigRequest @@ -64,43 +64,46 @@ from .types.pubsub import UpdateTopicRequest from .types.schema import CreateSchemaRequest from .types.schema import DeleteSchemaRequest +from .types.schema import Encoding from .types.schema import GetSchemaRequest from .types.schema import ListSchemasRequest from .types.schema import ListSchemasResponse from .types.schema import Schema +from .types.schema import SchemaView 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__ = ( - "PublisherClient", - "SchemaServiceClient", - "SubscriberClient", "AcknowledgeRequest", + "CreateSchemaRequest", "CreateSnapshotRequest", "DeadLetterPolicy", + "DeleteSchemaRequest", "DeleteSnapshotRequest", "DeleteSubscriptionRequest", "DeleteTopicRequest", "DetachSubscriptionRequest", "DetachSubscriptionResponse", + "Encoding", "ExpirationPolicy", + "GetSchemaRequest", "GetSnapshotRequest", "GetSubscriptionRequest", "GetTopicRequest", + "ListSchemasRequest", + "ListSchemasResponse", "ListSnapshotsRequest", "ListSnapshotsResponse", "ListSubscriptionsRequest", "ListSubscriptionsResponse", "ListTopicSnapshotsRequest", "ListTopicSnapshotsResponse", - "ListTopicsRequest", - "ListTopicsResponse", "ListTopicSubscriptionsRequest", "ListTopicSubscriptionsResponse", + "ListTopicsRequest", + "ListTopicsResponse", "MessageStoragePolicy", "ModifyAckDeadlineRequest", "ModifyPushConfigRequest", @@ -112,27 +115,24 @@ "PushConfig", "ReceivedMessage", "RetryPolicy", + "Schema", + "SchemaServiceClient", "SchemaSettings", + "SchemaView", "SeekRequest", "SeekResponse", "Snapshot", "StreamingPullRequest", "StreamingPullResponse", + "SubscriberClient", "Subscription", "Topic", "UpdateSnapshotRequest", "UpdateSubscriptionRequest", "UpdateTopicRequest", - "CreateSchemaRequest", - "DeleteSchemaRequest", - "GetSchemaRequest", - "ListSchemasRequest", - "ListSchemasResponse", - "Schema", "ValidateMessageRequest", "ValidateMessageResponse", "ValidateSchemaRequest", "ValidateSchemaResponse", - "Encoding", - "SchemaView", + "PublisherClient", ) diff --git a/google/pubsub_v1/services/publisher/async_client.py b/google/pubsub_v1/services/publisher/async_client.py index 2fc70ae1f..9311b05e4 100644 --- a/google/pubsub_v1/services/publisher/async_client.py +++ b/google/pubsub_v1/services/publisher/async_client.py @@ -179,7 +179,8 @@ async def create_topic( Args: request (:class:`google.pubsub_v1.types.Topic`): - The request object. A topic resource. + 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}`` @@ -261,7 +262,8 @@ async def update_topic( Args: request (:class:`google.pubsub_v1.types.UpdateTopicRequest`): - The request object. Request for the UpdateTopic method. + The request object. + Request for the UpdateTopic method. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (TimeoutType): @@ -320,7 +322,8 @@ async def publish( Args: request (:class:`google.pubsub_v1.types.PublishRequest`): - The request object. Request for the Publish method. + 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 @@ -412,7 +415,8 @@ async def get_topic( Args: request (:class:`google.pubsub_v1.types.GetTopicRequest`): - The request object. Request for the GetTopic method. + 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}``. @@ -492,7 +496,8 @@ async def list_topics( Args: request (:class:`google.pubsub_v1.types.ListTopicsRequest`): - The request object. Request for the `ListTopics` method. + 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}``. @@ -583,7 +588,8 @@ async def list_topic_subscriptions( Args: request (:class:`google.pubsub_v1.types.ListTopicSubscriptionsRequest`): - The request object. Request for the + The request object. + Request for the `ListTopicSubscriptions` method. topic (:class:`str`): Required. The name of the topic that subscriptions are @@ -680,7 +686,8 @@ async def list_topic_snapshots( Args: request (:class:`google.pubsub_v1.types.ListTopicSnapshotsRequest`): - The request object. Request for the `ListTopicSnapshots` + The request object. + Request for the `ListTopicSnapshots` method. topic (:class:`str`): Required. The name of the topic that snapshots are @@ -777,7 +784,8 @@ async def delete_topic( Args: request (:class:`google.pubsub_v1.types.DeleteTopicRequest`): - The request object. Request for the `DeleteTopic` + The request object. + Request for the `DeleteTopic` method. topic (:class:`str`): Required. Name of the topic to delete. Format is @@ -852,7 +860,8 @@ async def detach_subscription( Args: request (:class:`google.pubsub_v1.types.DetachSubscriptionRequest`): - The request object. Request for the DetachSubscription + The request object. + Request for the DetachSubscription method. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. diff --git a/google/pubsub_v1/services/publisher/client.py b/google/pubsub_v1/services/publisher/client.py index 6a9df86cd..736f3e3ce 100644 --- a/google/pubsub_v1/services/publisher/client.py +++ b/google/pubsub_v1/services/publisher/client.py @@ -410,7 +410,8 @@ def create_topic( Args: request (google.pubsub_v1.types.Topic): - The request object. A topic resource. + The request object. + A topic resource. name (str): Required. The name of the topic. It must have the format ``"projects/{project}/topics/{topic}"``. ``{topic}`` @@ -486,7 +487,8 @@ def update_topic( Args: request (google.pubsub_v1.types.UpdateTopicRequest): - The request object. Request for the UpdateTopic method. + The request object. + Request for the UpdateTopic method. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (TimeoutType): @@ -540,7 +542,8 @@ def publish( Args: request (google.pubsub_v1.types.PublishRequest): - The request object. Request for the Publish method. + The request object. + Request for the Publish method. topic (str): Required. The messages in the request will be published on this topic. Format is @@ -618,7 +621,8 @@ def get_topic( Args: request (google.pubsub_v1.types.GetTopicRequest): - The request object. Request for the GetTopic method. + The request object. + Request for the GetTopic method. topic (str): Required. The name of the topic to get. Format is ``projects/{project}/topics/{topic}``. @@ -688,7 +692,8 @@ def list_topics( Args: request (google.pubsub_v1.types.ListTopicsRequest): - The request object. Request for the `ListTopics` method. + 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}``. @@ -769,7 +774,8 @@ def list_topic_subscriptions( Args: request (google.pubsub_v1.types.ListTopicSubscriptionsRequest): - The request object. Request for the + The request object. + Request for the `ListTopicSubscriptions` method. topic (str): Required. The name of the topic that subscriptions are @@ -856,7 +862,8 @@ def list_topic_snapshots( Args: request (google.pubsub_v1.types.ListTopicSnapshotsRequest): - The request object. Request for the `ListTopicSnapshots` + The request object. + Request for the `ListTopicSnapshots` method. topic (str): Required. The name of the topic that snapshots are @@ -943,7 +950,8 @@ def delete_topic( Args: request (google.pubsub_v1.types.DeleteTopicRequest): - The request object. Request for the `DeleteTopic` + The request object. + Request for the `DeleteTopic` method. topic (str): Required. Name of the topic to delete. Format is @@ -1012,7 +1020,8 @@ def detach_subscription( Args: request (google.pubsub_v1.types.DetachSubscriptionRequest): - The request object. Request for the DetachSubscription + The request object. + Request for the DetachSubscription method. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. diff --git a/google/pubsub_v1/services/publisher/transports/grpc.py b/google/pubsub_v1/services/publisher/transports/grpc.py index a0e5c8773..2e6acea4d 100644 --- a/google/pubsub_v1/services/publisher/transports/grpc.py +++ b/google/pubsub_v1/services/publisher/transports/grpc.py @@ -228,7 +228,9 @@ def grpc_channel(self) -> grpc.Channel: @property def create_topic(self) -> Callable[[pubsub.Topic], pubsub.Topic]: - r"""Return a callable for the create topic method over gRPC. + r"""Return a callable for the + create topic + method over gRPC. Creates the given topic with the given name. See the [resource name rules] @@ -254,7 +256,9 @@ def create_topic(self) -> Callable[[pubsub.Topic], pubsub.Topic]: @property def update_topic(self) -> Callable[[pubsub.UpdateTopicRequest], pubsub.Topic]: - r"""Return a callable for the update topic method over gRPC. + 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. @@ -279,7 +283,9 @@ def update_topic(self) -> Callable[[pubsub.UpdateTopicRequest], pubsub.Topic]: @property def publish(self) -> Callable[[pubsub.PublishRequest], pubsub.PublishResponse]: - r"""Return a callable for the publish method over gRPC. + 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. @@ -304,7 +310,9 @@ def publish(self) -> Callable[[pubsub.PublishRequest], pubsub.PublishResponse]: @property def get_topic(self) -> Callable[[pubsub.GetTopicRequest], pubsub.Topic]: - r"""Return a callable for the get topic method over gRPC. + r"""Return a callable for the + get topic + method over gRPC. Gets the configuration of a topic. @@ -330,7 +338,9 @@ def get_topic(self) -> Callable[[pubsub.GetTopicRequest], pubsub.Topic]: def list_topics( self, ) -> Callable[[pubsub.ListTopicsRequest], pubsub.ListTopicsResponse]: - r"""Return a callable for the list topics method over gRPC. + r"""Return a callable for the + list topics + method over gRPC. Lists matching topics. @@ -358,7 +368,9 @@ def list_topic_subscriptions( ) -> Callable[ [pubsub.ListTopicSubscriptionsRequest], pubsub.ListTopicSubscriptionsResponse ]: - r"""Return a callable for the list topic subscriptions method over gRPC. + r"""Return a callable for the + list topic subscriptions + method over gRPC. Lists the names of the attached subscriptions on this topic. @@ -387,7 +399,9 @@ def list_topic_snapshots( ) -> Callable[ [pubsub.ListTopicSnapshotsRequest], pubsub.ListTopicSnapshotsResponse ]: - r"""Return a callable for the list topic snapshots method over gRPC. + 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 @@ -416,7 +430,9 @@ def list_topic_snapshots( @property def delete_topic(self) -> Callable[[pubsub.DeleteTopicRequest], empty.Empty]: - r"""Return a callable for the delete topic method over gRPC. + 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 @@ -449,7 +465,9 @@ def detach_subscription( ) -> Callable[ [pubsub.DetachSubscriptionRequest], pubsub.DetachSubscriptionResponse ]: - r"""Return a callable for the detach subscription method over gRPC. + 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 diff --git a/google/pubsub_v1/services/publisher/transports/grpc_asyncio.py b/google/pubsub_v1/services/publisher/transports/grpc_asyncio.py index 626bdd93a..64250b7c3 100644 --- a/google/pubsub_v1/services/publisher/transports/grpc_asyncio.py +++ b/google/pubsub_v1/services/publisher/transports/grpc_asyncio.py @@ -232,7 +232,9 @@ def grpc_channel(self) -> aio.Channel: @property def create_topic(self) -> Callable[[pubsub.Topic], Awaitable[pubsub.Topic]]: - r"""Return a callable for the create topic method over gRPC. + r"""Return a callable for the + create topic + method over gRPC. Creates the given topic with the given name. See the [resource name rules] @@ -260,7 +262,9 @@ def create_topic(self) -> Callable[[pubsub.Topic], Awaitable[pubsub.Topic]]: def update_topic( self, ) -> Callable[[pubsub.UpdateTopicRequest], Awaitable[pubsub.Topic]]: - r"""Return a callable for the update topic method over gRPC. + 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. @@ -287,7 +291,9 @@ def update_topic( def publish( self, ) -> Callable[[pubsub.PublishRequest], Awaitable[pubsub.PublishResponse]]: - r"""Return a callable for the publish method over gRPC. + 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. @@ -312,7 +318,9 @@ def publish( @property def get_topic(self) -> Callable[[pubsub.GetTopicRequest], Awaitable[pubsub.Topic]]: - r"""Return a callable for the get topic method over gRPC. + r"""Return a callable for the + get topic + method over gRPC. Gets the configuration of a topic. @@ -338,7 +346,9 @@ def get_topic(self) -> Callable[[pubsub.GetTopicRequest], Awaitable[pubsub.Topic def list_topics( self, ) -> Callable[[pubsub.ListTopicsRequest], Awaitable[pubsub.ListTopicsResponse]]: - r"""Return a callable for the list topics method over gRPC. + r"""Return a callable for the + list topics + method over gRPC. Lists matching topics. @@ -367,7 +377,9 @@ def list_topic_subscriptions( [pubsub.ListTopicSubscriptionsRequest], Awaitable[pubsub.ListTopicSubscriptionsResponse], ]: - r"""Return a callable for the list topic subscriptions method over gRPC. + r"""Return a callable for the + list topic subscriptions + method over gRPC. Lists the names of the attached subscriptions on this topic. @@ -396,7 +408,9 @@ def list_topic_snapshots( ) -> Callable[ [pubsub.ListTopicSnapshotsRequest], Awaitable[pubsub.ListTopicSnapshotsResponse] ]: - r"""Return a callable for the list topic snapshots method over gRPC. + 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 @@ -427,7 +441,9 @@ def list_topic_snapshots( def delete_topic( self, ) -> Callable[[pubsub.DeleteTopicRequest], Awaitable[empty.Empty]]: - r"""Return a callable for the delete topic method over gRPC. + 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 @@ -460,7 +476,9 @@ def detach_subscription( ) -> Callable[ [pubsub.DetachSubscriptionRequest], Awaitable[pubsub.DetachSubscriptionResponse] ]: - r"""Return a callable for the detach subscription method over gRPC. + 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 diff --git a/google/pubsub_v1/services/schema_service/async_client.py b/google/pubsub_v1/services/schema_service/async_client.py index 43c8139f5..4cfc74e81 100644 --- a/google/pubsub_v1/services/schema_service/async_client.py +++ b/google/pubsub_v1/services/schema_service/async_client.py @@ -178,7 +178,8 @@ async def create_schema( Args: request (:class:`google.pubsub_v1.types.CreateSchemaRequest`): - The request object. Request for the CreateSchema method. + 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}``. @@ -271,7 +272,8 @@ async def get_schema( Args: request (:class:`google.pubsub_v1.types.GetSchemaRequest`): - The request object. Request for the GetSchema method. + 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}``. @@ -339,7 +341,8 @@ async def list_schemas( Args: request (:class:`google.pubsub_v1.types.ListSchemasRequest`): - The request object. Request for the `ListSchemas` + The request object. + Request for the `ListSchemas` method. parent (:class:`str`): Required. The name of the project in which to list @@ -418,7 +421,8 @@ async def delete_schema( Args: request (:class:`google.pubsub_v1.types.DeleteSchemaRequest`): - The request object. Request for the `DeleteSchema` + The request object. + Request for the `DeleteSchema` method. name (:class:`str`): Required. Name of the schema to delete. Format is @@ -483,7 +487,8 @@ async def validate_schema( Args: request (:class:`google.pubsub_v1.types.ValidateSchemaRequest`): - The request object. Request for the `ValidateSchema` + The request object. + Request for the `ValidateSchema` method. parent (:class:`str`): Required. The name of the project in which to validate @@ -560,7 +565,8 @@ async def validate_message( Args: request (:class:`google.pubsub_v1.types.ValidateMessageRequest`): - The request object. Request for the `ValidateMessage` + The request object. + Request for the `ValidateMessage` method. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. diff --git a/google/pubsub_v1/services/schema_service/client.py b/google/pubsub_v1/services/schema_service/client.py index fc735a4e1..cb85dbd51 100644 --- a/google/pubsub_v1/services/schema_service/client.py +++ b/google/pubsub_v1/services/schema_service/client.py @@ -353,7 +353,8 @@ def create_schema( Args: request (google.pubsub_v1.types.CreateSchemaRequest): - The request object. Request for the CreateSchema method. + 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}``. @@ -446,7 +447,8 @@ def get_schema( Args: request (google.pubsub_v1.types.GetSchemaRequest): - The request object. Request for the GetSchema method. + The request object. + Request for the GetSchema method. name (str): Required. The name of the schema to get. Format is ``projects/{project}/schemas/{schema}``. @@ -514,7 +516,8 @@ def list_schemas( Args: request (google.pubsub_v1.types.ListSchemasRequest): - The request object. Request for the `ListSchemas` + The request object. + Request for the `ListSchemas` method. parent (str): Required. The name of the project in which to list @@ -593,7 +596,8 @@ def delete_schema( Args: request (google.pubsub_v1.types.DeleteSchemaRequest): - The request object. Request for the `DeleteSchema` + The request object. + Request for the `DeleteSchema` method. name (str): Required. Name of the schema to delete. Format is @@ -658,7 +662,8 @@ def validate_schema( Args: request (google.pubsub_v1.types.ValidateSchemaRequest): - The request object. Request for the `ValidateSchema` + The request object. + Request for the `ValidateSchema` method. parent (str): Required. The name of the project in which to validate @@ -735,7 +740,8 @@ def validate_message( Args: request (google.pubsub_v1.types.ValidateMessageRequest): - The request object. Request for the `ValidateMessage` + The request object. + Request for the `ValidateMessage` method. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. diff --git a/google/pubsub_v1/services/schema_service/transports/grpc.py b/google/pubsub_v1/services/schema_service/transports/grpc.py index f6eb42dce..55967e792 100644 --- a/google/pubsub_v1/services/schema_service/transports/grpc.py +++ b/google/pubsub_v1/services/schema_service/transports/grpc.py @@ -230,7 +230,9 @@ def grpc_channel(self) -> grpc.Channel: def create_schema( self, ) -> Callable[[gp_schema.CreateSchemaRequest], gp_schema.Schema]: - r"""Return a callable for the create schema method over gRPC. + r"""Return a callable for the + create schema + method over gRPC. Creates a schema. @@ -254,7 +256,9 @@ def create_schema( @property def get_schema(self) -> Callable[[schema.GetSchemaRequest], schema.Schema]: - r"""Return a callable for the get schema method over gRPC. + r"""Return a callable for the + get schema + method over gRPC. Gets a schema. @@ -280,7 +284,9 @@ def get_schema(self) -> Callable[[schema.GetSchemaRequest], schema.Schema]: def list_schemas( self, ) -> Callable[[schema.ListSchemasRequest], schema.ListSchemasResponse]: - r"""Return a callable for the list schemas method over gRPC. + r"""Return a callable for the + list schemas + method over gRPC. Lists schemas in a project. @@ -304,7 +310,9 @@ def list_schemas( @property def delete_schema(self) -> Callable[[schema.DeleteSchemaRequest], empty.Empty]: - r"""Return a callable for the delete schema method over gRPC. + r"""Return a callable for the + delete schema + method over gRPC. Deletes a schema. @@ -330,7 +338,9 @@ def delete_schema(self) -> Callable[[schema.DeleteSchemaRequest], empty.Empty]: def validate_schema( self, ) -> Callable[[gp_schema.ValidateSchemaRequest], gp_schema.ValidateSchemaResponse]: - r"""Return a callable for the validate schema method over gRPC. + r"""Return a callable for the + validate schema + method over gRPC. Validates a schema. @@ -356,7 +366,9 @@ def validate_schema( def validate_message( self, ) -> Callable[[schema.ValidateMessageRequest], schema.ValidateMessageResponse]: - r"""Return a callable for the validate message method over gRPC. + r"""Return a callable for the + validate message + method over gRPC. Validates a message against a schema. diff --git a/google/pubsub_v1/services/schema_service/transports/grpc_asyncio.py b/google/pubsub_v1/services/schema_service/transports/grpc_asyncio.py index 8e8fc22ce..957b402d0 100644 --- a/google/pubsub_v1/services/schema_service/transports/grpc_asyncio.py +++ b/google/pubsub_v1/services/schema_service/transports/grpc_asyncio.py @@ -234,7 +234,9 @@ def grpc_channel(self) -> aio.Channel: def create_schema( self, ) -> Callable[[gp_schema.CreateSchemaRequest], Awaitable[gp_schema.Schema]]: - r"""Return a callable for the create schema method over gRPC. + r"""Return a callable for the + create schema + method over gRPC. Creates a schema. @@ -260,7 +262,9 @@ def create_schema( def get_schema( self, ) -> Callable[[schema.GetSchemaRequest], Awaitable[schema.Schema]]: - r"""Return a callable for the get schema method over gRPC. + r"""Return a callable for the + get schema + method over gRPC. Gets a schema. @@ -286,7 +290,9 @@ def get_schema( def list_schemas( self, ) -> Callable[[schema.ListSchemasRequest], Awaitable[schema.ListSchemasResponse]]: - r"""Return a callable for the list schemas method over gRPC. + r"""Return a callable for the + list schemas + method over gRPC. Lists schemas in a project. @@ -312,7 +318,9 @@ def list_schemas( def delete_schema( self, ) -> Callable[[schema.DeleteSchemaRequest], Awaitable[empty.Empty]]: - r"""Return a callable for the delete schema method over gRPC. + r"""Return a callable for the + delete schema + method over gRPC. Deletes a schema. @@ -340,7 +348,9 @@ def validate_schema( ) -> Callable[ [gp_schema.ValidateSchemaRequest], Awaitable[gp_schema.ValidateSchemaResponse] ]: - r"""Return a callable for the validate schema method over gRPC. + r"""Return a callable for the + validate schema + method over gRPC. Validates a schema. @@ -368,7 +378,9 @@ def validate_message( ) -> Callable[ [schema.ValidateMessageRequest], Awaitable[schema.ValidateMessageResponse] ]: - r"""Return a callable for the validate message method over gRPC. + r"""Return a callable for the + validate message + method over gRPC. Validates a message against a schema. diff --git a/google/pubsub_v1/services/subscriber/async_client.py b/google/pubsub_v1/services/subscriber/async_client.py index 1a6b0cfbf..781df6d4c 100644 --- a/google/pubsub_v1/services/subscriber/async_client.py +++ b/google/pubsub_v1/services/subscriber/async_client.py @@ -204,7 +204,8 @@ async def create_subscription( Args: request (:class:`google.pubsub_v1.types.Subscription`): - The request object. A subscription resource. + The request object. + A subscription resource. name (:class:`str`): Required. The name of the subscription. It must have the format @@ -344,7 +345,8 @@ async def get_subscription( Args: request (:class:`google.pubsub_v1.types.GetSubscriptionRequest`): - The request object. Request for the GetSubscription + The request object. + Request for the GetSubscription method. subscription (:class:`str`): Required. The name of the subscription to get. Format is @@ -427,7 +429,8 @@ async def update_subscription( Args: request (:class:`google.pubsub_v1.types.UpdateSubscriptionRequest`): - The request object. Request for the UpdateSubscription + The request object. + Request for the UpdateSubscription method. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. @@ -484,7 +487,8 @@ async def list_subscriptions( Args: request (:class:`google.pubsub_v1.types.ListSubscriptionsRequest`): - The request object. Request for the `ListSubscriptions` + The request object. + Request for the `ListSubscriptions` method. project (:class:`str`): Required. The name of the project in which to list @@ -579,7 +583,8 @@ async def delete_subscription( Args: request (:class:`google.pubsub_v1.types.DeleteSubscriptionRequest`): - The request object. Request for the DeleteSubscription + The request object. + Request for the DeleteSubscription method. subscription (:class:`str`): Required. The subscription to delete. Format is @@ -659,7 +664,8 @@ async def modify_ack_deadline( Args: request (:class:`google.pubsub_v1.types.ModifyAckDeadlineRequest`): - The request object. Request for the ModifyAckDeadline + The request object. + Request for the ModifyAckDeadline method. subscription (:class:`str`): Required. The name of the subscription. Format is @@ -765,7 +771,8 @@ async def acknowledge( Args: request (:class:`google.pubsub_v1.types.AcknowledgeRequest`): - The request object. Request for the Acknowledge method. + The request object. + Request for the Acknowledge method. subscription (:class:`str`): Required. The subscription whose message is being acknowledged. Format is @@ -852,7 +859,8 @@ async def pull( Args: request (:class:`google.pubsub_v1.types.PullRequest`): - The request object. Request for the `Pull` method. + The request object. + Request for the `Pull` method. subscription (:class:`str`): Required. The subscription from which messages should be pulled. Format is @@ -974,7 +982,8 @@ def streaming_pull( Args: requests (AsyncIterator[`google.pubsub_v1.types.StreamingPullRequest`]): - The request object AsyncIterator. Request for the `StreamingPull` + 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 @@ -1039,7 +1048,8 @@ async def modify_push_config( Args: request (:class:`google.pubsub_v1.types.ModifyPushConfigRequest`): - The request object. Request for the ModifyPushConfig + The request object. + Request for the ModifyPushConfig method. subscription (:class:`str`): Required. The name of the subscription. Format is @@ -1132,7 +1142,8 @@ async def get_snapshot( Args: request (:class:`google.pubsub_v1.types.GetSnapshotRequest`): - The request object. Request for the GetSnapshot method. + 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}``. @@ -1221,7 +1232,8 @@ async def list_snapshots( Args: request (:class:`google.pubsub_v1.types.ListSnapshotsRequest`): - The request object. Request for the `ListSnapshots` + The request object. + Request for the `ListSnapshots` method. project (:class:`str`): Required. The name of the project in which to list @@ -1330,7 +1342,8 @@ async def create_snapshot( Args: request (:class:`google.pubsub_v1.types.CreateSnapshotRequest`): - The request object. Request for the `CreateSnapshot` + The request object. + Request for the `CreateSnapshot` method. name (:class:`str`): Required. User-provided name for this snapshot. If the @@ -1439,7 +1452,8 @@ async def update_snapshot( Args: request (:class:`google.pubsub_v1.types.UpdateSnapshotRequest`): - The request object. Request for the UpdateSnapshot + The request object. + Request for the UpdateSnapshot method. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. @@ -1511,7 +1525,8 @@ async def delete_snapshot( Args: request (:class:`google.pubsub_v1.types.DeleteSnapshotRequest`): - The request object. Request for the `DeleteSnapshot` + The request object. + Request for the `DeleteSnapshot` method. snapshot (:class:`str`): Required. The name of the snapshot to delete. Format is @@ -1589,7 +1604,8 @@ async def seek( Args: request (:class:`google.pubsub_v1.types.SeekRequest`): - The request object. Request for the `Seek` method. + 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. diff --git a/google/pubsub_v1/services/subscriber/client.py b/google/pubsub_v1/services/subscriber/client.py index 3c8899352..b9c988159 100644 --- a/google/pubsub_v1/services/subscriber/client.py +++ b/google/pubsub_v1/services/subscriber/client.py @@ -436,7 +436,8 @@ def create_subscription( Args: request (google.pubsub_v1.types.Subscription): - The request object. A subscription resource. + The request object. + A subscription resource. name (str): Required. The name of the subscription. It must have the format @@ -566,7 +567,8 @@ def get_subscription( Args: request (google.pubsub_v1.types.GetSubscriptionRequest): - The request object. Request for the GetSubscription + The request object. + Request for the GetSubscription method. subscription (str): Required. The name of the subscription to get. Format is @@ -639,7 +641,8 @@ def update_subscription( Args: request (google.pubsub_v1.types.UpdateSubscriptionRequest): - The request object. Request for the UpdateSubscription + The request object. + Request for the UpdateSubscription method. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. @@ -691,7 +694,8 @@ def list_subscriptions( Args: request (google.pubsub_v1.types.ListSubscriptionsRequest): - The request object. Request for the `ListSubscriptions` + The request object. + Request for the `ListSubscriptions` method. project (str): Required. The name of the project in which to list @@ -776,7 +780,8 @@ def delete_subscription( Args: request (google.pubsub_v1.types.DeleteSubscriptionRequest): - The request object. Request for the DeleteSubscription + The request object. + Request for the DeleteSubscription method. subscription (str): Required. The subscription to delete. Format is @@ -850,7 +855,8 @@ def modify_ack_deadline( Args: request (google.pubsub_v1.types.ModifyAckDeadlineRequest): - The request object. Request for the ModifyAckDeadline + The request object. + Request for the ModifyAckDeadline method. subscription (str): Required. The name of the subscription. Format is @@ -950,7 +956,8 @@ def acknowledge( Args: request (google.pubsub_v1.types.AcknowledgeRequest): - The request object. Request for the Acknowledge method. + The request object. + Request for the Acknowledge method. subscription (str): Required. The subscription whose message is being acknowledged. Format is @@ -1031,7 +1038,8 @@ def pull( Args: request (google.pubsub_v1.types.PullRequest): - The request object. Request for the `Pull` method. + The request object. + Request for the `Pull` method. subscription (str): Required. The subscription from which messages should be pulled. Format is @@ -1143,7 +1151,8 @@ def streaming_pull( Args: requests (Iterator[google.pubsub_v1.types.StreamingPullRequest]): - The request object iterator. Request for the `StreamingPull` + 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 @@ -1197,7 +1206,8 @@ def modify_push_config( Args: request (google.pubsub_v1.types.ModifyPushConfigRequest): - The request object. Request for the ModifyPushConfig + The request object. + Request for the ModifyPushConfig method. subscription (str): Required. The name of the subscription. Format is @@ -1284,7 +1294,8 @@ def get_snapshot( Args: request (google.pubsub_v1.types.GetSnapshotRequest): - The request object. Request for the GetSnapshot method. + The request object. + Request for the GetSnapshot method. snapshot (str): Required. The name of the snapshot to get. Format is ``projects/{project}/snapshots/{snap}``. @@ -1363,7 +1374,8 @@ def list_snapshots( Args: request (google.pubsub_v1.types.ListSnapshotsRequest): - The request object. Request for the `ListSnapshots` + The request object. + Request for the `ListSnapshots` method. project (str): Required. The name of the project in which to list @@ -1462,7 +1474,8 @@ def create_snapshot( Args: request (google.pubsub_v1.types.CreateSnapshotRequest): - The request object. Request for the `CreateSnapshot` + The request object. + Request for the `CreateSnapshot` method. name (str): Required. User-provided name for this snapshot. If the @@ -1565,7 +1578,8 @@ def update_snapshot( Args: request (google.pubsub_v1.types.UpdateSnapshotRequest): - The request object. Request for the UpdateSnapshot + The request object. + Request for the UpdateSnapshot method. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. @@ -1632,7 +1646,8 @@ def delete_snapshot( Args: request (google.pubsub_v1.types.DeleteSnapshotRequest): - The request object. Request for the `DeleteSnapshot` + The request object. + Request for the `DeleteSnapshot` method. snapshot (str): Required. The name of the snapshot to delete. Format is @@ -1704,7 +1719,8 @@ def seek( Args: request (google.pubsub_v1.types.SeekRequest): - The request object. Request for the `Seek` method. + 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. diff --git a/google/pubsub_v1/services/subscriber/transports/grpc.py b/google/pubsub_v1/services/subscriber/transports/grpc.py index c0e7f69e7..adb7f9b7a 100644 --- a/google/pubsub_v1/services/subscriber/transports/grpc.py +++ b/google/pubsub_v1/services/subscriber/transports/grpc.py @@ -232,7 +232,9 @@ def grpc_channel(self) -> grpc.Channel: def create_subscription( self, ) -> Callable[[pubsub.Subscription], pubsub.Subscription]: - r"""Return a callable for the create subscription method over gRPC. + r"""Return a callable for the + create subscription + method over gRPC. Creates a subscription to a given topic. See the [resource name rules] @@ -270,7 +272,9 @@ def create_subscription( def get_subscription( self, ) -> Callable[[pubsub.GetSubscriptionRequest], pubsub.Subscription]: - r"""Return a callable for the get subscription method over gRPC. + r"""Return a callable for the + get subscription + method over gRPC. Gets the configuration details of a subscription. @@ -296,7 +300,9 @@ def get_subscription( def update_subscription( self, ) -> Callable[[pubsub.UpdateSubscriptionRequest], pubsub.Subscription]: - r"""Return a callable for the update subscription method over gRPC. + 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 @@ -324,7 +330,9 @@ def update_subscription( def list_subscriptions( self, ) -> Callable[[pubsub.ListSubscriptionsRequest], pubsub.ListSubscriptionsResponse]: - r"""Return a callable for the list subscriptions method over gRPC. + r"""Return a callable for the + list subscriptions + method over gRPC. Lists matching subscriptions. @@ -350,7 +358,9 @@ def list_subscriptions( def delete_subscription( self, ) -> Callable[[pubsub.DeleteSubscriptionRequest], empty.Empty]: - r"""Return a callable for the delete subscription method over gRPC. + 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 @@ -381,7 +391,9 @@ def delete_subscription( def modify_ack_deadline( self, ) -> Callable[[pubsub.ModifyAckDeadlineRequest], empty.Empty]: - r"""Return a callable for the modify ack deadline method over gRPC. + 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 @@ -410,7 +422,9 @@ def modify_ack_deadline( @property def acknowledge(self) -> Callable[[pubsub.AcknowledgeRequest], empty.Empty]: - r"""Return a callable for the acknowledge method over gRPC. + 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 @@ -441,7 +455,9 @@ def acknowledge(self) -> Callable[[pubsub.AcknowledgeRequest], empty.Empty]: @property def pull(self) -> Callable[[pubsub.PullRequest], pubsub.PullResponse]: - r"""Return a callable for the pull method over gRPC. + 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 @@ -469,7 +485,9 @@ def pull(self) -> Callable[[pubsub.PullRequest], pubsub.PullResponse]: def streaming_pull( self, ) -> Callable[[pubsub.StreamingPullRequest], pubsub.StreamingPullResponse]: - r"""Return a callable for the streaming pull method over gRPC. + 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 @@ -502,7 +520,9 @@ def streaming_pull( def modify_push_config( self, ) -> Callable[[pubsub.ModifyPushConfigRequest], empty.Empty]: - r"""Return a callable for the modify push config method over gRPC. + r"""Return a callable for the + modify push config + method over gRPC. Modifies the ``PushConfig`` for a specified subscription. @@ -532,7 +552,9 @@ def modify_push_config( @property def get_snapshot(self) -> Callable[[pubsub.GetSnapshotRequest], pubsub.Snapshot]: - r"""Return a callable for the get snapshot method over gRPC. + r"""Return a callable for the + get snapshot + method over gRPC. Gets the configuration details of a snapshot. Snapshots are used in Callable[[pubsub.GetSnapshotRequest], pubsub.Snapshot] def list_snapshots( self, ) -> Callable[[pubsub.ListSnapshotsRequest], pubsub.ListSnapshotsResponse]: - r"""Return a callable for the list snapshots method over gRPC. + r"""Return a callable for the + list snapshots + method over gRPC. Lists the existing snapshots. Snapshots are used in `Seek `__ @@ -594,7 +618,9 @@ def list_snapshots( def create_snapshot( self, ) -> Callable[[pubsub.CreateSnapshotRequest], pubsub.Snapshot]: - r"""Return a callable for the create snapshot method over gRPC. + r"""Return a callable for the + create snapshot + method over gRPC. Creates a snapshot from the requested subscription. Snapshots are used in @@ -638,7 +664,9 @@ def create_snapshot( def update_snapshot( self, ) -> Callable[[pubsub.UpdateSnapshotRequest], pubsub.Snapshot]: - r"""Return a callable for the update snapshot method over gRPC. + r"""Return a callable for the + update snapshot + method over gRPC. Updates an existing snapshot. Snapshots are used in Callable[[pubsub.DeleteSnapshotRequest], empty.Empt @property def seek(self) -> Callable[[pubsub.SeekRequest], pubsub.SeekResponse]: - r"""Return a callable for the seek method over gRPC. + 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 diff --git a/google/pubsub_v1/services/subscriber/transports/grpc_asyncio.py b/google/pubsub_v1/services/subscriber/transports/grpc_asyncio.py index 64298b4ef..2f37070d7 100644 --- a/google/pubsub_v1/services/subscriber/transports/grpc_asyncio.py +++ b/google/pubsub_v1/services/subscriber/transports/grpc_asyncio.py @@ -236,7 +236,9 @@ def grpc_channel(self) -> aio.Channel: def create_subscription( self, ) -> Callable[[pubsub.Subscription], Awaitable[pubsub.Subscription]]: - r"""Return a callable for the create subscription method over gRPC. + r"""Return a callable for the + create subscription + method over gRPC. Creates a subscription to a given topic. See the [resource name rules] @@ -274,7 +276,9 @@ def create_subscription( def get_subscription( self, ) -> Callable[[pubsub.GetSubscriptionRequest], Awaitable[pubsub.Subscription]]: - r"""Return a callable for the get subscription method over gRPC. + r"""Return a callable for the + get subscription + method over gRPC. Gets the configuration details of a subscription. @@ -300,7 +304,9 @@ def get_subscription( def update_subscription( self, ) -> Callable[[pubsub.UpdateSubscriptionRequest], Awaitable[pubsub.Subscription]]: - r"""Return a callable for the update subscription method over gRPC. + 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 @@ -330,7 +336,9 @@ def list_subscriptions( ) -> Callable[ [pubsub.ListSubscriptionsRequest], Awaitable[pubsub.ListSubscriptionsResponse] ]: - r"""Return a callable for the list subscriptions method over gRPC. + r"""Return a callable for the + list subscriptions + method over gRPC. Lists matching subscriptions. @@ -356,7 +364,9 @@ def list_subscriptions( def delete_subscription( self, ) -> Callable[[pubsub.DeleteSubscriptionRequest], Awaitable[empty.Empty]]: - r"""Return a callable for the delete subscription method over gRPC. + 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 @@ -387,7 +397,9 @@ def delete_subscription( def modify_ack_deadline( self, ) -> Callable[[pubsub.ModifyAckDeadlineRequest], Awaitable[empty.Empty]]: - r"""Return a callable for the modify ack deadline method over gRPC. + 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 @@ -418,7 +430,9 @@ def modify_ack_deadline( def acknowledge( self, ) -> Callable[[pubsub.AcknowledgeRequest], Awaitable[empty.Empty]]: - r"""Return a callable for the acknowledge method over gRPC. + 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 @@ -449,7 +463,9 @@ def acknowledge( @property def pull(self) -> Callable[[pubsub.PullRequest], Awaitable[pubsub.PullResponse]]: - r"""Return a callable for the pull method over gRPC. + 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 @@ -479,7 +495,9 @@ def streaming_pull( ) -> Callable[ [pubsub.StreamingPullRequest], Awaitable[pubsub.StreamingPullResponse] ]: - r"""Return a callable for the streaming pull method over gRPC. + 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 @@ -512,7 +530,9 @@ def streaming_pull( def modify_push_config( self, ) -> Callable[[pubsub.ModifyPushConfigRequest], Awaitable[empty.Empty]]: - r"""Return a callable for the modify push config method over gRPC. + r"""Return a callable for the + modify push config + method over gRPC. Modifies the ``PushConfig`` for a specified subscription. @@ -544,7 +564,9 @@ def modify_push_config( def get_snapshot( self, ) -> Callable[[pubsub.GetSnapshotRequest], Awaitable[pubsub.Snapshot]]: - r"""Return a callable for the get snapshot method over gRPC. + r"""Return a callable for the + get snapshot + method over gRPC. Gets the configuration details of a snapshot. Snapshots are used in Callable[ [pubsub.ListSnapshotsRequest], Awaitable[pubsub.ListSnapshotsResponse] ]: - r"""Return a callable for the list snapshots method over gRPC. + r"""Return a callable for the + list snapshots + method over gRPC. Lists the existing snapshots. Snapshots are used in `Seek `__ @@ -608,7 +632,9 @@ def list_snapshots( def create_snapshot( self, ) -> Callable[[pubsub.CreateSnapshotRequest], Awaitable[pubsub.Snapshot]]: - r"""Return a callable for the create snapshot method over gRPC. + r"""Return a callable for the + create snapshot + method over gRPC. Creates a snapshot from the requested subscription. Snapshots are used in @@ -652,7 +678,9 @@ def create_snapshot( def update_snapshot( self, ) -> Callable[[pubsub.UpdateSnapshotRequest], Awaitable[pubsub.Snapshot]]: - r"""Return a callable for the update snapshot method over gRPC. + r"""Return a callable for the + update snapshot + method over gRPC. Updates an existing snapshot. Snapshots are used in Callable[[pubsub.SeekRequest], Awaitable[pubsub.SeekResponse]]: - r"""Return a callable for the seek method over gRPC. + 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 diff --git a/google/pubsub_v1/types/pubsub.py b/google/pubsub_v1/types/pubsub.py index 51da28e86..d06aa8e7e 100644 --- a/google/pubsub_v1/types/pubsub.py +++ b/google/pubsub_v1/types/pubsub.py @@ -144,7 +144,7 @@ class Topic(proto.Message): """ name = proto.Field(proto.STRING, number=1,) - labels = proto.MapField(proto.STRING, proto.STRING, number=2,) + labels = proto.MapField(proto.STRING, proto.STRING, number=2) message_storage_policy = proto.Field( proto.MESSAGE, number=3, message="MessageStoragePolicy", ) @@ -197,7 +197,7 @@ class PubsubMessage(proto.Message): """ data = proto.Field(proto.BYTES, number=1,) - attributes = proto.MapField(proto.STRING, proto.STRING, number=2,) + 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.Timestamp,) ordering_key = proto.Field(proto.STRING, number=5,) @@ -532,7 +532,7 @@ class Subscription(proto.Message): message_retention_duration = proto.Field( proto.MESSAGE, number=8, message=duration.Duration, ) - labels = proto.MapField(proto.STRING, proto.STRING, number=9,) + 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", @@ -709,7 +709,7 @@ class OidcToken(proto.Message): audience = proto.Field(proto.STRING, number=2,) push_endpoint = proto.Field(proto.STRING, number=1,) - attributes = proto.MapField(proto.STRING, proto.STRING, number=2,) + attributes = proto.MapField(proto.STRING, proto.STRING, number=2) oidc_token = proto.Field( proto.MESSAGE, number=3, oneof="authentication_method", message=OidcToken, ) @@ -1072,7 +1072,7 @@ class CreateSnapshotRequest(proto.Message): name = proto.Field(proto.STRING, number=1,) subscription = proto.Field(proto.STRING, number=2,) - labels = proto.MapField(proto.STRING, proto.STRING, number=3,) + labels = proto.MapField(proto.STRING, proto.STRING, number=3) class UpdateSnapshotRequest(proto.Message): @@ -1125,7 +1125,7 @@ class Snapshot(proto.Message): name = proto.Field(proto.STRING, number=1,) topic = proto.Field(proto.STRING, number=2,) expire_time = proto.Field(proto.MESSAGE, number=3, message=timestamp.Timestamp,) - labels = proto.MapField(proto.STRING, proto.STRING, number=4,) + labels = proto.MapField(proto.STRING, proto.STRING, number=4) class GetSnapshotRequest(proto.Message): diff --git a/synth.metadata b/synth.metadata index b53578ba5..0ff0f0c3f 100644 --- a/synth.metadata +++ b/synth.metadata @@ -11,8 +11,8 @@ "git": { "name": "googleapis", "remote": "https://github.com/googleapis/googleapis.git", - "sha": "382ed8de075e1ddc9baa4ebf8dbc5b2c257a77b8", - "internalRef": "370926454" + "sha": "4e825559e5ab242c4d1aafca19c83c4d1bac743e", + "internalRef": "370989216" } } ], diff --git a/tests/unit/gapic/pubsub_v1/test_publisher.py b/tests/unit/gapic/pubsub_v1/test_publisher.py index c550d6186..159f07af2 100644 --- a/tests/unit/gapic/pubsub_v1/test_publisher.py +++ b/tests/unit/gapic/pubsub_v1/test_publisher.py @@ -2769,7 +2769,7 @@ def test_publisher_transport_create_channel(transport_class, grpc_helpers): transport_class(quota_project_id="octopus", scopes=["1", "2"]) create_channel.assert_called_with( - "pubsub.googleapis.com:443", + "pubsub.googleapis.com", credentials=creds, credentials_file=None, quota_project_id="octopus", diff --git a/tests/unit/gapic/pubsub_v1/test_schema_service.py b/tests/unit/gapic/pubsub_v1/test_schema_service.py index 1c1610f66..d3f206ea2 100644 --- a/tests/unit/gapic/pubsub_v1/test_schema_service.py +++ b/tests/unit/gapic/pubsub_v1/test_schema_service.py @@ -1996,7 +1996,7 @@ def test_schema_service_transport_create_channel(transport_class, grpc_helpers): transport_class(quota_project_id="octopus", scopes=["1", "2"]) create_channel.assert_called_with( - "pubsub.googleapis.com:443", + "pubsub.googleapis.com", credentials=creds, credentials_file=None, quota_project_id="octopus", diff --git a/tests/unit/gapic/pubsub_v1/test_subscriber.py b/tests/unit/gapic/pubsub_v1/test_subscriber.py index eb4acac24..f83661f03 100644 --- a/tests/unit/gapic/pubsub_v1/test_subscriber.py +++ b/tests/unit/gapic/pubsub_v1/test_subscriber.py @@ -4046,7 +4046,7 @@ def test_subscriber_transport_create_channel(transport_class, grpc_helpers): transport_class(quota_project_id="octopus", scopes=["1", "2"]) create_channel.assert_called_with( - "pubsub.googleapis.com:443", + "pubsub.googleapis.com", credentials=creds, credentials_file=None, quota_project_id="octopus", From 2e0be21a7b78dbdc202869938e29943ebc0cc099 Mon Sep 17 00:00:00 2001 From: yoshi-automation Date: Sun, 18 Jul 2021 04:51:34 +0000 Subject: [PATCH 05/18] chore: revert to gapic-generator-python 0.43.3 PiperOrigin-RevId: 371362703 Source-Author: Google APIs Source-Date: Fri Apr 30 10:44:40 2021 -0700 Source-Repo: googleapis/googleapis Source-Sha: 5a04154e7c7c0e98e0e4085f6e2c67bd5bff6ff8 Source-Link: https://github.com/googleapis/googleapis/commit/5a04154e7c7c0e98e0e4085f6e2c67bd5bff6ff8 --- .coveragerc | 1 + google/pubsub/__init__.py | 1 + google/pubsub_v1/__init__.py | 3 +- google/pubsub_v1/gapic_metadata.json | 361 ------------- google/pubsub_v1/services/__init__.py | 1 + .../pubsub_v1/services/publisher/__init__.py | 2 + .../services/publisher/async_client.py | 55 +- google/pubsub_v1/services/publisher/client.py | 55 +- google/pubsub_v1/services/publisher/pagers.py | 2 + .../services/publisher/transports/__init__.py | 2 + .../services/publisher/transports/base.py | 145 ++---- .../services/publisher/transports/grpc.py | 50 +- .../publisher/transports/grpc_asyncio.py | 52 +- .../services/schema_service/__init__.py | 2 + .../services/schema_service/async_client.py | 39 +- .../services/schema_service/client.py | 38 +- .../services/schema_service/pagers.py | 2 + .../schema_service/transports/__init__.py | 2 + .../schema_service/transports/base.py | 131 ++--- .../schema_service/transports/grpc.py | 38 +- .../schema_service/transports/grpc_asyncio.py | 40 +- .../pubsub_v1/services/subscriber/__init__.py | 2 + .../services/subscriber/async_client.py | 89 ++-- .../pubsub_v1/services/subscriber/client.py | 93 ++-- .../pubsub_v1/services/subscriber/pagers.py | 2 + .../subscriber/transports/__init__.py | 2 + .../services/subscriber/transports/base.py | 176 +++---- .../services/subscriber/transports/grpc.py | 78 +-- .../subscriber/transports/grpc_asyncio.py | 80 +-- google/pubsub_v1/types/__init__.py | 2 + google/pubsub_v1/types/pubsub.py | 261 +++++++--- google/pubsub_v1/types/schema.py | 56 +- scripts/fixup_pubsub_v1_keywords.py | 68 +-- synth.metadata | 8 +- tests/__init__.py | 15 - tests/unit/__init__.py | 15 - tests/unit/gapic/__init__.py | 15 - tests/unit/gapic/pubsub_v1/__init__.py | 1 + tests/unit/gapic/pubsub_v1/test_publisher.py | 367 +++++-------- .../gapic/pubsub_v1/test_schema_service.py | 329 ++++-------- tests/unit/gapic/pubsub_v1/test_subscriber.py | 492 +++++++++--------- 41 files changed, 1277 insertions(+), 1896 deletions(-) delete mode 100644 google/pubsub_v1/gapic_metadata.json delete mode 100644 tests/__init__.py delete mode 100644 tests/unit/gapic/__init__.py diff --git a/.coveragerc b/.coveragerc index 96190b454..a48e62f2e 100644 --- a/.coveragerc +++ b/.coveragerc @@ -2,6 +2,7 @@ branch = True [report] +fail_under = 100 show_missing = True omit = google/cloud/__init__.py diff --git a/google/pubsub/__init__.py b/google/pubsub/__init__.py index 5529b3ca6..b146fadef 100644 --- a/google/pubsub/__init__.py +++ b/google/pubsub/__init__.py @@ -1,4 +1,5 @@ # -*- coding: utf-8 -*- + # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); diff --git a/google/pubsub_v1/__init__.py b/google/pubsub_v1/__init__.py index 33fca22fc..d5a1de488 100644 --- a/google/pubsub_v1/__init__.py +++ b/google/pubsub_v1/__init__.py @@ -1,4 +1,5 @@ # -*- coding: utf-8 -*- + # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -17,7 +18,6 @@ from .services.publisher import PublisherClient from .services.schema_service import SchemaServiceClient from .services.subscriber import SubscriberClient - from .types.pubsub import AcknowledgeRequest from .types.pubsub import CreateSnapshotRequest from .types.pubsub import DeadLetterPolicy @@ -75,6 +75,7 @@ from .types.schema import ValidateSchemaRequest from .types.schema import ValidateSchemaResponse + __all__ = ( "AcknowledgeRequest", "CreateSchemaRequest", diff --git a/google/pubsub_v1/gapic_metadata.json b/google/pubsub_v1/gapic_metadata.json deleted file mode 100644 index 4c5b86bd1..000000000 --- a/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/google/pubsub_v1/services/__init__.py b/google/pubsub_v1/services/__init__.py index 4de65971c..42ffdf2bc 100644 --- a/google/pubsub_v1/services/__init__.py +++ b/google/pubsub_v1/services/__init__.py @@ -1,4 +1,5 @@ # -*- coding: utf-8 -*- + # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); diff --git a/google/pubsub_v1/services/publisher/__init__.py b/google/pubsub_v1/services/publisher/__init__.py index 98e50425d..970a1a3b4 100644 --- a/google/pubsub_v1/services/publisher/__init__.py +++ b/google/pubsub_v1/services/publisher/__init__.py @@ -1,4 +1,5 @@ # -*- coding: utf-8 -*- + # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -13,6 +14,7 @@ # See the License for the specific language governing permissions and # limitations under the License. # + from .client import PublisherClient from .async_client import PublisherAsyncClient diff --git a/google/pubsub_v1/services/publisher/async_client.py b/google/pubsub_v1/services/publisher/async_client.py index 9311b05e4..056ba288d 100644 --- a/google/pubsub_v1/services/publisher/async_client.py +++ b/google/pubsub_v1/services/publisher/async_client.py @@ -1,4 +1,5 @@ # -*- coding: utf-8 -*- + # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -13,6 +14,7 @@ # See the License for the specific language governing permissions and # limitations under the License. # + from collections import OrderedDict import functools import re @@ -32,6 +34,7 @@ from google.pubsub_v1.services.publisher import pagers from google.pubsub_v1.types import pubsub from google.pubsub_v1.types import TimeoutType + from .transports.base import PublisherTransport, DEFAULT_CLIENT_INFO from .transports.grpc_asyncio import PublisherGrpcAsyncIOTransport from .client import PublisherClient @@ -53,20 +56,25 @@ class PublisherAsyncClient: 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 @@ -157,6 +165,7 @@ def __init__( google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport creation failed for any reason. """ + self._client = PublisherClient( credentials=credentials, transport=transport, @@ -179,8 +188,7 @@ async def create_topic( Args: request (:class:`google.pubsub_v1.types.Topic`): - The request object. - A topic resource. + 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}`` @@ -194,6 +202,7 @@ async def create_topic( 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 (TimeoutType): @@ -219,6 +228,7 @@ async def create_topic( # If we have keyword arguments corresponding to fields on the # request, apply these. + if name is not None: request.name = name @@ -262,8 +272,8 @@ async def update_topic( Args: request (:class:`google.pubsub_v1.types.UpdateTopicRequest`): - The request object. - Request for the UpdateTopic method. + The request object. Request for the UpdateTopic method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (TimeoutType): @@ -276,6 +286,7 @@ async def update_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, @@ -322,8 +333,7 @@ async def publish( Args: request (:class:`google.pubsub_v1.types.PublishRequest`): - The request object. - Request for the Publish method. + 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 @@ -337,6 +347,7 @@ async def 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 (TimeoutType): @@ -362,8 +373,10 @@ async def publish( # 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) @@ -415,8 +428,7 @@ async def get_topic( Args: request (:class:`google.pubsub_v1.types.GetTopicRequest`): - The request object. - Request for the GetTopic method. + 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}``. @@ -424,6 +436,7 @@ async def get_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 (TimeoutType): @@ -449,6 +462,7 @@ async def get_topic( # If we have keyword arguments corresponding to fields on the # request, apply these. + if topic is not None: request.topic = topic @@ -496,8 +510,7 @@ async def list_topics( Args: request (:class:`google.pubsub_v1.types.ListTopicsRequest`): - The request object. - Request for the `ListTopics` method. + 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}``. @@ -505,6 +518,7 @@ async def list_topics( 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 (TimeoutType): @@ -534,6 +548,7 @@ async def list_topics( # If we have keyword arguments corresponding to fields on the # request, apply these. + if project is not None: request.project = project @@ -588,8 +603,7 @@ async def list_topic_subscriptions( Args: request (:class:`google.pubsub_v1.types.ListTopicSubscriptionsRequest`): - The request object. - Request for the + The request object. Request for the `ListTopicSubscriptions` method. topic (:class:`str`): Required. The name of the topic that subscriptions are @@ -599,6 +613,7 @@ async def list_topic_subscriptions( 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 (TimeoutType): @@ -628,6 +643,7 @@ async def list_topic_subscriptions( # If we have keyword arguments corresponding to fields on the # request, apply these. + if topic is not None: request.topic = topic @@ -686,8 +702,7 @@ async def list_topic_snapshots( Args: request (:class:`google.pubsub_v1.types.ListTopicSnapshotsRequest`): - The request object. - Request for the `ListTopicSnapshots` + The request object. Request for the `ListTopicSnapshots` method. topic (:class:`str`): Required. The name of the topic that snapshots are @@ -697,6 +712,7 @@ async def list_topic_snapshots( 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 (TimeoutType): @@ -726,6 +742,7 @@ async def list_topic_snapshots( # If we have keyword arguments corresponding to fields on the # request, apply these. + if topic is not None: request.topic = topic @@ -784,8 +801,7 @@ async def delete_topic( Args: request (:class:`google.pubsub_v1.types.DeleteTopicRequest`): - The request object. - Request for the `DeleteTopic` + The request object. Request for the `DeleteTopic` method. topic (:class:`str`): Required. Name of the topic to delete. Format is @@ -794,6 +810,7 @@ async def delete_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 (TimeoutType): @@ -815,6 +832,7 @@ async def delete_topic( # If we have keyword arguments corresponding to fields on the # request, apply these. + if topic is not None: request.topic = topic @@ -860,9 +878,9 @@ async def detach_subscription( Args: request (:class:`google.pubsub_v1.types.DetachSubscriptionRequest`): - The request object. - Request for the DetachSubscription + The request object. Request for the DetachSubscription method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (TimeoutType): @@ -877,6 +895,7 @@ async def detach_subscription( """ # Create or coerce a protobuf request object. + request = pubsub.DetachSubscriptionRequest(request) # Wrap the RPC method; this adds retry and timeout information, diff --git a/google/pubsub_v1/services/publisher/client.py b/google/pubsub_v1/services/publisher/client.py index 736f3e3ce..3a3db1ebe 100644 --- a/google/pubsub_v1/services/publisher/client.py +++ b/google/pubsub_v1/services/publisher/client.py @@ -1,4 +1,5 @@ # -*- coding: utf-8 -*- + # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -13,6 +14,7 @@ # See the License for the specific language governing permissions and # limitations under the License. # + from collections import OrderedDict from distutils import util import functools @@ -39,6 +41,7 @@ from google.pubsub_v1.types import TimeoutType import grpc + from .transports.base import PublisherTransport, DEFAULT_CLIENT_INFO from .transports.grpc import PublisherGrpcTransport from .transports.grpc_asyncio import PublisherGrpcAsyncIOTransport @@ -410,8 +413,7 @@ def create_topic( Args: request (google.pubsub_v1.types.Topic): - The request object. - A topic resource. + The request object. A topic resource. name (str): Required. The name of the topic. It must have the format ``"projects/{project}/topics/{topic}"``. ``{topic}`` @@ -425,6 +427,7 @@ def create_topic( 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 (TimeoutType): @@ -452,8 +455,10 @@ def create_topic( # 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 @@ -487,8 +492,8 @@ def update_topic( Args: request (google.pubsub_v1.types.UpdateTopicRequest): - The request object. - Request for the UpdateTopic method. + The request object. Request for the UpdateTopic method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (TimeoutType): @@ -501,6 +506,7 @@ def update_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 @@ -542,8 +548,7 @@ def publish( Args: request (google.pubsub_v1.types.PublishRequest): - The request object. - Request for the Publish method. + The request object. Request for the Publish method. topic (str): Required. The messages in the request will be published on this topic. Format is @@ -557,6 +562,7 @@ def 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 (TimeoutType): @@ -584,8 +590,10 @@ def publish( # 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: @@ -621,8 +629,7 @@ def get_topic( Args: request (google.pubsub_v1.types.GetTopicRequest): - The request object. - Request for the GetTopic method. + The request object. Request for the GetTopic method. topic (str): Required. The name of the topic to get. Format is ``projects/{project}/topics/{topic}``. @@ -630,6 +637,7 @@ def get_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 (TimeoutType): @@ -657,8 +665,10 @@ def get_topic( # 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 @@ -692,8 +702,7 @@ def list_topics( Args: request (google.pubsub_v1.types.ListTopicsRequest): - The request object. - Request for the `ListTopics` method. + 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}``. @@ -701,6 +710,7 @@ def list_topics( 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 (TimeoutType): @@ -732,8 +742,10 @@ def list_topics( # 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 @@ -774,8 +786,7 @@ def list_topic_subscriptions( Args: request (google.pubsub_v1.types.ListTopicSubscriptionsRequest): - The request object. - Request for the + The request object. Request for the `ListTopicSubscriptions` method. topic (str): Required. The name of the topic that subscriptions are @@ -785,6 +796,7 @@ def list_topic_subscriptions( 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 (TimeoutType): @@ -816,8 +828,10 @@ def list_topic_subscriptions( # 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 @@ -862,8 +876,7 @@ def list_topic_snapshots( Args: request (google.pubsub_v1.types.ListTopicSnapshotsRequest): - The request object. - Request for the `ListTopicSnapshots` + The request object. Request for the `ListTopicSnapshots` method. topic (str): Required. The name of the topic that snapshots are @@ -873,6 +886,7 @@ def list_topic_snapshots( 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 (TimeoutType): @@ -904,8 +918,10 @@ def list_topic_snapshots( # 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 @@ -950,8 +966,7 @@ def delete_topic( Args: request (google.pubsub_v1.types.DeleteTopicRequest): - The request object. - Request for the `DeleteTopic` + The request object. Request for the `DeleteTopic` method. topic (str): Required. Name of the topic to delete. Format is @@ -960,6 +975,7 @@ def delete_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 (TimeoutType): @@ -983,8 +999,10 @@ def delete_topic( # 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 @@ -1020,9 +1038,9 @@ def detach_subscription( Args: request (google.pubsub_v1.types.DetachSubscriptionRequest): - The request object. - Request for the DetachSubscription + The request object. Request for the DetachSubscription method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (TimeoutType): @@ -1037,6 +1055,7 @@ def detach_subscription( """ # 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 diff --git a/google/pubsub_v1/services/publisher/pagers.py b/google/pubsub_v1/services/publisher/pagers.py index 592e3d507..e8836d410 100644 --- a/google/pubsub_v1/services/publisher/pagers.py +++ b/google/pubsub_v1/services/publisher/pagers.py @@ -1,4 +1,5 @@ # -*- coding: utf-8 -*- + # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -13,6 +14,7 @@ # See the License for the specific language governing permissions and # limitations under the License. # + from typing import ( Any, AsyncIterable, diff --git a/google/pubsub_v1/services/publisher/transports/__init__.py b/google/pubsub_v1/services/publisher/transports/__init__.py index 34066edc3..9eec7fc5d 100644 --- a/google/pubsub_v1/services/publisher/transports/__init__.py +++ b/google/pubsub_v1/services/publisher/transports/__init__.py @@ -1,4 +1,5 @@ # -*- coding: utf-8 -*- + # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -13,6 +14,7 @@ # See the License for the specific language governing permissions and # limitations under the License. # + from collections import OrderedDict from typing import Dict, Type diff --git a/google/pubsub_v1/services/publisher/transports/base.py b/google/pubsub_v1/services/publisher/transports/base.py index e814c9cbb..b1111a841 100644 --- a/google/pubsub_v1/services/publisher/transports/base.py +++ b/google/pubsub_v1/services/publisher/transports/base.py @@ -1,4 +1,5 @@ # -*- coding: utf-8 -*- + # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -13,13 +14,12 @@ # 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 packaging.version +import typing import pkg_resources from google import auth # type: ignore -import google.api_core # type: ignore from google.api_core import exceptions # type: ignore from google.api_core import gapic_v1 # type: ignore from google.api_core import retry as retries # type: ignore @@ -30,6 +30,7 @@ from google.protobuf import empty_pb2 as empty # type: ignore from google.pubsub_v1.types import pubsub + try: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( client_library_version=pkg_resources.get_distribution( @@ -39,17 +40,6 @@ except pkg_resources.DistributionNotFound: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() -try: - # google.auth.__version__ was added in 1.26.0 - _GOOGLE_AUTH_VERSION = auth.__version__ -except AttributeError: - try: # try pkg_resources if it is available - _GOOGLE_AUTH_VERSION = pkg_resources.get_distribution("google-auth").version - except pkg_resources.DistributionNotFound: # pragma: NO COVER - _GOOGLE_AUTH_VERSION = None - -_API_CORE_VERSION = google.api_core.__version__ - class PublisherTransport(abc.ABC): """Abstract transport class for Publisher.""" @@ -59,24 +49,21 @@ class PublisherTransport(abc.ABC): "https://www.googleapis.com/auth/pubsub", ) - DEFAULT_HOST: str = "pubsub.googleapis.com" - def __init__( self, *, - host: str = DEFAULT_HOST, + host: str = "pubsub.googleapis.com", credentials: credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, + credentials_file: typing.Optional[str] = None, + scopes: typing.Optional[typing.Sequence[str]] = AUTH_SCOPES, + quota_project_id: typing.Optional[str] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, **kwargs, ) -> None: """Instantiate the transport. Args: - host (Optional[str]): - The hostname to connect to. + 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 @@ -85,7 +72,7 @@ def __init__( 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. + scope (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): @@ -99,8 +86,6 @@ def __init__( host += ":443" self._host = host - scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) - # Save the scopes. self._scopes = scopes or self.AUTH_SCOPES @@ -113,62 +98,17 @@ def __init__( if credentials_file is not None: credentials, _ = auth.load_credentials_from_file( - credentials_file, **scopes_kwargs, quota_project_id=quota_project_id + credentials_file, scopes=self._scopes, quota_project_id=quota_project_id ) elif credentials is None: credentials, _ = auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=self._scopes, quota_project_id=quota_project_id ) # Save the credentials. self._credentials = credentials - # TODO(busunkim): These two class methods are in the base transport - # to avoid duplicating code across the transport classes. These functions - # should be deleted once the minimum required versions of google-api-core - # and google-auth are increased. - - # TODO: Remove this function once google-auth >= 1.25.0 is required - @classmethod - def _get_scopes_kwargs( - cls, host: str, scopes: Optional[Sequence[str]] - ) -> Dict[str, Optional[Sequence[str]]]: - """Returns scopes kwargs to pass to google-auth methods depending on the google-auth version""" - - scopes_kwargs = {} - - if _GOOGLE_AUTH_VERSION and ( - packaging.version.parse(_GOOGLE_AUTH_VERSION) - >= packaging.version.parse("1.25.0") - ): - scopes_kwargs = {"scopes": scopes, "default_scopes": cls.AUTH_SCOPES} - else: - scopes_kwargs = {"scopes": scopes or cls.AUTH_SCOPES} - - return scopes_kwargs - - # TODO: Remove this function once google-api-core >= 1.26.0 is required - @classmethod - def _get_self_signed_jwt_kwargs( - cls, host: str, scopes: Optional[Sequence[str]] - ) -> Dict[str, Union[Optional[Sequence[str]], str]]: - """Returns kwargs to pass to grpc_helpers.create_channel depending on the google-api-core version""" - - self_signed_jwt_kwargs: Dict[str, Union[Optional[Sequence[str]], str]] = {} - - if _API_CORE_VERSION and ( - packaging.version.parse(_API_CORE_VERSION) - >= packaging.version.parse("1.26.0") - ): - self_signed_jwt_kwargs["default_scopes"] = cls.AUTH_SCOPES - self_signed_jwt_kwargs["scopes"] = scopes - self_signed_jwt_kwargs["default_host"] = cls.DEFAULT_HOST - else: - self_signed_jwt_kwargs["scopes"] = scopes or cls.AUTH_SCOPES - - return self_signed_jwt_kwargs - def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. self._wrapped_methods = { @@ -309,51 +249,57 @@ def _prep_wrapped_messages(self, client_info): @property def create_topic( self, - ) -> Callable[[pubsub.Topic], Union[pubsub.Topic, Awaitable[pubsub.Topic]]]: + ) -> typing.Callable[ + [pubsub.Topic], typing.Union[pubsub.Topic, typing.Awaitable[pubsub.Topic]] + ]: raise NotImplementedError() @property def update_topic( self, - ) -> Callable[ - [pubsub.UpdateTopicRequest], Union[pubsub.Topic, Awaitable[pubsub.Topic]] + ) -> typing.Callable[ + [pubsub.UpdateTopicRequest], + typing.Union[pubsub.Topic, typing.Awaitable[pubsub.Topic]], ]: raise NotImplementedError() @property def publish( self, - ) -> Callable[ + ) -> typing.Callable[ [pubsub.PublishRequest], - Union[pubsub.PublishResponse, Awaitable[pubsub.PublishResponse]], + typing.Union[pubsub.PublishResponse, typing.Awaitable[pubsub.PublishResponse]], ]: raise NotImplementedError() @property def get_topic( self, - ) -> Callable[ - [pubsub.GetTopicRequest], Union[pubsub.Topic, Awaitable[pubsub.Topic]] + ) -> typing.Callable[ + [pubsub.GetTopicRequest], + typing.Union[pubsub.Topic, typing.Awaitable[pubsub.Topic]], ]: raise NotImplementedError() @property def list_topics( self, - ) -> Callable[ + ) -> typing.Callable[ [pubsub.ListTopicsRequest], - Union[pubsub.ListTopicsResponse, Awaitable[pubsub.ListTopicsResponse]], + typing.Union[ + pubsub.ListTopicsResponse, typing.Awaitable[pubsub.ListTopicsResponse] + ], ]: raise NotImplementedError() @property def list_topic_subscriptions( self, - ) -> Callable[ + ) -> typing.Callable[ [pubsub.ListTopicSubscriptionsRequest], - Union[ + typing.Union[ pubsub.ListTopicSubscriptionsResponse, - Awaitable[pubsub.ListTopicSubscriptionsResponse], + typing.Awaitable[pubsub.ListTopicSubscriptionsResponse], ], ]: raise NotImplementedError() @@ -361,11 +307,11 @@ def list_topic_subscriptions( @property def list_topic_snapshots( self, - ) -> Callable[ + ) -> typing.Callable[ [pubsub.ListTopicSnapshotsRequest], - Union[ + typing.Union[ pubsub.ListTopicSnapshotsResponse, - Awaitable[pubsub.ListTopicSnapshotsResponse], + typing.Awaitable[pubsub.ListTopicSnapshotsResponse], ], ]: raise NotImplementedError() @@ -373,19 +319,20 @@ def list_topic_snapshots( @property def delete_topic( self, - ) -> Callable[ - [pubsub.DeleteTopicRequest], Union[empty.Empty, Awaitable[empty.Empty]] + ) -> typing.Callable[ + [pubsub.DeleteTopicRequest], + typing.Union[empty.Empty, typing.Awaitable[empty.Empty]], ]: raise NotImplementedError() @property def detach_subscription( self, - ) -> Callable[ + ) -> typing.Callable[ [pubsub.DetachSubscriptionRequest], - Union[ + typing.Union[ pubsub.DetachSubscriptionResponse, - Awaitable[pubsub.DetachSubscriptionResponse], + typing.Awaitable[pubsub.DetachSubscriptionResponse], ], ]: raise NotImplementedError() @@ -393,29 +340,29 @@ def detach_subscription( @property def set_iam_policy( self, - ) -> Callable[ + ) -> typing.Callable[ [iam_policy.SetIamPolicyRequest], - Union[policy.Policy, Awaitable[policy.Policy]], + typing.Union[policy.Policy, typing.Awaitable[policy.Policy]], ]: raise NotImplementedError() @property def get_iam_policy( self, - ) -> Callable[ + ) -> typing.Callable[ [iam_policy.GetIamPolicyRequest], - Union[policy.Policy, Awaitable[policy.Policy]], + typing.Union[policy.Policy, typing.Awaitable[policy.Policy]], ]: raise NotImplementedError() @property def test_iam_permissions( self, - ) -> Callable[ + ) -> typing.Callable[ [iam_policy.TestIamPermissionsRequest], - Union[ + typing.Union[ iam_policy.TestIamPermissionsResponse, - Awaitable[iam_policy.TestIamPermissionsResponse], + typing.Awaitable[iam_policy.TestIamPermissionsResponse], ], ]: raise NotImplementedError() diff --git a/google/pubsub_v1/services/publisher/transports/grpc.py b/google/pubsub_v1/services/publisher/transports/grpc.py index 2e6acea4d..0b9ddc8e2 100644 --- a/google/pubsub_v1/services/publisher/transports/grpc.py +++ b/google/pubsub_v1/services/publisher/transports/grpc.py @@ -1,4 +1,5 @@ # -*- coding: utf-8 -*- + # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -13,8 +14,9 @@ # 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 typing import Callable, Dict, Optional, Sequence, Tuple from google.api_core import grpc_helpers # type: ignore from google.api_core import gapic_v1 # type: ignore @@ -28,6 +30,7 @@ from google.iam.v1 import policy_pb2 as policy # type: ignore from google.protobuf import empty_pb2 as empty # type: ignore from google.pubsub_v1.types import pubsub + from .base import PublisherTransport, DEFAULT_CLIENT_INFO @@ -65,8 +68,7 @@ def __init__( """Instantiate the transport. Args: - host (Optional[str]): - The hostname to connect to. + 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 @@ -208,15 +210,13 @@ def create_channel( google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` and ``credentials_file`` are passed. """ - - self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) - + scopes = scopes or cls.AUTH_SCOPES return grpc_helpers.create_channel( host, credentials=credentials, credentials_file=credentials_file, + scopes=scopes, quota_project_id=quota_project_id, - **self_signed_jwt_kwargs, **kwargs, ) @@ -228,9 +228,7 @@ def grpc_channel(self) -> grpc.Channel: @property def create_topic(self) -> Callable[[pubsub.Topic], pubsub.Topic]: - r"""Return a callable for the - create topic - method over gRPC. + r"""Return a callable for the create topic method over gRPC. Creates the given topic with the given name. See the [resource name rules] @@ -256,9 +254,7 @@ def create_topic(self) -> Callable[[pubsub.Topic], pubsub.Topic]: @property def update_topic(self) -> Callable[[pubsub.UpdateTopicRequest], pubsub.Topic]: - r"""Return a callable for the - update topic - method over gRPC. + 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. @@ -283,9 +279,7 @@ def update_topic(self) -> Callable[[pubsub.UpdateTopicRequest], pubsub.Topic]: @property def publish(self) -> Callable[[pubsub.PublishRequest], pubsub.PublishResponse]: - r"""Return a callable for the - publish - method over gRPC. + 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. @@ -310,9 +304,7 @@ def publish(self) -> Callable[[pubsub.PublishRequest], pubsub.PublishResponse]: @property def get_topic(self) -> Callable[[pubsub.GetTopicRequest], pubsub.Topic]: - r"""Return a callable for the - get topic - method over gRPC. + r"""Return a callable for the get topic method over gRPC. Gets the configuration of a topic. @@ -338,9 +330,7 @@ def get_topic(self) -> Callable[[pubsub.GetTopicRequest], pubsub.Topic]: def list_topics( self, ) -> Callable[[pubsub.ListTopicsRequest], pubsub.ListTopicsResponse]: - r"""Return a callable for the - list topics - method over gRPC. + r"""Return a callable for the list topics method over gRPC. Lists matching topics. @@ -368,9 +358,7 @@ def list_topic_subscriptions( ) -> Callable[ [pubsub.ListTopicSubscriptionsRequest], pubsub.ListTopicSubscriptionsResponse ]: - r"""Return a callable for the - list topic subscriptions - method over gRPC. + r"""Return a callable for the list topic subscriptions method over gRPC. Lists the names of the attached subscriptions on this topic. @@ -399,9 +387,7 @@ def list_topic_snapshots( ) -> Callable[ [pubsub.ListTopicSnapshotsRequest], pubsub.ListTopicSnapshotsResponse ]: - r"""Return a callable for the - list topic snapshots - method over gRPC. + 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 @@ -430,9 +416,7 @@ def list_topic_snapshots( @property def delete_topic(self) -> Callable[[pubsub.DeleteTopicRequest], empty.Empty]: - r"""Return a callable for the - delete topic - method over gRPC. + 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 @@ -465,9 +449,7 @@ def detach_subscription( ) -> Callable[ [pubsub.DetachSubscriptionRequest], pubsub.DetachSubscriptionResponse ]: - r"""Return a callable for the - detach subscription - method over gRPC. + 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 diff --git a/google/pubsub_v1/services/publisher/transports/grpc_asyncio.py b/google/pubsub_v1/services/publisher/transports/grpc_asyncio.py index 64250b7c3..6a3a096f0 100644 --- a/google/pubsub_v1/services/publisher/transports/grpc_asyncio.py +++ b/google/pubsub_v1/services/publisher/transports/grpc_asyncio.py @@ -1,4 +1,5 @@ # -*- coding: utf-8 -*- + # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -13,15 +14,15 @@ # 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 typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple from google.api_core import gapic_v1 # type: ignore from google.api_core import grpc_helpers_async # type: ignore from google import auth # type: ignore from google.auth import credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore -import packaging.version import grpc # type: ignore from grpc.experimental import aio # type: ignore @@ -30,6 +31,7 @@ from google.iam.v1 import policy_pb2 as policy # type: ignore from google.protobuf import empty_pb2 as empty # type: ignore from google.pubsub_v1.types import pubsub + from .base import PublisherTransport, DEFAULT_CLIENT_INFO from .grpc import PublisherGrpcTransport @@ -82,15 +84,13 @@ def create_channel( Returns: aio.Channel: A gRPC AsyncIO channel object. """ - - self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) - + scopes = scopes or cls.AUTH_SCOPES return grpc_helpers_async.create_channel( host, credentials=credentials, credentials_file=credentials_file, + scopes=scopes, quota_project_id=quota_project_id, - **self_signed_jwt_kwargs, **kwargs, ) @@ -112,8 +112,7 @@ def __init__( """Instantiate the transport. Args: - host (Optional[str]): - The hostname to connect to. + 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 @@ -171,6 +170,7 @@ def __init__( # 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 @@ -232,9 +232,7 @@ def grpc_channel(self) -> aio.Channel: @property def create_topic(self) -> Callable[[pubsub.Topic], Awaitable[pubsub.Topic]]: - r"""Return a callable for the - create topic - method over gRPC. + r"""Return a callable for the create topic method over gRPC. Creates the given topic with the given name. See the [resource name rules] @@ -262,9 +260,7 @@ def create_topic(self) -> Callable[[pubsub.Topic], Awaitable[pubsub.Topic]]: def update_topic( self, ) -> Callable[[pubsub.UpdateTopicRequest], Awaitable[pubsub.Topic]]: - r"""Return a callable for the - update topic - method over gRPC. + 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. @@ -291,9 +287,7 @@ def update_topic( def publish( self, ) -> Callable[[pubsub.PublishRequest], Awaitable[pubsub.PublishResponse]]: - r"""Return a callable for the - publish - method over gRPC. + 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. @@ -318,9 +312,7 @@ def publish( @property def get_topic(self) -> Callable[[pubsub.GetTopicRequest], Awaitable[pubsub.Topic]]: - r"""Return a callable for the - get topic - method over gRPC. + r"""Return a callable for the get topic method over gRPC. Gets the configuration of a topic. @@ -346,9 +338,7 @@ def get_topic(self) -> Callable[[pubsub.GetTopicRequest], Awaitable[pubsub.Topic def list_topics( self, ) -> Callable[[pubsub.ListTopicsRequest], Awaitable[pubsub.ListTopicsResponse]]: - r"""Return a callable for the - list topics - method over gRPC. + r"""Return a callable for the list topics method over gRPC. Lists matching topics. @@ -377,9 +367,7 @@ def list_topic_subscriptions( [pubsub.ListTopicSubscriptionsRequest], Awaitable[pubsub.ListTopicSubscriptionsResponse], ]: - r"""Return a callable for the - list topic subscriptions - method over gRPC. + r"""Return a callable for the list topic subscriptions method over gRPC. Lists the names of the attached subscriptions on this topic. @@ -408,9 +396,7 @@ def list_topic_snapshots( ) -> Callable[ [pubsub.ListTopicSnapshotsRequest], Awaitable[pubsub.ListTopicSnapshotsResponse] ]: - r"""Return a callable for the - list topic snapshots - method over gRPC. + 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 @@ -441,9 +427,7 @@ def list_topic_snapshots( def delete_topic( self, ) -> Callable[[pubsub.DeleteTopicRequest], Awaitable[empty.Empty]]: - r"""Return a callable for the - delete topic - method over gRPC. + 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 @@ -476,9 +460,7 @@ def detach_subscription( ) -> Callable[ [pubsub.DetachSubscriptionRequest], Awaitable[pubsub.DetachSubscriptionResponse] ]: - r"""Return a callable for the - detach subscription - method over gRPC. + 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 diff --git a/google/pubsub_v1/services/schema_service/__init__.py b/google/pubsub_v1/services/schema_service/__init__.py index 523d5b5f5..d93cff56f 100644 --- a/google/pubsub_v1/services/schema_service/__init__.py +++ b/google/pubsub_v1/services/schema_service/__init__.py @@ -1,4 +1,5 @@ # -*- coding: utf-8 -*- + # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -13,6 +14,7 @@ # See the License for the specific language governing permissions and # limitations under the License. # + from .client import SchemaServiceClient from .async_client import SchemaServiceAsyncClient diff --git a/google/pubsub_v1/services/schema_service/async_client.py b/google/pubsub_v1/services/schema_service/async_client.py index 4cfc74e81..9aeb62990 100644 --- a/google/pubsub_v1/services/schema_service/async_client.py +++ b/google/pubsub_v1/services/schema_service/async_client.py @@ -1,4 +1,5 @@ # -*- coding: utf-8 -*- + # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -13,6 +14,7 @@ # See the License for the specific language governing permissions and # limitations under the License. # + from collections import OrderedDict import functools import re @@ -31,6 +33,7 @@ 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 @@ -46,26 +49,31 @@ class SchemaServiceAsyncClient: 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 @@ -156,6 +164,7 @@ def __init__( google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport creation failed for any reason. """ + self._client = SchemaServiceClient( credentials=credentials, transport=transport, @@ -178,8 +187,7 @@ async def create_schema( Args: request (:class:`google.pubsub_v1.types.CreateSchemaRequest`): - The request object. - Request for the CreateSchema method. + 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}``. @@ -208,6 +216,7 @@ async def create_schema( 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. @@ -232,6 +241,7 @@ async def create_schema( # 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: @@ -272,8 +282,7 @@ async def get_schema( Args: request (:class:`google.pubsub_v1.types.GetSchemaRequest`): - The request object. - Request for the GetSchema method. + 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}``. @@ -281,6 +290,7 @@ async def get_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. @@ -305,6 +315,7 @@ async def get_schema( # If we have keyword arguments corresponding to fields on the # request, apply these. + if name is not None: request.name = name @@ -341,8 +352,7 @@ async def list_schemas( Args: request (:class:`google.pubsub_v1.types.ListSchemasRequest`): - The request object. - Request for the `ListSchemas` + The request object. Request for the `ListSchemas` method. parent (:class:`str`): Required. The name of the project in which to list @@ -351,6 +361,7 @@ async def list_schemas( 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. @@ -379,6 +390,7 @@ async def list_schemas( # If we have keyword arguments corresponding to fields on the # request, apply these. + if parent is not None: request.parent = parent @@ -421,8 +433,7 @@ async def delete_schema( Args: request (:class:`google.pubsub_v1.types.DeleteSchemaRequest`): - The request object. - Request for the `DeleteSchema` + The request object. Request for the `DeleteSchema` method. name (:class:`str`): Required. Name of the schema to delete. Format is @@ -431,6 +442,7 @@ async def delete_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. @@ -451,6 +463,7 @@ async def delete_schema( # If we have keyword arguments corresponding to fields on the # request, apply these. + if name is not None: request.name = name @@ -487,8 +500,7 @@ async def validate_schema( Args: request (:class:`google.pubsub_v1.types.ValidateSchemaRequest`): - The request object. - Request for the `ValidateSchema` + The request object. Request for the `ValidateSchema` method. parent (:class:`str`): Required. The name of the project in which to validate @@ -504,6 +516,7 @@ async def validate_schema( 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. @@ -528,6 +541,7 @@ async def validate_schema( # 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: @@ -565,9 +579,9 @@ async def validate_message( Args: request (:class:`google.pubsub_v1.types.ValidateMessageRequest`): - The request object. - Request for the `ValidateMessage` + 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. @@ -579,6 +593,7 @@ async def validate_message( Response for the ValidateMessage method. """ # Create or coerce a protobuf request object. + request = schema.ValidateMessageRequest(request) # Wrap the RPC method; this adds retry and timeout information, diff --git a/google/pubsub_v1/services/schema_service/client.py b/google/pubsub_v1/services/schema_service/client.py index cb85dbd51..5f65a0388 100644 --- a/google/pubsub_v1/services/schema_service/client.py +++ b/google/pubsub_v1/services/schema_service/client.py @@ -1,4 +1,5 @@ # -*- coding: utf-8 -*- + # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -13,6 +14,7 @@ # See the License for the specific language governing permissions and # limitations under the License. # + from collections import OrderedDict from distutils import util import os @@ -35,6 +37,7 @@ 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 @@ -353,8 +356,7 @@ def create_schema( Args: request (google.pubsub_v1.types.CreateSchemaRequest): - The request object. - Request for the CreateSchema method. + 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}``. @@ -383,6 +385,7 @@ def create_schema( 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. @@ -409,8 +412,10 @@ def create_schema( # 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: @@ -447,8 +452,7 @@ def get_schema( Args: request (google.pubsub_v1.types.GetSchemaRequest): - The request object. - Request for the GetSchema method. + The request object. Request for the GetSchema method. name (str): Required. The name of the schema to get. Format is ``projects/{project}/schemas/{schema}``. @@ -456,6 +460,7 @@ def get_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. @@ -482,8 +487,10 @@ def get_schema( # 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 @@ -516,8 +523,7 @@ def list_schemas( Args: request (google.pubsub_v1.types.ListSchemasRequest): - The request object. - Request for the `ListSchemas` + The request object. Request for the `ListSchemas` method. parent (str): Required. The name of the project in which to list @@ -526,6 +532,7 @@ def list_schemas( 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. @@ -556,8 +563,10 @@ def list_schemas( # 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 @@ -596,8 +605,7 @@ def delete_schema( Args: request (google.pubsub_v1.types.DeleteSchemaRequest): - The request object. - Request for the `DeleteSchema` + The request object. Request for the `DeleteSchema` method. name (str): Required. Name of the schema to delete. Format is @@ -606,6 +614,7 @@ def delete_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. @@ -628,8 +637,10 @@ def delete_schema( # 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 @@ -662,8 +673,7 @@ def validate_schema( Args: request (google.pubsub_v1.types.ValidateSchemaRequest): - The request object. - Request for the `ValidateSchema` + The request object. Request for the `ValidateSchema` method. parent (str): Required. The name of the project in which to validate @@ -679,6 +689,7 @@ def validate_schema( 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. @@ -705,8 +716,10 @@ def validate_schema( # 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: @@ -740,9 +753,9 @@ def validate_message( Args: request (google.pubsub_v1.types.ValidateMessageRequest): - The request object. - Request for the `ValidateMessage` + 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. @@ -754,6 +767,7 @@ def validate_message( Response for the ValidateMessage method. """ # 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 diff --git a/google/pubsub_v1/services/schema_service/pagers.py b/google/pubsub_v1/services/schema_service/pagers.py index a6bf1ccc0..2712f37c6 100644 --- a/google/pubsub_v1/services/schema_service/pagers.py +++ b/google/pubsub_v1/services/schema_service/pagers.py @@ -1,4 +1,5 @@ # -*- coding: utf-8 -*- + # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -13,6 +14,7 @@ # See the License for the specific language governing permissions and # limitations under the License. # + from typing import ( Any, AsyncIterable, diff --git a/google/pubsub_v1/services/schema_service/transports/__init__.py b/google/pubsub_v1/services/schema_service/transports/__init__.py index 81ebf8d1c..015410d3d 100644 --- a/google/pubsub_v1/services/schema_service/transports/__init__.py +++ b/google/pubsub_v1/services/schema_service/transports/__init__.py @@ -1,4 +1,5 @@ # -*- coding: utf-8 -*- + # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -13,6 +14,7 @@ # See the License for the specific language governing permissions and # limitations under the License. # + from collections import OrderedDict from typing import Dict, Type diff --git a/google/pubsub_v1/services/schema_service/transports/base.py b/google/pubsub_v1/services/schema_service/transports/base.py index fa897ee68..fec2169ae 100644 --- a/google/pubsub_v1/services/schema_service/transports/base.py +++ b/google/pubsub_v1/services/schema_service/transports/base.py @@ -1,4 +1,5 @@ # -*- coding: utf-8 -*- + # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -13,13 +14,12 @@ # 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 packaging.version +import typing import pkg_resources from google import auth # type: ignore -import google.api_core # type: ignore from google.api_core import exceptions # type: ignore from google.api_core import gapic_v1 # type: ignore from google.api_core import retry as retries # type: ignore @@ -31,6 +31,7 @@ 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( client_library_version=pkg_resources.get_distribution( @@ -40,17 +41,6 @@ except pkg_resources.DistributionNotFound: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() -try: - # google.auth.__version__ was added in 1.26.0 - _GOOGLE_AUTH_VERSION = auth.__version__ -except AttributeError: - try: # try pkg_resources if it is available - _GOOGLE_AUTH_VERSION = pkg_resources.get_distribution("google-auth").version - except pkg_resources.DistributionNotFound: # pragma: NO COVER - _GOOGLE_AUTH_VERSION = None - -_API_CORE_VERSION = google.api_core.__version__ - class SchemaServiceTransport(abc.ABC): """Abstract transport class for SchemaService.""" @@ -60,24 +50,21 @@ class SchemaServiceTransport(abc.ABC): "https://www.googleapis.com/auth/pubsub", ) - DEFAULT_HOST: str = "pubsub.googleapis.com" - def __init__( self, *, - host: str = DEFAULT_HOST, + host: str = "pubsub.googleapis.com", credentials: credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, + credentials_file: typing.Optional[str] = None, + scopes: typing.Optional[typing.Sequence[str]] = AUTH_SCOPES, + quota_project_id: typing.Optional[str] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, **kwargs, ) -> None: """Instantiate the transport. Args: - host (Optional[str]): - The hostname to connect to. + 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 @@ -86,7 +73,7 @@ def __init__( 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. + scope (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): @@ -100,8 +87,6 @@ def __init__( host += ":443" self._host = host - scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) - # Save the scopes. self._scopes = scopes or self.AUTH_SCOPES @@ -114,62 +99,17 @@ def __init__( if credentials_file is not None: credentials, _ = auth.load_credentials_from_file( - credentials_file, **scopes_kwargs, quota_project_id=quota_project_id + credentials_file, scopes=self._scopes, quota_project_id=quota_project_id ) elif credentials is None: credentials, _ = auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=self._scopes, quota_project_id=quota_project_id ) # Save the credentials. self._credentials = credentials - # TODO(busunkim): These two class methods are in the base transport - # to avoid duplicating code across the transport classes. These functions - # should be deleted once the minimum required versions of google-api-core - # and google-auth are increased. - - # TODO: Remove this function once google-auth >= 1.25.0 is required - @classmethod - def _get_scopes_kwargs( - cls, host: str, scopes: Optional[Sequence[str]] - ) -> Dict[str, Optional[Sequence[str]]]: - """Returns scopes kwargs to pass to google-auth methods depending on the google-auth version""" - - scopes_kwargs = {} - - if _GOOGLE_AUTH_VERSION and ( - packaging.version.parse(_GOOGLE_AUTH_VERSION) - >= packaging.version.parse("1.25.0") - ): - scopes_kwargs = {"scopes": scopes, "default_scopes": cls.AUTH_SCOPES} - else: - scopes_kwargs = {"scopes": scopes or cls.AUTH_SCOPES} - - return scopes_kwargs - - # TODO: Remove this function once google-api-core >= 1.26.0 is required - @classmethod - def _get_self_signed_jwt_kwargs( - cls, host: str, scopes: Optional[Sequence[str]] - ) -> Dict[str, Union[Optional[Sequence[str]], str]]: - """Returns kwargs to pass to grpc_helpers.create_channel depending on the google-api-core version""" - - self_signed_jwt_kwargs: Dict[str, Union[Optional[Sequence[str]], str]] = {} - - if _API_CORE_VERSION and ( - packaging.version.parse(_API_CORE_VERSION) - >= packaging.version.parse("1.26.0") - ): - self_signed_jwt_kwargs["default_scopes"] = cls.AUTH_SCOPES - self_signed_jwt_kwargs["scopes"] = scopes - self_signed_jwt_kwargs["default_host"] = cls.DEFAULT_HOST - else: - self_signed_jwt_kwargs["scopes"] = scopes or cls.AUTH_SCOPES - - return self_signed_jwt_kwargs - def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. self._wrapped_methods = { @@ -196,45 +136,49 @@ def _prep_wrapped_messages(self, client_info): @property def create_schema( self, - ) -> Callable[ + ) -> typing.Callable[ [gp_schema.CreateSchemaRequest], - Union[gp_schema.Schema, Awaitable[gp_schema.Schema]], + typing.Union[gp_schema.Schema, typing.Awaitable[gp_schema.Schema]], ]: raise NotImplementedError() @property def get_schema( self, - ) -> Callable[ - [schema.GetSchemaRequest], Union[schema.Schema, Awaitable[schema.Schema]] + ) -> typing.Callable[ + [schema.GetSchemaRequest], + typing.Union[schema.Schema, typing.Awaitable[schema.Schema]], ]: raise NotImplementedError() @property def list_schemas( self, - ) -> Callable[ + ) -> typing.Callable[ [schema.ListSchemasRequest], - Union[schema.ListSchemasResponse, Awaitable[schema.ListSchemasResponse]], + typing.Union[ + schema.ListSchemasResponse, typing.Awaitable[schema.ListSchemasResponse] + ], ]: raise NotImplementedError() @property def delete_schema( self, - ) -> Callable[ - [schema.DeleteSchemaRequest], Union[empty.Empty, Awaitable[empty.Empty]] + ) -> typing.Callable[ + [schema.DeleteSchemaRequest], + typing.Union[empty.Empty, typing.Awaitable[empty.Empty]], ]: raise NotImplementedError() @property def validate_schema( self, - ) -> Callable[ + ) -> typing.Callable[ [gp_schema.ValidateSchemaRequest], - Union[ + typing.Union[ gp_schema.ValidateSchemaResponse, - Awaitable[gp_schema.ValidateSchemaResponse], + typing.Awaitable[gp_schema.ValidateSchemaResponse], ], ]: raise NotImplementedError() @@ -242,10 +186,11 @@ def validate_schema( @property def validate_message( self, - ) -> Callable[ + ) -> typing.Callable[ [schema.ValidateMessageRequest], - Union[ - schema.ValidateMessageResponse, Awaitable[schema.ValidateMessageResponse] + typing.Union[ + schema.ValidateMessageResponse, + typing.Awaitable[schema.ValidateMessageResponse], ], ]: raise NotImplementedError() @@ -253,29 +198,29 @@ def validate_message( @property def set_iam_policy( self, - ) -> Callable[ + ) -> typing.Callable[ [iam_policy.SetIamPolicyRequest], - Union[policy.Policy, Awaitable[policy.Policy]], + typing.Union[policy.Policy, typing.Awaitable[policy.Policy]], ]: raise NotImplementedError() @property def get_iam_policy( self, - ) -> Callable[ + ) -> typing.Callable[ [iam_policy.GetIamPolicyRequest], - Union[policy.Policy, Awaitable[policy.Policy]], + typing.Union[policy.Policy, typing.Awaitable[policy.Policy]], ]: raise NotImplementedError() @property def test_iam_permissions( self, - ) -> Callable[ + ) -> typing.Callable[ [iam_policy.TestIamPermissionsRequest], - Union[ + typing.Union[ iam_policy.TestIamPermissionsResponse, - Awaitable[iam_policy.TestIamPermissionsResponse], + typing.Awaitable[iam_policy.TestIamPermissionsResponse], ], ]: raise NotImplementedError() diff --git a/google/pubsub_v1/services/schema_service/transports/grpc.py b/google/pubsub_v1/services/schema_service/transports/grpc.py index 55967e792..ed9822e01 100644 --- a/google/pubsub_v1/services/schema_service/transports/grpc.py +++ b/google/pubsub_v1/services/schema_service/transports/grpc.py @@ -1,4 +1,5 @@ # -*- coding: utf-8 -*- + # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -13,8 +14,9 @@ # 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 typing import Callable, Dict, Optional, Sequence, Tuple from google.api_core import grpc_helpers # type: ignore from google.api_core import gapic_v1 # type: ignore @@ -29,6 +31,7 @@ from google.protobuf import empty_pb2 as empty # 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 @@ -65,8 +68,7 @@ def __init__( """Instantiate the transport. Args: - host (Optional[str]): - The hostname to connect to. + 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 @@ -208,15 +210,13 @@ def create_channel( google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` and ``credentials_file`` are passed. """ - - self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) - + scopes = scopes or cls.AUTH_SCOPES return grpc_helpers.create_channel( host, credentials=credentials, credentials_file=credentials_file, + scopes=scopes, quota_project_id=quota_project_id, - **self_signed_jwt_kwargs, **kwargs, ) @@ -230,9 +230,7 @@ def grpc_channel(self) -> grpc.Channel: def create_schema( self, ) -> Callable[[gp_schema.CreateSchemaRequest], gp_schema.Schema]: - r"""Return a callable for the - create schema - method over gRPC. + r"""Return a callable for the create schema method over gRPC. Creates a schema. @@ -256,9 +254,7 @@ def create_schema( @property def get_schema(self) -> Callable[[schema.GetSchemaRequest], schema.Schema]: - r"""Return a callable for the - get schema - method over gRPC. + r"""Return a callable for the get schema method over gRPC. Gets a schema. @@ -284,9 +280,7 @@ def get_schema(self) -> Callable[[schema.GetSchemaRequest], schema.Schema]: def list_schemas( self, ) -> Callable[[schema.ListSchemasRequest], schema.ListSchemasResponse]: - r"""Return a callable for the - list schemas - method over gRPC. + r"""Return a callable for the list schemas method over gRPC. Lists schemas in a project. @@ -310,9 +304,7 @@ def list_schemas( @property def delete_schema(self) -> Callable[[schema.DeleteSchemaRequest], empty.Empty]: - r"""Return a callable for the - delete schema - method over gRPC. + r"""Return a callable for the delete schema method over gRPC. Deletes a schema. @@ -338,9 +330,7 @@ def delete_schema(self) -> Callable[[schema.DeleteSchemaRequest], empty.Empty]: def validate_schema( self, ) -> Callable[[gp_schema.ValidateSchemaRequest], gp_schema.ValidateSchemaResponse]: - r"""Return a callable for the - validate schema - method over gRPC. + r"""Return a callable for the validate schema method over gRPC. Validates a schema. @@ -366,9 +356,7 @@ def validate_schema( def validate_message( self, ) -> Callable[[schema.ValidateMessageRequest], schema.ValidateMessageResponse]: - r"""Return a callable for the - validate message - method over gRPC. + r"""Return a callable for the validate message method over gRPC. Validates a message against a schema. diff --git a/google/pubsub_v1/services/schema_service/transports/grpc_asyncio.py b/google/pubsub_v1/services/schema_service/transports/grpc_asyncio.py index 957b402d0..c7cb3ac63 100644 --- a/google/pubsub_v1/services/schema_service/transports/grpc_asyncio.py +++ b/google/pubsub_v1/services/schema_service/transports/grpc_asyncio.py @@ -1,4 +1,5 @@ # -*- coding: utf-8 -*- + # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -13,15 +14,15 @@ # 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 typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple from google.api_core import gapic_v1 # type: ignore from google.api_core import grpc_helpers_async # type: ignore from google import auth # type: ignore from google.auth import credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore -import packaging.version import grpc # type: ignore from grpc.experimental import aio # type: ignore @@ -31,6 +32,7 @@ from google.protobuf import empty_pb2 as empty # 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 @@ -82,15 +84,13 @@ def create_channel( Returns: aio.Channel: A gRPC AsyncIO channel object. """ - - self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) - + scopes = scopes or cls.AUTH_SCOPES return grpc_helpers_async.create_channel( host, credentials=credentials, credentials_file=credentials_file, + scopes=scopes, quota_project_id=quota_project_id, - **self_signed_jwt_kwargs, **kwargs, ) @@ -112,8 +112,7 @@ def __init__( """Instantiate the transport. Args: - host (Optional[str]): - The hostname to connect to. + 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 @@ -171,6 +170,7 @@ def __init__( # 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 @@ -234,9 +234,7 @@ def grpc_channel(self) -> aio.Channel: def create_schema( self, ) -> Callable[[gp_schema.CreateSchemaRequest], Awaitable[gp_schema.Schema]]: - r"""Return a callable for the - create schema - method over gRPC. + r"""Return a callable for the create schema method over gRPC. Creates a schema. @@ -262,9 +260,7 @@ def create_schema( def get_schema( self, ) -> Callable[[schema.GetSchemaRequest], Awaitable[schema.Schema]]: - r"""Return a callable for the - get schema - method over gRPC. + r"""Return a callable for the get schema method over gRPC. Gets a schema. @@ -290,9 +286,7 @@ def get_schema( def list_schemas( self, ) -> Callable[[schema.ListSchemasRequest], Awaitable[schema.ListSchemasResponse]]: - r"""Return a callable for the - list schemas - method over gRPC. + r"""Return a callable for the list schemas method over gRPC. Lists schemas in a project. @@ -318,9 +312,7 @@ def list_schemas( def delete_schema( self, ) -> Callable[[schema.DeleteSchemaRequest], Awaitable[empty.Empty]]: - r"""Return a callable for the - delete schema - method over gRPC. + r"""Return a callable for the delete schema method over gRPC. Deletes a schema. @@ -348,9 +340,7 @@ def validate_schema( ) -> Callable[ [gp_schema.ValidateSchemaRequest], Awaitable[gp_schema.ValidateSchemaResponse] ]: - r"""Return a callable for the - validate schema - method over gRPC. + r"""Return a callable for the validate schema method over gRPC. Validates a schema. @@ -378,9 +368,7 @@ def validate_message( ) -> Callable[ [schema.ValidateMessageRequest], Awaitable[schema.ValidateMessageResponse] ]: - r"""Return a callable for the - validate message - method over gRPC. + r"""Return a callable for the validate message method over gRPC. Validates a message against a schema. diff --git a/google/pubsub_v1/services/subscriber/__init__.py b/google/pubsub_v1/services/subscriber/__init__.py index 0961d69d1..361085a5e 100644 --- a/google/pubsub_v1/services/subscriber/__init__.py +++ b/google/pubsub_v1/services/subscriber/__init__.py @@ -1,4 +1,5 @@ # -*- coding: utf-8 -*- + # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -13,6 +14,7 @@ # See the License for the specific language governing permissions and # limitations under the License. # + from .client import SubscriberClient from .async_client import SubscriberAsyncClient diff --git a/google/pubsub_v1/services/subscriber/async_client.py b/google/pubsub_v1/services/subscriber/async_client.py index 781df6d4c..7dbc3c5ed 100644 --- a/google/pubsub_v1/services/subscriber/async_client.py +++ b/google/pubsub_v1/services/subscriber/async_client.py @@ -1,4 +1,5 @@ # -*- coding: utf-8 -*- + # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -13,6 +14,7 @@ # See the License for the specific language governing permissions and # limitations under the License. # + from collections import OrderedDict import functools import re @@ -42,6 +44,7 @@ from google.protobuf import timestamp_pb2 as timestamp # 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 @@ -65,20 +68,25 @@ class SubscriberAsyncClient: 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 @@ -169,6 +177,7 @@ def __init__( google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport creation failed for any reason. """ + self._client = SubscriberClient( credentials=credentials, transport=transport, @@ -204,8 +213,7 @@ async def create_subscription( Args: request (:class:`google.pubsub_v1.types.Subscription`): - The request object. - A subscription resource. + The request object. A subscription resource. name (:class:`str`): Required. The name of the subscription. It must have the format @@ -268,6 +276,7 @@ async def create_subscription( 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. @@ -292,6 +301,7 @@ async def create_subscription( # 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: @@ -345,8 +355,7 @@ async def get_subscription( Args: request (:class:`google.pubsub_v1.types.GetSubscriptionRequest`): - The request object. - Request for the GetSubscription + The request object. Request for the GetSubscription method. subscription (:class:`str`): Required. The name of the subscription to get. Format is @@ -355,6 +364,7 @@ async def get_subscription( 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. @@ -379,6 +389,7 @@ async def get_subscription( # If we have keyword arguments corresponding to fields on the # request, apply these. + if subscription is not None: request.subscription = subscription @@ -429,9 +440,9 @@ async def update_subscription( Args: request (:class:`google.pubsub_v1.types.UpdateSubscriptionRequest`): - The request object. - Request for the UpdateSubscription + 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. @@ -443,6 +454,7 @@ async def update_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, @@ -487,8 +499,7 @@ async def list_subscriptions( Args: request (:class:`google.pubsub_v1.types.ListSubscriptionsRequest`): - The request object. - Request for the `ListSubscriptions` + The request object. Request for the `ListSubscriptions` method. project (:class:`str`): Required. The name of the project in which to list @@ -497,6 +508,7 @@ async def list_subscriptions( 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. @@ -525,6 +537,7 @@ async def list_subscriptions( # If we have keyword arguments corresponding to fields on the # request, apply these. + if project is not None: request.project = project @@ -583,8 +596,7 @@ async def delete_subscription( Args: request (:class:`google.pubsub_v1.types.DeleteSubscriptionRequest`): - The request object. - Request for the DeleteSubscription + The request object. Request for the DeleteSubscription method. subscription (:class:`str`): Required. The subscription to delete. Format is @@ -593,6 +605,7 @@ async def delete_subscription( 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. @@ -613,6 +626,7 @@ async def delete_subscription( # If we have keyword arguments corresponding to fields on the # request, apply these. + if subscription is not None: request.subscription = subscription @@ -664,8 +678,7 @@ async def modify_ack_deadline( Args: request (:class:`google.pubsub_v1.types.ModifyAckDeadlineRequest`): - The request object. - Request for the ModifyAckDeadline + The request object. Request for the ModifyAckDeadline method. subscription (:class:`str`): Required. The name of the subscription. Format is @@ -695,6 +708,7 @@ async def modify_ack_deadline( 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. @@ -715,10 +729,12 @@ async def modify_ack_deadline( # 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) @@ -771,8 +787,7 @@ async def acknowledge( Args: request (:class:`google.pubsub_v1.types.AcknowledgeRequest`): - The request object. - Request for the Acknowledge method. + The request object. Request for the Acknowledge method. subscription (:class:`str`): Required. The subscription whose message is being acknowledged. Format is @@ -789,6 +804,7 @@ async def acknowledge( 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. @@ -809,8 +825,10 @@ async def acknowledge( # 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) @@ -859,8 +877,7 @@ async def pull( Args: request (:class:`google.pubsub_v1.types.PullRequest`): - The request object. - Request for the `Pull` method. + The request object. Request for the `Pull` method. subscription (:class:`str`): Required. The subscription from which messages should be pulled. Format is @@ -893,6 +910,7 @@ async def pull( 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. @@ -917,6 +935,7 @@ async def pull( # 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: @@ -982,8 +1001,7 @@ def streaming_pull( Args: requests (AsyncIterator[`google.pubsub_v1.types.StreamingPullRequest`]): - The request object AsyncIterator. - Request for the `StreamingPull` + 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 @@ -1048,8 +1066,7 @@ async def modify_push_config( Args: request (:class:`google.pubsub_v1.types.ModifyPushConfigRequest`): - The request object. - Request for the ModifyPushConfig + The request object. Request for the ModifyPushConfig method. subscription (:class:`str`): Required. The name of the subscription. Format is @@ -1070,6 +1087,7 @@ async def modify_push_config( 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. @@ -1090,6 +1108,7 @@ async def modify_push_config( # 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: @@ -1142,8 +1161,7 @@ async def get_snapshot( Args: request (:class:`google.pubsub_v1.types.GetSnapshotRequest`): - The request object. - Request for the GetSnapshot method. + 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}``. @@ -1151,6 +1169,7 @@ async def get_snapshot( 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. @@ -1181,6 +1200,7 @@ async def get_snapshot( # If we have keyword arguments corresponding to fields on the # request, apply these. + if snapshot is not None: request.snapshot = snapshot @@ -1232,8 +1252,7 @@ async def list_snapshots( Args: request (:class:`google.pubsub_v1.types.ListSnapshotsRequest`): - The request object. - Request for the `ListSnapshots` + The request object. Request for the `ListSnapshots` method. project (:class:`str`): Required. The name of the project in which to list @@ -1242,6 +1261,7 @@ async def list_snapshots( 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. @@ -1270,6 +1290,7 @@ async def list_snapshots( # If we have keyword arguments corresponding to fields on the # request, apply these. + if project is not None: request.project = project @@ -1342,8 +1363,7 @@ async def create_snapshot( Args: request (:class:`google.pubsub_v1.types.CreateSnapshotRequest`): - The request object. - Request for the `CreateSnapshot` + The request object. Request for the `CreateSnapshot` method. name (:class:`str`): Required. User-provided name for this snapshot. If the @@ -1372,6 +1392,7 @@ async def create_snapshot( 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. @@ -1402,6 +1423,7 @@ async def create_snapshot( # 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: @@ -1452,9 +1474,9 @@ async def update_snapshot( Args: request (:class:`google.pubsub_v1.types.UpdateSnapshotRequest`): - The request object. - Request for the UpdateSnapshot + 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. @@ -1472,6 +1494,7 @@ async def update_snapshot( """ # Create or coerce a protobuf request object. + request = pubsub.UpdateSnapshotRequest(request) # Wrap the RPC method; this adds retry and timeout information, @@ -1525,8 +1548,7 @@ async def delete_snapshot( Args: request (:class:`google.pubsub_v1.types.DeleteSnapshotRequest`): - The request object. - Request for the `DeleteSnapshot` + The request object. Request for the `DeleteSnapshot` method. snapshot (:class:`str`): Required. The name of the snapshot to delete. Format is @@ -1535,6 +1557,7 @@ async def delete_snapshot( 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. @@ -1555,6 +1578,7 @@ async def delete_snapshot( # If we have keyword arguments corresponding to fields on the # request, apply these. + if snapshot is not None: request.snapshot = snapshot @@ -1604,8 +1628,8 @@ async def seek( Args: request (:class:`google.pubsub_v1.types.SeekRequest`): - The request object. - Request for the `Seek` method. + 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. @@ -1617,6 +1641,7 @@ async def seek( 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, diff --git a/google/pubsub_v1/services/subscriber/client.py b/google/pubsub_v1/services/subscriber/client.py index b9c988159..e2fbde711 100644 --- a/google/pubsub_v1/services/subscriber/client.py +++ b/google/pubsub_v1/services/subscriber/client.py @@ -1,4 +1,5 @@ # -*- coding: utf-8 -*- + # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -13,6 +14,7 @@ # See the License for the specific language governing permissions and # limitations under the License. # + from collections import OrderedDict from distutils import util import functools @@ -50,6 +52,7 @@ from google.pubsub_v1.types import pubsub import grpc + from .transports.base import SubscriberTransport, DEFAULT_CLIENT_INFO from .transports.grpc import SubscriberGrpcTransport from .transports.grpc_asyncio import SubscriberGrpcAsyncIOTransport @@ -436,8 +439,7 @@ def create_subscription( Args: request (google.pubsub_v1.types.Subscription): - The request object. - A subscription resource. + The request object. A subscription resource. name (str): Required. The name of the subscription. It must have the format @@ -500,6 +502,7 @@ def create_subscription( 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. @@ -526,8 +529,10 @@ def create_subscription( # 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: @@ -567,8 +572,7 @@ def get_subscription( Args: request (google.pubsub_v1.types.GetSubscriptionRequest): - The request object. - Request for the GetSubscription + The request object. Request for the GetSubscription method. subscription (str): Required. The name of the subscription to get. Format is @@ -577,6 +581,7 @@ def get_subscription( 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. @@ -603,8 +608,10 @@ def get_subscription( # 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 @@ -641,9 +648,9 @@ def update_subscription( Args: request (google.pubsub_v1.types.UpdateSubscriptionRequest): - The request object. - Request for the UpdateSubscription + 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. @@ -655,6 +662,7 @@ def update_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 @@ -694,8 +702,7 @@ def list_subscriptions( Args: request (google.pubsub_v1.types.ListSubscriptionsRequest): - The request object. - Request for the `ListSubscriptions` + The request object. Request for the `ListSubscriptions` method. project (str): Required. The name of the project in which to list @@ -704,6 +711,7 @@ def list_subscriptions( 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. @@ -734,8 +742,10 @@ def list_subscriptions( # 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 @@ -780,8 +790,7 @@ def delete_subscription( Args: request (google.pubsub_v1.types.DeleteSubscriptionRequest): - The request object. - Request for the DeleteSubscription + The request object. Request for the DeleteSubscription method. subscription (str): Required. The subscription to delete. Format is @@ -790,6 +799,7 @@ def delete_subscription( 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. @@ -812,8 +822,10 @@ def delete_subscription( # 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 @@ -855,8 +867,7 @@ def modify_ack_deadline( Args: request (google.pubsub_v1.types.ModifyAckDeadlineRequest): - The request object. - Request for the ModifyAckDeadline + The request object. Request for the ModifyAckDeadline method. subscription (str): Required. The name of the subscription. Format is @@ -886,6 +897,7 @@ def modify_ack_deadline( 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. @@ -908,8 +920,10 @@ def modify_ack_deadline( # 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: @@ -956,8 +970,7 @@ def acknowledge( Args: request (google.pubsub_v1.types.AcknowledgeRequest): - The request object. - Request for the Acknowledge method. + The request object. Request for the Acknowledge method. subscription (str): Required. The subscription whose message is being acknowledged. Format is @@ -974,6 +987,7 @@ def acknowledge( 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. @@ -996,8 +1010,10 @@ def acknowledge( # 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: @@ -1038,8 +1054,7 @@ def pull( Args: request (google.pubsub_v1.types.PullRequest): - The request object. - Request for the `Pull` method. + The request object. Request for the `Pull` method. subscription (str): Required. The subscription from which messages should be pulled. Format is @@ -1072,6 +1087,7 @@ def pull( 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. @@ -1098,8 +1114,10 @@ def pull( # 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: @@ -1151,8 +1169,7 @@ def streaming_pull( Args: requests (Iterator[google.pubsub_v1.types.StreamingPullRequest]): - The request object iterator. - Request for the `StreamingPull` + 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 @@ -1206,8 +1223,7 @@ def modify_push_config( Args: request (google.pubsub_v1.types.ModifyPushConfigRequest): - The request object. - Request for the ModifyPushConfig + The request object. Request for the ModifyPushConfig method. subscription (str): Required. The name of the subscription. Format is @@ -1228,6 +1244,7 @@ def modify_push_config( 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. @@ -1250,8 +1267,10 @@ def modify_push_config( # 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: @@ -1294,8 +1313,7 @@ def get_snapshot( Args: request (google.pubsub_v1.types.GetSnapshotRequest): - The request object. - Request for the GetSnapshot method. + The request object. Request for the GetSnapshot method. snapshot (str): Required. The name of the snapshot to get. Format is ``projects/{project}/snapshots/{snap}``. @@ -1303,6 +1321,7 @@ def get_snapshot( 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. @@ -1335,8 +1354,10 @@ def get_snapshot( # 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 @@ -1374,8 +1395,7 @@ def list_snapshots( Args: request (google.pubsub_v1.types.ListSnapshotsRequest): - The request object. - Request for the `ListSnapshots` + The request object. Request for the `ListSnapshots` method. project (str): Required. The name of the project in which to list @@ -1384,6 +1404,7 @@ def list_snapshots( 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. @@ -1414,8 +1435,10 @@ def list_snapshots( # 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 @@ -1474,8 +1497,7 @@ def create_snapshot( Args: request (google.pubsub_v1.types.CreateSnapshotRequest): - The request object. - Request for the `CreateSnapshot` + The request object. Request for the `CreateSnapshot` method. name (str): Required. User-provided name for this snapshot. If the @@ -1504,6 +1526,7 @@ def create_snapshot( 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. @@ -1536,8 +1559,10 @@ def create_snapshot( # 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: @@ -1578,9 +1603,9 @@ def update_snapshot( Args: request (google.pubsub_v1.types.UpdateSnapshotRequest): - The request object. - Request for the UpdateSnapshot + 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. @@ -1598,6 +1623,7 @@ def update_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 @@ -1646,8 +1672,7 @@ def delete_snapshot( Args: request (google.pubsub_v1.types.DeleteSnapshotRequest): - The request object. - Request for the `DeleteSnapshot` + The request object. Request for the `DeleteSnapshot` method. snapshot (str): Required. The name of the snapshot to delete. Format is @@ -1656,6 +1681,7 @@ def delete_snapshot( 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. @@ -1678,8 +1704,10 @@ def delete_snapshot( # 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 @@ -1719,8 +1747,8 @@ def seek( Args: request (google.pubsub_v1.types.SeekRequest): - The request object. - Request for the `Seek` method. + 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. @@ -1732,6 +1760,7 @@ def seek( 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 diff --git a/google/pubsub_v1/services/subscriber/pagers.py b/google/pubsub_v1/services/subscriber/pagers.py index 3e0de8ddc..b7ec9f6e3 100644 --- a/google/pubsub_v1/services/subscriber/pagers.py +++ b/google/pubsub_v1/services/subscriber/pagers.py @@ -1,4 +1,5 @@ # -*- coding: utf-8 -*- + # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -13,6 +14,7 @@ # See the License for the specific language governing permissions and # limitations under the License. # + from typing import ( Any, AsyncIterable, diff --git a/google/pubsub_v1/services/subscriber/transports/__init__.py b/google/pubsub_v1/services/subscriber/transports/__init__.py index 023406c8f..0246cfeca 100644 --- a/google/pubsub_v1/services/subscriber/transports/__init__.py +++ b/google/pubsub_v1/services/subscriber/transports/__init__.py @@ -1,4 +1,5 @@ # -*- coding: utf-8 -*- + # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -13,6 +14,7 @@ # See the License for the specific language governing permissions and # limitations under the License. # + from collections import OrderedDict from typing import Dict, Type diff --git a/google/pubsub_v1/services/subscriber/transports/base.py b/google/pubsub_v1/services/subscriber/transports/base.py index d93d08e30..b8a1b97b3 100644 --- a/google/pubsub_v1/services/subscriber/transports/base.py +++ b/google/pubsub_v1/services/subscriber/transports/base.py @@ -1,4 +1,5 @@ # -*- coding: utf-8 -*- + # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -13,13 +14,12 @@ # 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 packaging.version +import typing import pkg_resources from google import auth # type: ignore -import google.api_core # type: ignore from google.api_core import exceptions # type: ignore from google.api_core import gapic_v1 # type: ignore from google.api_core import retry as retries # type: ignore @@ -30,6 +30,7 @@ from google.protobuf import empty_pb2 as empty # type: ignore from google.pubsub_v1.types import pubsub + try: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( client_library_version=pkg_resources.get_distribution( @@ -39,17 +40,6 @@ except pkg_resources.DistributionNotFound: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() -try: - # google.auth.__version__ was added in 1.26.0 - _GOOGLE_AUTH_VERSION = auth.__version__ -except AttributeError: - try: # try pkg_resources if it is available - _GOOGLE_AUTH_VERSION = pkg_resources.get_distribution("google-auth").version - except pkg_resources.DistributionNotFound: # pragma: NO COVER - _GOOGLE_AUTH_VERSION = None - -_API_CORE_VERSION = google.api_core.__version__ - class SubscriberTransport(abc.ABC): """Abstract transport class for Subscriber.""" @@ -59,24 +49,21 @@ class SubscriberTransport(abc.ABC): "https://www.googleapis.com/auth/pubsub", ) - DEFAULT_HOST: str = "pubsub.googleapis.com" - def __init__( self, *, - host: str = DEFAULT_HOST, + host: str = "pubsub.googleapis.com", credentials: credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, + credentials_file: typing.Optional[str] = None, + scopes: typing.Optional[typing.Sequence[str]] = AUTH_SCOPES, + quota_project_id: typing.Optional[str] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, **kwargs, ) -> None: """Instantiate the transport. Args: - host (Optional[str]): - The hostname to connect to. + 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 @@ -85,7 +72,7 @@ def __init__( 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. + scope (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): @@ -99,8 +86,6 @@ def __init__( host += ":443" self._host = host - scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) - # Save the scopes. self._scopes = scopes or self.AUTH_SCOPES @@ -113,62 +98,17 @@ def __init__( if credentials_file is not None: credentials, _ = auth.load_credentials_from_file( - credentials_file, **scopes_kwargs, quota_project_id=quota_project_id + credentials_file, scopes=self._scopes, quota_project_id=quota_project_id ) elif credentials is None: credentials, _ = auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=self._scopes, quota_project_id=quota_project_id ) # Save the credentials. self._credentials = credentials - # TODO(busunkim): These two class methods are in the base transport - # to avoid duplicating code across the transport classes. These functions - # should be deleted once the minimum required versions of google-api-core - # and google-auth are increased. - - # TODO: Remove this function once google-auth >= 1.25.0 is required - @classmethod - def _get_scopes_kwargs( - cls, host: str, scopes: Optional[Sequence[str]] - ) -> Dict[str, Optional[Sequence[str]]]: - """Returns scopes kwargs to pass to google-auth methods depending on the google-auth version""" - - scopes_kwargs = {} - - if _GOOGLE_AUTH_VERSION and ( - packaging.version.parse(_GOOGLE_AUTH_VERSION) - >= packaging.version.parse("1.25.0") - ): - scopes_kwargs = {"scopes": scopes, "default_scopes": cls.AUTH_SCOPES} - else: - scopes_kwargs = {"scopes": scopes or cls.AUTH_SCOPES} - - return scopes_kwargs - - # TODO: Remove this function once google-api-core >= 1.26.0 is required - @classmethod - def _get_self_signed_jwt_kwargs( - cls, host: str, scopes: Optional[Sequence[str]] - ) -> Dict[str, Union[Optional[Sequence[str]], str]]: - """Returns kwargs to pass to grpc_helpers.create_channel depending on the google-api-core version""" - - self_signed_jwt_kwargs: Dict[str, Union[Optional[Sequence[str]], str]] = {} - - if _API_CORE_VERSION and ( - packaging.version.parse(_API_CORE_VERSION) - >= packaging.version.parse("1.26.0") - ): - self_signed_jwt_kwargs["default_scopes"] = cls.AUTH_SCOPES - self_signed_jwt_kwargs["scopes"] = scopes - self_signed_jwt_kwargs["default_host"] = cls.DEFAULT_HOST - else: - self_signed_jwt_kwargs["scopes"] = scopes or cls.AUTH_SCOPES - - return self_signed_jwt_kwargs - def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. self._wrapped_methods = { @@ -403,38 +343,38 @@ def _prep_wrapped_messages(self, client_info): @property def create_subscription( self, - ) -> Callable[ + ) -> typing.Callable[ [pubsub.Subscription], - Union[pubsub.Subscription, Awaitable[pubsub.Subscription]], + typing.Union[pubsub.Subscription, typing.Awaitable[pubsub.Subscription]], ]: raise NotImplementedError() @property def get_subscription( self, - ) -> Callable[ + ) -> typing.Callable[ [pubsub.GetSubscriptionRequest], - Union[pubsub.Subscription, Awaitable[pubsub.Subscription]], + typing.Union[pubsub.Subscription, typing.Awaitable[pubsub.Subscription]], ]: raise NotImplementedError() @property def update_subscription( self, - ) -> Callable[ + ) -> typing.Callable[ [pubsub.UpdateSubscriptionRequest], - Union[pubsub.Subscription, Awaitable[pubsub.Subscription]], + typing.Union[pubsub.Subscription, typing.Awaitable[pubsub.Subscription]], ]: raise NotImplementedError() @property def list_subscriptions( self, - ) -> Callable[ + ) -> typing.Callable[ [pubsub.ListSubscriptionsRequest], - Union[ + typing.Union[ pubsub.ListSubscriptionsResponse, - Awaitable[pubsub.ListSubscriptionsResponse], + typing.Awaitable[pubsub.ListSubscriptionsResponse], ], ]: raise NotImplementedError() @@ -442,129 +382,141 @@ def list_subscriptions( @property def delete_subscription( self, - ) -> Callable[ - [pubsub.DeleteSubscriptionRequest], Union[empty.Empty, Awaitable[empty.Empty]] + ) -> typing.Callable[ + [pubsub.DeleteSubscriptionRequest], + typing.Union[empty.Empty, typing.Awaitable[empty.Empty]], ]: raise NotImplementedError() @property def modify_ack_deadline( self, - ) -> Callable[ - [pubsub.ModifyAckDeadlineRequest], Union[empty.Empty, Awaitable[empty.Empty]] + ) -> typing.Callable[ + [pubsub.ModifyAckDeadlineRequest], + typing.Union[empty.Empty, typing.Awaitable[empty.Empty]], ]: raise NotImplementedError() @property def acknowledge( self, - ) -> Callable[ - [pubsub.AcknowledgeRequest], Union[empty.Empty, Awaitable[empty.Empty]] + ) -> typing.Callable[ + [pubsub.AcknowledgeRequest], + typing.Union[empty.Empty, typing.Awaitable[empty.Empty]], ]: raise NotImplementedError() @property def pull( self, - ) -> Callable[ - [pubsub.PullRequest], Union[pubsub.PullResponse, Awaitable[pubsub.PullResponse]] + ) -> typing.Callable[ + [pubsub.PullRequest], + typing.Union[pubsub.PullResponse, typing.Awaitable[pubsub.PullResponse]], ]: raise NotImplementedError() @property def streaming_pull( self, - ) -> Callable[ + ) -> typing.Callable[ [pubsub.StreamingPullRequest], - Union[pubsub.StreamingPullResponse, Awaitable[pubsub.StreamingPullResponse]], + typing.Union[ + pubsub.StreamingPullResponse, typing.Awaitable[pubsub.StreamingPullResponse] + ], ]: raise NotImplementedError() @property def modify_push_config( self, - ) -> Callable[ - [pubsub.ModifyPushConfigRequest], Union[empty.Empty, Awaitable[empty.Empty]] + ) -> typing.Callable[ + [pubsub.ModifyPushConfigRequest], + typing.Union[empty.Empty, typing.Awaitable[empty.Empty]], ]: raise NotImplementedError() @property def get_snapshot( self, - ) -> Callable[ - [pubsub.GetSnapshotRequest], Union[pubsub.Snapshot, Awaitable[pubsub.Snapshot]] + ) -> typing.Callable[ + [pubsub.GetSnapshotRequest], + typing.Union[pubsub.Snapshot, typing.Awaitable[pubsub.Snapshot]], ]: raise NotImplementedError() @property def list_snapshots( self, - ) -> Callable[ + ) -> typing.Callable[ [pubsub.ListSnapshotsRequest], - Union[pubsub.ListSnapshotsResponse, Awaitable[pubsub.ListSnapshotsResponse]], + typing.Union[ + pubsub.ListSnapshotsResponse, typing.Awaitable[pubsub.ListSnapshotsResponse] + ], ]: raise NotImplementedError() @property def create_snapshot( self, - ) -> Callable[ + ) -> typing.Callable[ [pubsub.CreateSnapshotRequest], - Union[pubsub.Snapshot, Awaitable[pubsub.Snapshot]], + typing.Union[pubsub.Snapshot, typing.Awaitable[pubsub.Snapshot]], ]: raise NotImplementedError() @property def update_snapshot( self, - ) -> Callable[ + ) -> typing.Callable[ [pubsub.UpdateSnapshotRequest], - Union[pubsub.Snapshot, Awaitable[pubsub.Snapshot]], + typing.Union[pubsub.Snapshot, typing.Awaitable[pubsub.Snapshot]], ]: raise NotImplementedError() @property def delete_snapshot( self, - ) -> Callable[ - [pubsub.DeleteSnapshotRequest], Union[empty.Empty, Awaitable[empty.Empty]] + ) -> typing.Callable[ + [pubsub.DeleteSnapshotRequest], + typing.Union[empty.Empty, typing.Awaitable[empty.Empty]], ]: raise NotImplementedError() @property def seek( self, - ) -> Callable[ - [pubsub.SeekRequest], Union[pubsub.SeekResponse, Awaitable[pubsub.SeekResponse]] + ) -> typing.Callable[ + [pubsub.SeekRequest], + typing.Union[pubsub.SeekResponse, typing.Awaitable[pubsub.SeekResponse]], ]: raise NotImplementedError() @property def set_iam_policy( self, - ) -> Callable[ + ) -> typing.Callable[ [iam_policy.SetIamPolicyRequest], - Union[policy.Policy, Awaitable[policy.Policy]], + typing.Union[policy.Policy, typing.Awaitable[policy.Policy]], ]: raise NotImplementedError() @property def get_iam_policy( self, - ) -> Callable[ + ) -> typing.Callable[ [iam_policy.GetIamPolicyRequest], - Union[policy.Policy, Awaitable[policy.Policy]], + typing.Union[policy.Policy, typing.Awaitable[policy.Policy]], ]: raise NotImplementedError() @property def test_iam_permissions( self, - ) -> Callable[ + ) -> typing.Callable[ [iam_policy.TestIamPermissionsRequest], - Union[ + typing.Union[ iam_policy.TestIamPermissionsResponse, - Awaitable[iam_policy.TestIamPermissionsResponse], + typing.Awaitable[iam_policy.TestIamPermissionsResponse], ], ]: raise NotImplementedError() diff --git a/google/pubsub_v1/services/subscriber/transports/grpc.py b/google/pubsub_v1/services/subscriber/transports/grpc.py index adb7f9b7a..b3f26f1f0 100644 --- a/google/pubsub_v1/services/subscriber/transports/grpc.py +++ b/google/pubsub_v1/services/subscriber/transports/grpc.py @@ -1,4 +1,5 @@ # -*- coding: utf-8 -*- + # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -13,8 +14,9 @@ # 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 typing import Callable, Dict, Optional, Sequence, Tuple from google.api_core import grpc_helpers # type: ignore from google.api_core import gapic_v1 # type: ignore @@ -28,6 +30,7 @@ from google.iam.v1 import policy_pb2 as policy # type: ignore from google.protobuf import empty_pb2 as empty # type: ignore from google.pubsub_v1.types import pubsub + from .base import SubscriberTransport, DEFAULT_CLIENT_INFO @@ -67,8 +70,7 @@ def __init__( """Instantiate the transport. Args: - host (Optional[str]): - The hostname to connect to. + 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 @@ -210,15 +212,13 @@ def create_channel( google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` and ``credentials_file`` are passed. """ - - self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) - + scopes = scopes or cls.AUTH_SCOPES return grpc_helpers.create_channel( host, credentials=credentials, credentials_file=credentials_file, + scopes=scopes, quota_project_id=quota_project_id, - **self_signed_jwt_kwargs, **kwargs, ) @@ -232,9 +232,7 @@ def grpc_channel(self) -> grpc.Channel: def create_subscription( self, ) -> Callable[[pubsub.Subscription], pubsub.Subscription]: - r"""Return a callable for the - create subscription - method over gRPC. + r"""Return a callable for the create subscription method over gRPC. Creates a subscription to a given topic. See the [resource name rules] @@ -272,9 +270,7 @@ def create_subscription( def get_subscription( self, ) -> Callable[[pubsub.GetSubscriptionRequest], pubsub.Subscription]: - r"""Return a callable for the - get subscription - method over gRPC. + r"""Return a callable for the get subscription method over gRPC. Gets the configuration details of a subscription. @@ -300,9 +296,7 @@ def get_subscription( def update_subscription( self, ) -> Callable[[pubsub.UpdateSubscriptionRequest], pubsub.Subscription]: - r"""Return a callable for the - update subscription - method over gRPC. + 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 @@ -330,9 +324,7 @@ def update_subscription( def list_subscriptions( self, ) -> Callable[[pubsub.ListSubscriptionsRequest], pubsub.ListSubscriptionsResponse]: - r"""Return a callable for the - list subscriptions - method over gRPC. + r"""Return a callable for the list subscriptions method over gRPC. Lists matching subscriptions. @@ -358,9 +350,7 @@ def list_subscriptions( def delete_subscription( self, ) -> Callable[[pubsub.DeleteSubscriptionRequest], empty.Empty]: - r"""Return a callable for the - delete subscription - method over gRPC. + 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 @@ -391,9 +381,7 @@ def delete_subscription( def modify_ack_deadline( self, ) -> Callable[[pubsub.ModifyAckDeadlineRequest], empty.Empty]: - r"""Return a callable for the - modify ack deadline - method over gRPC. + 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 @@ -422,9 +410,7 @@ def modify_ack_deadline( @property def acknowledge(self) -> Callable[[pubsub.AcknowledgeRequest], empty.Empty]: - r"""Return a callable for the - acknowledge - method over gRPC. + 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 @@ -455,9 +441,7 @@ def acknowledge(self) -> Callable[[pubsub.AcknowledgeRequest], empty.Empty]: @property def pull(self) -> Callable[[pubsub.PullRequest], pubsub.PullResponse]: - r"""Return a callable for the - pull - method over gRPC. + 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 @@ -485,9 +469,7 @@ def pull(self) -> Callable[[pubsub.PullRequest], pubsub.PullResponse]: def streaming_pull( self, ) -> Callable[[pubsub.StreamingPullRequest], pubsub.StreamingPullResponse]: - r"""Return a callable for the - streaming pull - method over gRPC. + 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 @@ -520,9 +502,7 @@ def streaming_pull( def modify_push_config( self, ) -> Callable[[pubsub.ModifyPushConfigRequest], empty.Empty]: - r"""Return a callable for the - modify push config - method over gRPC. + r"""Return a callable for the modify push config method over gRPC. Modifies the ``PushConfig`` for a specified subscription. @@ -552,9 +532,7 @@ def modify_push_config( @property def get_snapshot(self) -> Callable[[pubsub.GetSnapshotRequest], pubsub.Snapshot]: - r"""Return a callable for the - get snapshot - method over gRPC. + r"""Return a callable for the get snapshot method over gRPC. Gets the configuration details of a snapshot. Snapshots are used in Callable[[pubsub.GetSnapshotRequest], pubsub.Snapshot] def list_snapshots( self, ) -> Callable[[pubsub.ListSnapshotsRequest], pubsub.ListSnapshotsResponse]: - r"""Return a callable for the - list snapshots - method over gRPC. + r"""Return a callable for the list snapshots method over gRPC. Lists the existing snapshots. Snapshots are used in `Seek `__ @@ -618,9 +594,7 @@ def list_snapshots( def create_snapshot( self, ) -> Callable[[pubsub.CreateSnapshotRequest], pubsub.Snapshot]: - r"""Return a callable for the - create snapshot - method over gRPC. + r"""Return a callable for the create snapshot method over gRPC. Creates a snapshot from the requested subscription. Snapshots are used in @@ -664,9 +638,7 @@ def create_snapshot( def update_snapshot( self, ) -> Callable[[pubsub.UpdateSnapshotRequest], pubsub.Snapshot]: - r"""Return a callable for the - update snapshot - method over gRPC. + r"""Return a callable for the update snapshot method over gRPC. Updates an existing snapshot. Snapshots are used in Callable[[pubsub.DeleteSnapshotRequest], empty.Empt @property def seek(self) -> Callable[[pubsub.SeekRequest], pubsub.SeekResponse]: - r"""Return a callable for the - seek - method over gRPC. + 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 diff --git a/google/pubsub_v1/services/subscriber/transports/grpc_asyncio.py b/google/pubsub_v1/services/subscriber/transports/grpc_asyncio.py index 2f37070d7..bc385d317 100644 --- a/google/pubsub_v1/services/subscriber/transports/grpc_asyncio.py +++ b/google/pubsub_v1/services/subscriber/transports/grpc_asyncio.py @@ -1,4 +1,5 @@ # -*- coding: utf-8 -*- + # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -13,15 +14,15 @@ # 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 typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple from google.api_core import gapic_v1 # type: ignore from google.api_core import grpc_helpers_async # type: ignore from google import auth # type: ignore from google.auth import credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore -import packaging.version import grpc # type: ignore from grpc.experimental import aio # type: ignore @@ -30,6 +31,7 @@ from google.iam.v1 import policy_pb2 as policy # type: ignore from google.protobuf import empty_pb2 as empty # type: ignore from google.pubsub_v1.types import pubsub + from .base import SubscriberTransport, DEFAULT_CLIENT_INFO from .grpc import SubscriberGrpcTransport @@ -84,15 +86,13 @@ def create_channel( Returns: aio.Channel: A gRPC AsyncIO channel object. """ - - self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) - + scopes = scopes or cls.AUTH_SCOPES return grpc_helpers_async.create_channel( host, credentials=credentials, credentials_file=credentials_file, + scopes=scopes, quota_project_id=quota_project_id, - **self_signed_jwt_kwargs, **kwargs, ) @@ -114,8 +114,7 @@ def __init__( """Instantiate the transport. Args: - host (Optional[str]): - The hostname to connect to. + 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 @@ -173,6 +172,7 @@ def __init__( # 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 @@ -236,9 +236,7 @@ def grpc_channel(self) -> aio.Channel: def create_subscription( self, ) -> Callable[[pubsub.Subscription], Awaitable[pubsub.Subscription]]: - r"""Return a callable for the - create subscription - method over gRPC. + r"""Return a callable for the create subscription method over gRPC. Creates a subscription to a given topic. See the [resource name rules] @@ -276,9 +274,7 @@ def create_subscription( def get_subscription( self, ) -> Callable[[pubsub.GetSubscriptionRequest], Awaitable[pubsub.Subscription]]: - r"""Return a callable for the - get subscription - method over gRPC. + r"""Return a callable for the get subscription method over gRPC. Gets the configuration details of a subscription. @@ -304,9 +300,7 @@ def get_subscription( def update_subscription( self, ) -> Callable[[pubsub.UpdateSubscriptionRequest], Awaitable[pubsub.Subscription]]: - r"""Return a callable for the - update subscription - method over gRPC. + 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 @@ -336,9 +330,7 @@ def list_subscriptions( ) -> Callable[ [pubsub.ListSubscriptionsRequest], Awaitable[pubsub.ListSubscriptionsResponse] ]: - r"""Return a callable for the - list subscriptions - method over gRPC. + r"""Return a callable for the list subscriptions method over gRPC. Lists matching subscriptions. @@ -364,9 +356,7 @@ def list_subscriptions( def delete_subscription( self, ) -> Callable[[pubsub.DeleteSubscriptionRequest], Awaitable[empty.Empty]]: - r"""Return a callable for the - delete subscription - method over gRPC. + 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 @@ -397,9 +387,7 @@ def delete_subscription( def modify_ack_deadline( self, ) -> Callable[[pubsub.ModifyAckDeadlineRequest], Awaitable[empty.Empty]]: - r"""Return a callable for the - modify ack deadline - method over gRPC. + 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 @@ -430,9 +418,7 @@ def modify_ack_deadline( def acknowledge( self, ) -> Callable[[pubsub.AcknowledgeRequest], Awaitable[empty.Empty]]: - r"""Return a callable for the - acknowledge - method over gRPC. + 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 @@ -463,9 +449,7 @@ def acknowledge( @property def pull(self) -> Callable[[pubsub.PullRequest], Awaitable[pubsub.PullResponse]]: - r"""Return a callable for the - pull - method over gRPC. + 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 @@ -495,9 +479,7 @@ def streaming_pull( ) -> Callable[ [pubsub.StreamingPullRequest], Awaitable[pubsub.StreamingPullResponse] ]: - r"""Return a callable for the - streaming pull - method over gRPC. + 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 @@ -530,9 +512,7 @@ def streaming_pull( def modify_push_config( self, ) -> Callable[[pubsub.ModifyPushConfigRequest], Awaitable[empty.Empty]]: - r"""Return a callable for the - modify push config - method over gRPC. + r"""Return a callable for the modify push config method over gRPC. Modifies the ``PushConfig`` for a specified subscription. @@ -564,9 +544,7 @@ def modify_push_config( def get_snapshot( self, ) -> Callable[[pubsub.GetSnapshotRequest], Awaitable[pubsub.Snapshot]]: - r"""Return a callable for the - get snapshot - method over gRPC. + r"""Return a callable for the get snapshot method over gRPC. Gets the configuration details of a snapshot. Snapshots are used in Callable[ [pubsub.ListSnapshotsRequest], Awaitable[pubsub.ListSnapshotsResponse] ]: - r"""Return a callable for the - list snapshots - method over gRPC. + r"""Return a callable for the list snapshots method over gRPC. Lists the existing snapshots. Snapshots are used in `Seek `__ @@ -632,9 +608,7 @@ def list_snapshots( def create_snapshot( self, ) -> Callable[[pubsub.CreateSnapshotRequest], Awaitable[pubsub.Snapshot]]: - r"""Return a callable for the - create snapshot - method over gRPC. + r"""Return a callable for the create snapshot method over gRPC. Creates a snapshot from the requested subscription. Snapshots are used in @@ -678,9 +652,7 @@ def create_snapshot( def update_snapshot( self, ) -> Callable[[pubsub.UpdateSnapshotRequest], Awaitable[pubsub.Snapshot]]: - r"""Return a callable for the - update snapshot - method over gRPC. + r"""Return a callable for the update snapshot method over gRPC. Updates an existing snapshot. Snapshots are used in Callable[[pubsub.SeekRequest], Awaitable[pubsub.SeekResponse]]: - r"""Return a callable for the - seek - method over gRPC. + 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 diff --git a/google/pubsub_v1/types/__init__.py b/google/pubsub_v1/types/__init__.py index ebc8b5399..5203abfe7 100644 --- a/google/pubsub_v1/types/__init__.py +++ b/google/pubsub_v1/types/__init__.py @@ -1,4 +1,5 @@ # -*- coding: utf-8 -*- + # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -13,6 +14,7 @@ # See the License for the specific language governing permissions and # limitations under the License. # + from typing import Union from .pubsub import ( diff --git a/google/pubsub_v1/types/pubsub.py b/google/pubsub_v1/types/pubsub.py index d06aa8e7e..6fb73e8c9 100644 --- a/google/pubsub_v1/types/pubsub.py +++ b/google/pubsub_v1/types/pubsub.py @@ -1,4 +1,5 @@ # -*- coding: utf-8 -*- + # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -13,8 +14,10 @@ # See the License for the specific language governing permissions and # limitations under the License. # + import proto # type: ignore + from google.protobuf import duration_pb2 as duration # type: ignore from google.protobuf import field_mask_pb2 as field_mask # type: ignore from google.protobuf import timestamp_pb2 as timestamp # type: ignore @@ -88,11 +91,12 @@ class MessageStoragePolicy(proto.Message): not a valid configuration. """ - allowed_persistence_regions = proto.RepeatedField(proto.STRING, number=1,) + 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 @@ -104,12 +108,14 @@ class SchemaSettings(proto.Message): The encoding of messages validated against ``schema``. """ - schema = proto.Field(proto.STRING, number=1,) + 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 @@ -143,14 +149,19 @@ class Topic(proto.Message): if it is set in any requests. """ - name = proto.Field(proto.STRING, number=1,) + 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,) + + 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,) + + satisfies_pzs = proto.Field(proto.BOOL, number=7) class PubsubMessage(proto.Message): @@ -196,26 +207,32 @@ class PubsubMessage(proto.Message): same ``ordering_key`` value. """ - data = proto.Field(proto.BYTES, number=1,) + data = proto.Field(proto.BYTES, number=1) + attributes = proto.MapField(proto.STRING, proto.STRING, number=2) - message_id = proto.Field(proto.STRING, number=3,) + + message_id = proto.Field(proto.STRING, number=3) + publish_time = proto.Field(proto.MESSAGE, number=4, message=timestamp.Timestamp,) - ordering_key = proto.Field(proto.STRING, number=5,) + + 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,) + 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. @@ -229,11 +246,13 @@ class UpdateTopicRequest(proto.Message): """ topic = proto.Field(proto.MESSAGE, number=1, message="Topic",) + update_mask = proto.Field(proto.MESSAGE, number=2, message=field_mask.FieldMask,) class PublishRequest(proto.Message): r"""Request for the Publish method. + Attributes: topic (str): Required. The messages in the request will be published on @@ -242,12 +261,14 @@ class PublishRequest(proto.Message): Required. The messages to publish. """ - topic = proto.Field(proto.STRING, number=1,) + 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 @@ -256,11 +277,12 @@ class PublishResponse(proto.Message): within the topic. """ - message_ids = proto.RepeatedField(proto.STRING, number=1,) + 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. @@ -274,13 +296,16 @@ class ListTopicsRequest(proto.Message): 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,) + 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. @@ -295,11 +320,13 @@ def raw_page(self): return self topics = proto.RepeatedField(proto.MESSAGE, number=1, message="Topic",) - next_page_token = proto.Field(proto.STRING, number=2,) + + 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 @@ -315,13 +342,16 @@ class ListTopicSubscriptionsRequest(proto.Message): 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,) + 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 @@ -336,12 +366,14 @@ class ListTopicSubscriptionsResponse(proto.Message): def raw_page(self): return self - subscriptions = proto.RepeatedField(proto.STRING, number=1,) - next_page_token = proto.Field(proto.STRING, number=2,) + 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 @@ -355,13 +387,16 @@ class ListTopicSnapshotsRequest(proto.Message): 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,) + 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 @@ -376,40 +411,44 @@ class ListTopicSnapshotsResponse(proto.Message): def raw_page(self): return self - snapshots = proto.RepeatedField(proto.STRING, number=1,) - next_page_token = proto.Field(proto.STRING, number=2,) + 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,) + 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,) + 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 @@ -524,25 +563,37 @@ class Subscription(proto.Message): endpoint will not be made. """ - name = proto.Field(proto.STRING, number=1,) - topic = proto.Field(proto.STRING, number=2,) + 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,) + + 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.Duration, ) + labels = proto.MapField(proto.STRING, proto.STRING, number=9) - enable_message_ordering = proto.Field(proto.BOOL, number=10,) + + 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,) + + 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,) + + detached = proto.Field(proto.BOOL, number=15) class RetryPolicy(proto.Message): @@ -573,6 +624,7 @@ class RetryPolicy(proto.Message): """ minimum_backoff = proto.Field(proto.MESSAGE, number=1, message=duration.Duration,) + maximum_backoff = proto.Field(proto.MESSAGE, number=2, message=duration.Duration,) @@ -615,8 +667,9 @@ class DeadLetterPolicy(proto.Message): 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,) + dead_letter_topic = proto.Field(proto.STRING, number=1) + + max_delivery_attempts = proto.Field(proto.INT32, number=2) class ExpirationPolicy(proto.Message): @@ -639,6 +692,7 @@ class ExpirationPolicy(proto.Message): class PushConfig(proto.Message): r"""Configuration for a push delivery endpoint. + Attributes: push_endpoint (str): A URL locating the endpoint to which messages should be @@ -705,11 +759,14 @@ class OidcToken(proto.Message): will be used. """ - service_account_email = proto.Field(proto.STRING, number=1,) - audience = proto.Field(proto.STRING, number=2,) + service_account_email = proto.Field(proto.STRING, number=1) + + audience = proto.Field(proto.STRING, number=2) + + push_endpoint = proto.Field(proto.STRING, number=1) - 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, ) @@ -717,6 +774,7 @@ class OidcToken(proto.Message): class ReceivedMessage(proto.Message): r"""A message and its corresponding acknowledgment ID. + Attributes: ack_id (str): This ID can be used to acknowledge the @@ -744,24 +802,28 @@ class ReceivedMessage(proto.Message): will be 0. """ - ack_id = proto.Field(proto.STRING, number=1,) + 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,) + + 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,) + 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. @@ -772,11 +834,13 @@ class UpdateSubscriptionRequest(proto.Message): """ subscription = proto.Field(proto.MESSAGE, number=1, message="Subscription",) + update_mask = proto.Field(proto.MESSAGE, number=2, message=field_mask.FieldMask,) class ListSubscriptionsRequest(proto.Message): r"""Request for the ``ListSubscriptions`` method. + Attributes: project (str): Required. The name of the project in which to list @@ -790,13 +854,16 @@ class ListSubscriptionsRequest(proto.Message): 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,) + 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. @@ -813,22 +880,25 @@ def raw_page(self): subscriptions = proto.RepeatedField( proto.MESSAGE, number=1, message="Subscription", ) - next_page_token = proto.Field(proto.STRING, number=2,) + + 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,) + 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 @@ -843,12 +913,14 @@ class ModifyPushConfigRequest(proto.Message): not called. """ - subscription = proto.Field(proto.STRING, number=1,) + 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 @@ -870,13 +942,16 @@ class PullRequest(proto.Message): 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,) + 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 @@ -893,6 +968,7 @@ class PullResponse(proto.Message): class ModifyAckDeadlineRequest(proto.Message): r"""Request for the ModifyAckDeadline method. + Attributes: subscription (str): Required. The name of the subscription. Format is @@ -912,13 +988,16 @@ class ModifyAckDeadlineRequest(proto.Message): 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,) + 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 @@ -930,8 +1009,9 @@ class AcknowledgeRequest(proto.Message): ``Pull`` response. Must not be empty. """ - subscription = proto.Field(proto.STRING, number=1,) - ack_ids = proto.RepeatedField(proto.STRING, number=2,) + subscription = proto.Field(proto.STRING, number=1) + + ack_ids = proto.RepeatedField(proto.STRING, number=2) class StreamingPullRequest(proto.Message): @@ -1018,14 +1098,21 @@ class StreamingPullRequest(proto.Message): ``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,) + 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): @@ -1045,6 +1132,7 @@ class StreamingPullResponse(proto.Message): class CreateSnapshotRequest(proto.Message): r"""Request for the ``CreateSnapshot`` method. + Attributes: name (str): Required. User-provided name for this snapshot. If the name @@ -1070,13 +1158,16 @@ class CreateSnapshotRequest(proto.Message): Creating and managing labels. """ - name = proto.Field(proto.STRING, number=1,) - subscription = proto.Field(proto.STRING, number=2,) + 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. @@ -1087,6 +1178,7 @@ class UpdateSnapshotRequest(proto.Message): """ snapshot = proto.Field(proto.MESSAGE, number=1, message="Snapshot",) + update_mask = proto.Field(proto.MESSAGE, number=2, message=field_mask.FieldMask,) @@ -1122,25 +1214,30 @@ class Snapshot(proto.Message): (https://cloud.google.com/pubsub/docs/labels). """ - name = proto.Field(proto.STRING, number=1,) - topic = proto.Field(proto.STRING, number=2,) + name = proto.Field(proto.STRING, number=1) + + topic = proto.Field(proto.STRING, number=2) + expire_time = proto.Field(proto.MESSAGE, number=3, message=timestamp.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,) + 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 @@ -1154,13 +1251,16 @@ class ListSnapshotsRequest(proto.Message): 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,) + 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. @@ -1175,22 +1275,25 @@ def raw_page(self): return self snapshots = proto.RepeatedField(proto.MESSAGE, number=1, message="Snapshot",) - next_page_token = proto.Field(proto.STRING, number=2,) + + 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,) + snapshot = proto.Field(proto.STRING, number=1) class SeekRequest(proto.Message): r"""Request for the ``Seek`` method. + Attributes: subscription (str): Required. The subscription to affect. @@ -1214,15 +1317,17 @@ class SeekRequest(proto.Message): ``projects/{project}/snapshots/{snap}``. """ - subscription = proto.Field(proto.STRING, number=1,) + subscription = proto.Field(proto.STRING, number=1) + time = proto.Field( proto.MESSAGE, number=2, oneof="target", message=timestamp.Timestamp, ) - snapshot = proto.Field(proto.STRING, number=3, oneof="target",) + + snapshot = proto.Field(proto.STRING, number=3, oneof="target") class SeekResponse(proto.Message): - r"""Response for the ``Seek`` method (this response is empty). """ + r"""Response for the ``Seek`` method (this response is empty).""" __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/pubsub_v1/types/schema.py b/google/pubsub_v1/types/schema.py index d15837cbd..e4f71d132 100644 --- a/google/pubsub_v1/types/schema.py +++ b/google/pubsub_v1/types/schema.py @@ -1,4 +1,5 @@ # -*- coding: utf-8 -*- + # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -13,6 +14,7 @@ # See the License for the specific language governing permissions and # limitations under the License. # + import proto # type: ignore @@ -53,6 +55,7 @@ class Encoding(proto.Enum): class Schema(proto.Message): r"""A schema resource. + Attributes: name (str): Required. Name of the schema. Format is @@ -71,13 +74,16 @@ class Type(proto.Enum): PROTOCOL_BUFFER = 1 AVRO = 2 - name = proto.Field(proto.STRING, number=1,) + name = proto.Field(proto.STRING, number=1) + type_ = proto.Field(proto.ENUM, number=2, enum=Type,) - definition = proto.Field(proto.STRING, number=3,) + + 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 @@ -97,13 +103,16 @@ class CreateSchemaRequest(proto.Message): for resource name constraints. """ - parent = proto.Field(proto.STRING, number=1,) + parent = proto.Field(proto.STRING, number=1) + schema = proto.Field(proto.MESSAGE, number=2, message="Schema",) - schema_id = proto.Field(proto.STRING, number=3,) + + 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 @@ -114,12 +123,14 @@ class GetSchemaRequest(proto.Message): ``definition``. Set to ``FULL`` to retrieve all fields. """ - name = proto.Field(proto.STRING, number=1,) + 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. @@ -137,14 +148,18 @@ class ListSchemasRequest(proto.Message): next page of data. """ - parent = proto.Field(proto.STRING, number=1,) + 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,) + + 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. @@ -159,22 +174,25 @@ def raw_page(self): return self schemas = proto.RepeatedField(proto.MESSAGE, number=1, message="Schema",) - next_page_token = proto.Field(proto.STRING, number=2,) + + 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,) + 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 @@ -183,16 +201,18 @@ class ValidateSchemaRequest(proto.Message): Required. The schema object to validate. """ - parent = proto.Field(proto.STRING, number=1,) + 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. """ + r"""Response for the ``ValidateSchema`` method.""" class ValidateMessageRequest(proto.Message): r"""Request for the ``ValidateMessage`` method. + Attributes: parent (str): Required. The name of the project in which to validate @@ -209,17 +229,21 @@ class ValidateMessageRequest(proto.Message): The encoding expected for messages """ - parent = proto.Field(proto.STRING, number=1,) - name = proto.Field(proto.STRING, number=2, oneof="schema_spec",) + 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,) + + 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. """ + r"""Response for the ``ValidateMessage`` method.""" __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/scripts/fixup_pubsub_v1_keywords.py b/scripts/fixup_pubsub_v1_keywords.py index 7262e021e..071e3665f 100644 --- a/scripts/fixup_pubsub_v1_keywords.py +++ b/scripts/fixup_pubsub_v1_keywords.py @@ -1,5 +1,6 @@ #! /usr/bin/env python3 # -*- coding: utf-8 -*- + # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,6 +15,7 @@ # See the License for the specific language governing permissions and # limitations under the License. # + import argparse import os import libcst as cst @@ -39,40 +41,42 @@ def partition( 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', ), - 'create_topic': ('name', 'labels', 'message_storage_policy', 'kms_key_name', 'schema_settings', 'satisfies_pzs', ), - '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', ), + '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', ), + 'create_topic': ('name', 'labels', 'message_storage_policy', 'kms_key_name', 'schema_settings', 'satisfies_pzs', ), + '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: @@ -103,7 +107,7 @@ def leave_Call(self, original: cst.Call, updated: cst.Call) -> cst.CSTNode: value=cst.Dict([ cst.DictElement( cst.SimpleString("'{}'".format(name)), -cst.Element(value=arg.value) + 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 diff --git a/synth.metadata b/synth.metadata index 0ff0f0c3f..02509864d 100644 --- a/synth.metadata +++ b/synth.metadata @@ -11,8 +11,8 @@ "git": { "name": "googleapis", "remote": "https://github.com/googleapis/googleapis.git", - "sha": "4e825559e5ab242c4d1aafca19c83c4d1bac743e", - "internalRef": "370989216" + "sha": "5a04154e7c7c0e98e0e4085f6e2c67bd5bff6ff8", + "internalRef": "371362703" } } ], @@ -98,7 +98,6 @@ "google/pubsub/__init__.py", "google/pubsub/py.typed", "google/pubsub_v1/__init__.py", - "google/pubsub_v1/gapic_metadata.json", "google/pubsub_v1/py.typed", "google/pubsub_v1/services/__init__.py", "google/pubsub_v1/services/publisher/__init__.py", @@ -144,9 +143,6 @@ "scripts/readme-gen/templates/install_portaudio.tmpl.rst", "setup.cfg", "testing/.gitignore", - "tests/__init__.py", - "tests/unit/__init__.py", - "tests/unit/gapic/__init__.py", "tests/unit/gapic/pubsub_v1/__init__.py", "tests/unit/gapic/pubsub_v1/test_publisher.py", "tests/unit/gapic/pubsub_v1/test_schema_service.py", diff --git a/tests/__init__.py b/tests/__init__.py deleted file mode 100644 index 4de65971c..000000000 --- a/tests/__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/tests/unit/__init__.py b/tests/unit/__init__.py index 4de65971c..e69de29bb 100644 --- a/tests/unit/__init__.py +++ b/tests/unit/__init__.py @@ -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/tests/unit/gapic/__init__.py b/tests/unit/gapic/__init__.py deleted file mode 100644 index 4de65971c..000000000 --- a/tests/unit/gapic/__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/tests/unit/gapic/pubsub_v1/__init__.py b/tests/unit/gapic/pubsub_v1/__init__.py index 4de65971c..42ffdf2bc 100644 --- a/tests/unit/gapic/pubsub_v1/__init__.py +++ b/tests/unit/gapic/pubsub_v1/__init__.py @@ -1,4 +1,5 @@ # -*- coding: utf-8 -*- + # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); diff --git a/tests/unit/gapic/pubsub_v1/test_publisher.py b/tests/unit/gapic/pubsub_v1/test_publisher.py index 159f07af2..5434ae944 100644 --- a/tests/unit/gapic/pubsub_v1/test_publisher.py +++ b/tests/unit/gapic/pubsub_v1/test_publisher.py @@ -1,4 +1,5 @@ # -*- coding: utf-8 -*- + # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -13,9 +14,9 @@ # See the License for the specific language governing permissions and # limitations under the License. # + import os import mock -import packaging.version import grpc from grpc.experimental import aio @@ -23,7 +24,6 @@ import pytest from proto.marshal.rules.dates import DurationRule, TimestampRule - from google import auth from google.api_core import client_options from google.api_core import exceptions @@ -42,35 +42,10 @@ 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.services.publisher.transports.base import _API_CORE_VERSION -from google.pubsub_v1.services.publisher.transports.base import _GOOGLE_AUTH_VERSION from google.pubsub_v1.types import pubsub from google.pubsub_v1.types import schema -# TODO(busunkim): Once google-api-core >= 1.26.0 is required: -# - Delete all the api-core and auth "less than" test cases -# - Delete these pytest markers (Make the "greater than or equal to" tests the default). -requires_google_auth_lt_1_25_0 = pytest.mark.skipif( - packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), - reason="This test requires google-auth < 1.25.0", -) -requires_google_auth_gte_1_25_0 = pytest.mark.skipif( - packaging.version.parse(_GOOGLE_AUTH_VERSION) < packaging.version.parse("1.25.0"), - reason="This test requires google-auth >= 1.25.0", -) - -requires_api_core_lt_1_26_0 = pytest.mark.skipif( - packaging.version.parse(_API_CORE_VERSION) >= packaging.version.parse("1.26.0"), - reason="This test requires google-api-core < 1.26.0", -) - -requires_api_core_gte_1_26_0 = pytest.mark.skipif( - packaging.version.parse(_API_CORE_VERSION) < packaging.version.parse("1.26.0"), - reason="This test requires google-api-core >= 1.26.0", -) - - def client_cert_source_callback(): return b"cert bytes", b"key bytes" @@ -471,17 +446,23 @@ def test_create_topic(transport: str = "grpc", request_type=pubsub.Topic): 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 @@ -501,6 +482,7 @@ def test_create_topic_empty_call(): client.create_topic() call.assert_called() _, args, _ = call.mock_calls[0] + assert args[0] == pubsub.Topic() @@ -526,17 +508,22 @@ async def test_create_topic_async( 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 @@ -551,12 +538,12 @@ def test_create_topic_field_headers(): # Any value 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. @@ -576,12 +563,12 @@ async def test_create_topic_field_headers_async(): # Any value 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. @@ -601,6 +588,7 @@ def test_create_topic_flattened(): 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",) @@ -609,6 +597,7 @@ def test_create_topic_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] + assert args[0].name == "name_value" @@ -641,6 +630,7 @@ async def test_create_topic_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] + assert args[0].name == "name_value" @@ -671,17 +661,23 @@ def test_update_topic(transport: str = "grpc", request_type=pubsub.UpdateTopicRe 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 @@ -701,6 +697,7 @@ def test_update_topic_empty_call(): client.update_topic() call.assert_called() _, args, _ = call.mock_calls[0] + assert args[0] == pubsub.UpdateTopicRequest() @@ -726,17 +723,22 @@ async def test_update_topic_async( 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 @@ -751,12 +753,12 @@ def test_update_topic_field_headers(): # Any value 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. @@ -776,12 +778,12 @@ async def test_update_topic_field_headers_async(): # Any value 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. @@ -807,15 +809,19 @@ def test_publish(transport: str = "grpc", request_type=pubsub.PublishRequest): 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"] @@ -835,6 +841,7 @@ def test_publish_empty_call(): client.publish() call.assert_called() _, args, _ = call.mock_calls[0] + assert args[0] == pubsub.PublishRequest() @@ -856,15 +863,18 @@ async def test_publish_async( 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"] @@ -879,12 +889,12 @@ def test_publish_field_headers(): # Any value 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. @@ -904,7 +914,6 @@ async def test_publish_field_headers_async(): # Any value 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. @@ -912,6 +921,7 @@ async def test_publish_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( pubsub.PublishResponse() ) + await client.publish(request) # Establish that the underlying gRPC stub method was called. @@ -931,6 +941,7 @@ def test_publish_flattened(): 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( @@ -941,7 +952,9 @@ def test_publish_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] + assert args[0].topic == "topic_value" + assert args[0].messages == [pubsub.PubsubMessage(data=b"data_blob")] @@ -980,7 +993,9 @@ async def test_publish_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] + assert args[0].topic == "topic_value" + assert args[0].messages == [pubsub.PubsubMessage(data=b"data_blob")] @@ -1013,17 +1028,23 @@ def test_get_topic(transport: str = "grpc", request_type=pubsub.GetTopicRequest) 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 @@ -1043,6 +1064,7 @@ def test_get_topic_empty_call(): client.get_topic() call.assert_called() _, args, _ = call.mock_calls[0] + assert args[0] == pubsub.GetTopicRequest() @@ -1068,17 +1090,22 @@ async def test_get_topic_async( 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 @@ -1093,12 +1120,12 @@ def test_get_topic_field_headers(): # Any value 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. @@ -1118,12 +1145,12 @@ async def test_get_topic_field_headers_async(): # Any value 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. @@ -1143,6 +1170,7 @@ def test_get_topic_flattened(): 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",) @@ -1151,6 +1179,7 @@ def test_get_topic_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] + assert args[0].topic == "topic_value" @@ -1183,6 +1212,7 @@ async def test_get_topic_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] + assert args[0].topic == "topic_value" @@ -1213,15 +1243,19 @@ def test_list_topics(transport: str = "grpc", request_type=pubsub.ListTopicsRequ 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" @@ -1241,6 +1275,7 @@ def test_list_topics_empty_call(): client.list_topics() call.assert_called() _, args, _ = call.mock_calls[0] + assert args[0] == pubsub.ListTopicsRequest() @@ -1262,15 +1297,18 @@ async def test_list_topics_async( 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" @@ -1285,12 +1323,12 @@ def test_list_topics_field_headers(): # Any value 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. @@ -1310,7 +1348,6 @@ async def test_list_topics_field_headers_async(): # Any value 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. @@ -1318,6 +1355,7 @@ async def test_list_topics_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( pubsub.ListTopicsResponse() ) + await client.list_topics(request) # Establish that the underlying gRPC stub method was called. @@ -1337,6 +1375,7 @@ def test_list_topics_flattened(): 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",) @@ -1345,6 +1384,7 @@ def test_list_topics_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] + assert args[0].project == "project_value" @@ -1379,6 +1419,7 @@ async def test_list_topics_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] + assert args[0].project == "project_value" @@ -1520,16 +1561,21 @@ def test_list_topic_subscriptions( 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" @@ -1551,6 +1597,7 @@ def test_list_topic_subscriptions_empty_call(): client.list_topic_subscriptions() call.assert_called() _, args, _ = call.mock_calls[0] + assert args[0] == pubsub.ListTopicSubscriptionsRequest() @@ -1577,16 +1624,20 @@ async def test_list_topic_subscriptions_async( 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" @@ -1601,7 +1652,6 @@ def test_list_topic_subscriptions_field_headers(): # Any value 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. @@ -1609,6 +1659,7 @@ def test_list_topic_subscriptions_field_headers(): 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. @@ -1628,7 +1679,6 @@ async def test_list_topic_subscriptions_field_headers_async(): # Any value 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. @@ -1638,6 +1688,7 @@ async def test_list_topic_subscriptions_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( pubsub.ListTopicSubscriptionsResponse() ) + await client.list_topic_subscriptions(request) # Establish that the underlying gRPC stub method was called. @@ -1659,6 +1710,7 @@ def test_list_topic_subscriptions_flattened(): ) 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",) @@ -1667,6 +1719,7 @@ def test_list_topic_subscriptions_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] + assert args[0].topic == "topic_value" @@ -1703,6 +1756,7 @@ async def test_list_topic_subscriptions_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] + assert args[0].topic == "topic_value" @@ -1863,16 +1917,21 @@ def test_list_topic_snapshots( 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" @@ -1894,6 +1953,7 @@ def test_list_topic_snapshots_empty_call(): client.list_topic_snapshots() call.assert_called() _, args, _ = call.mock_calls[0] + assert args[0] == pubsub.ListTopicSnapshotsRequest() @@ -1919,16 +1979,20 @@ async def test_list_topic_snapshots_async( 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" @@ -1943,7 +2007,6 @@ def test_list_topic_snapshots_field_headers(): # Any value 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. @@ -1951,6 +2014,7 @@ def test_list_topic_snapshots_field_headers(): 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. @@ -1970,7 +2034,6 @@ async def test_list_topic_snapshots_field_headers_async(): # Any value 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. @@ -1980,6 +2043,7 @@ async def test_list_topic_snapshots_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( pubsub.ListTopicSnapshotsResponse() ) + await client.list_topic_snapshots(request) # Establish that the underlying gRPC stub method was called. @@ -2001,6 +2065,7 @@ def test_list_topic_snapshots_flattened(): ) 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",) @@ -2009,6 +2074,7 @@ def test_list_topic_snapshots_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] + assert args[0].topic == "topic_value" @@ -2045,6 +2111,7 @@ async def test_list_topic_snapshots_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] + assert args[0].topic == "topic_value" @@ -2191,11 +2258,13 @@ def test_delete_topic(transport: str = "grpc", request_type=pubsub.DeleteTopicRe 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. @@ -2218,6 +2287,7 @@ def test_delete_topic_empty_call(): client.delete_topic() call.assert_called() _, args, _ = call.mock_calls[0] + assert args[0] == pubsub.DeleteTopicRequest() @@ -2237,11 +2307,13 @@ async def test_delete_topic_async( 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. @@ -2259,12 +2331,12 @@ def test_delete_topic_field_headers(): # Any value 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. @@ -2284,12 +2356,12 @@ async def test_delete_topic_field_headers_async(): # Any value 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. @@ -2309,6 +2381,7 @@ def test_delete_topic_flattened(): 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",) @@ -2317,6 +2390,7 @@ def test_delete_topic_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] + assert args[0].topic == "topic_value" @@ -2349,6 +2423,7 @@ async def test_delete_topic_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] + assert args[0].topic == "topic_value" @@ -2381,14 +2456,17 @@ def test_detach_subscription( ) 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) @@ -2410,6 +2488,7 @@ def test_detach_subscription_empty_call(): client.detach_subscription() call.assert_called() _, args, _ = call.mock_calls[0] + assert args[0] == pubsub.DetachSubscriptionRequest() @@ -2433,11 +2512,13 @@ async def test_detach_subscription_async( 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. @@ -2455,7 +2536,6 @@ def test_detach_subscription_field_headers(): # Any value 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. @@ -2463,6 +2543,7 @@ def test_detach_subscription_field_headers(): 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. @@ -2484,7 +2565,6 @@ async def test_detach_subscription_field_headers_async(): # Any value 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. @@ -2494,6 +2574,7 @@ async def test_detach_subscription_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( pubsub.DetachSubscriptionResponse() ) + await client.detach_subscription(request) # Establish that the underlying gRPC stub method was called. @@ -2620,35 +2701,10 @@ def test_publisher_base_transport(): getattr(transport, method)(request=object()) -@requires_google_auth_gte_1_25_0 def test_publisher_base_transport_with_credentials_file(): # Instantiate the base transport with a credentials file with mock.patch.object( - 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 = (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", - ) - - -@requires_google_auth_lt_1_25_0 -def test_publisher_base_transport_with_credentials_file_old_google_auth(): - # Instantiate the base transport with a credentials file - with mock.patch.object( - auth, "load_credentials_from_file", autospec=True + auth, "load_credentials_from_file" ) as load_creds, mock.patch( "google.pubsub_v1.services.publisher.transports.PublisherTransport._prep_wrapped_messages" ) as Transport: @@ -2669,7 +2725,7 @@ def test_publisher_base_transport_with_credentials_file_old_google_auth(): def test_publisher_base_transport_with_adc(): # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(auth, "default", autospec=True) as adc, mock.patch( + with mock.patch.object(auth, "default") as adc, mock.patch( "google.pubsub_v1.services.publisher.transports.PublisherTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None @@ -2678,26 +2734,9 @@ def test_publisher_base_transport_with_adc(): adc.assert_called_once() -@requires_google_auth_gte_1_25_0 def test_publisher_auth_adc(): # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(auth, "default", autospec=True) as adc: - adc.return_value = (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, - ) - - -@requires_google_auth_lt_1_25_0 -def test_publisher_auth_adc_old_google_auth(): - # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(auth, "default", autospec=True) as adc: + with mock.patch.object(auth, "default") as adc: adc.return_value = (credentials.AnonymousCredentials(), None) PublisherClient() adc.assert_called_once_with( @@ -2709,38 +2748,14 @@ def test_publisher_auth_adc_old_google_auth(): ) -@pytest.mark.parametrize( - "transport_class", - [transports.PublisherGrpcTransport, transports.PublisherGrpcAsyncIOTransport,], -) -@requires_google_auth_gte_1_25_0 -def test_publisher_transport_auth_adc(transport_class): +def test_publisher_transport_auth_adc(): # If credentials and host are not provided, the transport class should use # ADC credentials. - with mock.patch.object(auth, "default", autospec=True) as adc: + with mock.patch.object(auth, "default") as adc: adc.return_value = (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", + transports.PublisherGrpcTransport( + host="squid.clam.whelk", quota_project_id="octopus" ) - - -@pytest.mark.parametrize( - "transport_class", - [transports.PublisherGrpcTransport, transports.PublisherGrpcAsyncIOTransport,], -) -@requires_google_auth_lt_1_25_0 -def test_publisher_transport_auth_adc_old_google_auth(transport_class): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(auth, "default", autospec=True) as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) - transport_class(quota_project_id="octopus") adc.assert_called_once_with( scopes=( "https://www.googleapis.com/auth/cloud-platform", @@ -2750,114 +2765,6 @@ def test_publisher_transport_auth_adc_old_google_auth(transport_class): ) -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.PublisherGrpcTransport, grpc_helpers), - (transports.PublisherGrpcAsyncIOTransport, grpc_helpers_async), - ], -) -@requires_api_core_gte_1_26_0 -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(auth, "default", autospec=True) as adc, mock.patch.object( - grpc_helpers, "create_channel", autospec=True - ) as create_channel: - creds = credentials.AnonymousCredentials() - adc.return_value = (creds, None) - transport_class(quota_project_id="octopus", scopes=["1", "2"]) - - create_channel.assert_called_with( - "pubsub.googleapis.com", - 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), - ("grpc.keepalive_time_ms", 30000), - ], - ) - - -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.PublisherGrpcTransport, grpc_helpers), - (transports.PublisherGrpcAsyncIOTransport, grpc_helpers_async), - ], -) -@requires_api_core_lt_1_26_0 -def test_publisher_transport_create_channel_old_api_core(transport_class, grpc_helpers): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(auth, "default", autospec=True) as adc, mock.patch.object( - grpc_helpers, "create_channel", autospec=True - ) as create_channel: - creds = credentials.AnonymousCredentials() - adc.return_value = (creds, None) - transport_class(quota_project_id="octopus") - - create_channel.assert_called_with( - "pubsub.googleapis.com", - credentials=creds, - credentials_file=None, - quota_project_id="octopus", - scopes=( - "https://www.googleapis.com/auth/cloud-platform", - "https://www.googleapis.com/auth/pubsub", - ), - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ("grpc.keepalive_time_ms", 30000), - ], - ) - - -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.PublisherGrpcTransport, grpc_helpers), - (transports.PublisherGrpcAsyncIOTransport, grpc_helpers_async), - ], -) -@requires_api_core_lt_1_26_0 -def test_publisher_transport_create_channel_user_scopes(transport_class, grpc_helpers): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(auth, "default", autospec=True) as adc, mock.patch.object( - grpc_helpers, "create_channel", autospec=True - ) as create_channel: - creds = credentials.AnonymousCredentials() - adc.return_value = (creds, None) - - transport_class(quota_project_id="octopus", scopes=["1", "2"]) - - create_channel.assert_called_with( - "pubsub.googleapis.com", - credentials=creds, - credentials_file=None, - quota_project_id="octopus", - scopes=["1", "2"], - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ("grpc.keepalive_time_ms", 30000), - ], - ) - - @pytest.mark.parametrize( "transport_class", [transports.PublisherGrpcTransport, transports.PublisherGrpcAsyncIOTransport], @@ -3051,6 +2958,7 @@ def test_publisher_transport_channel_mtls_with_adc(transport_class): def test_schema_path(): project = "squid" schema = "clam" + expected = "projects/{project}/schemas/{schema}".format( project=project, schema=schema, ) @@ -3073,6 +2981,7 @@ def test_parse_schema_path(): def test_subscription_path(): project = "oyster" subscription = "nudibranch" + expected = "projects/{project}/subscriptions/{subscription}".format( project=project, subscription=subscription, ) @@ -3095,6 +3004,7 @@ def test_parse_subscription_path(): 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 @@ -3114,6 +3024,7 @@ def test_parse_topic_path(): def test_common_billing_account_path(): billing_account = "squid" + expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -3134,6 +3045,7 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): folder = "whelk" + expected = "folders/{folder}".format(folder=folder,) actual = PublisherClient.common_folder_path(folder) assert expected == actual @@ -3152,6 +3064,7 @@ def test_parse_common_folder_path(): def test_common_organization_path(): organization = "oyster" + expected = "organizations/{organization}".format(organization=organization,) actual = PublisherClient.common_organization_path(organization) assert expected == actual @@ -3170,6 +3083,7 @@ def test_parse_common_organization_path(): def test_common_project_path(): project = "cuttlefish" + expected = "projects/{project}".format(project=project,) actual = PublisherClient.common_project_path(project) assert expected == actual @@ -3189,6 +3103,7 @@ def test_parse_common_project_path(): def test_common_location_path(): project = "winkle" location = "nautilus" + expected = "projects/{project}/locations/{location}".format( project=project, location=location, ) diff --git a/tests/unit/gapic/pubsub_v1/test_schema_service.py b/tests/unit/gapic/pubsub_v1/test_schema_service.py index d3f206ea2..62a3aa730 100644 --- a/tests/unit/gapic/pubsub_v1/test_schema_service.py +++ b/tests/unit/gapic/pubsub_v1/test_schema_service.py @@ -1,4 +1,5 @@ # -*- coding: utf-8 -*- + # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -13,9 +14,9 @@ # See the License for the specific language governing permissions and # limitations under the License. # + import os import mock -import packaging.version import grpc from grpc.experimental import aio @@ -23,7 +24,6 @@ import pytest from proto.marshal.rules.dates import DurationRule, TimestampRule - from google import auth from google.api_core import client_options from google.api_core import exceptions @@ -40,37 +40,10 @@ 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.services.schema_service.transports.base import _API_CORE_VERSION -from google.pubsub_v1.services.schema_service.transports.base import ( - _GOOGLE_AUTH_VERSION, -) from google.pubsub_v1.types import schema from google.pubsub_v1.types import schema as gp_schema -# TODO(busunkim): Once google-api-core >= 1.26.0 is required: -# - Delete all the api-core and auth "less than" test cases -# - Delete these pytest markers (Make the "greater than or equal to" tests the default). -requires_google_auth_lt_1_25_0 = pytest.mark.skipif( - packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), - reason="This test requires google-auth < 1.25.0", -) -requires_google_auth_gte_1_25_0 = pytest.mark.skipif( - packaging.version.parse(_GOOGLE_AUTH_VERSION) < packaging.version.parse("1.25.0"), - reason="This test requires google-auth >= 1.25.0", -) - -requires_api_core_lt_1_26_0 = pytest.mark.skipif( - packaging.version.parse(_API_CORE_VERSION) >= packaging.version.parse("1.26.0"), - reason="This test requires google-api-core < 1.26.0", -) - -requires_api_core_gte_1_26_0 = pytest.mark.skipif( - packaging.version.parse(_API_CORE_VERSION) < packaging.version.parse("1.26.0"), - reason="This test requires google-api-core >= 1.26.0", -) - - def client_cert_source_callback(): return b"cert bytes", b"key bytes" @@ -492,17 +465,23 @@ def test_create_schema( 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" @@ -522,6 +501,7 @@ def test_create_schema_empty_call(): client.create_schema() call.assert_called() _, args, _ = call.mock_calls[0] + assert args[0] == gp_schema.CreateSchemaRequest() @@ -547,17 +527,22 @@ async def test_create_schema_async( 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" @@ -572,12 +557,12 @@ def test_create_schema_field_headers(): # Any value 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. @@ -597,12 +582,12 @@ async def test_create_schema_field_headers_async(): # Any value 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. @@ -622,6 +607,7 @@ def test_create_schema_flattened(): 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( @@ -634,8 +620,11 @@ def test_create_schema_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] + assert args[0].parent == "parent_value" + assert args[0].schema == gp_schema.Schema(name="name_value") + assert args[0].schema_id == "schema_id_value" @@ -675,8 +664,11 @@ async def test_create_schema_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] + assert args[0].parent == "parent_value" + assert args[0].schema == gp_schema.Schema(name="name_value") + assert args[0].schema_id == "schema_id_value" @@ -712,17 +704,23 @@ def test_get_schema(transport: str = "grpc", request_type=schema.GetSchemaReques 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" @@ -742,6 +740,7 @@ def test_get_schema_empty_call(): client.get_schema() call.assert_called() _, args, _ = call.mock_calls[0] + assert args[0] == schema.GetSchemaRequest() @@ -767,17 +766,22 @@ async def test_get_schema_async( 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" @@ -792,12 +796,12 @@ def test_get_schema_field_headers(): # Any value 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. @@ -817,12 +821,12 @@ async def test_get_schema_field_headers_async(): # Any value 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. @@ -842,6 +846,7 @@ def test_get_schema_flattened(): 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",) @@ -850,6 +855,7 @@ def test_get_schema_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] + assert args[0].name == "name_value" @@ -882,6 +888,7 @@ async def test_get_schema_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] + assert args[0].name == "name_value" @@ -912,15 +919,19 @@ def test_list_schemas(transport: str = "grpc", request_type=schema.ListSchemasRe 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" @@ -940,6 +951,7 @@ def test_list_schemas_empty_call(): client.list_schemas() call.assert_called() _, args, _ = call.mock_calls[0] + assert args[0] == schema.ListSchemasRequest() @@ -961,15 +973,18 @@ async def test_list_schemas_async( 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" @@ -984,12 +999,12 @@ def test_list_schemas_field_headers(): # Any value 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. @@ -1009,7 +1024,6 @@ async def test_list_schemas_field_headers_async(): # Any value 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. @@ -1017,6 +1031,7 @@ async def test_list_schemas_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( schema.ListSchemasResponse() ) + await client.list_schemas(request) # Establish that the underlying gRPC stub method was called. @@ -1036,6 +1051,7 @@ def test_list_schemas_flattened(): 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",) @@ -1044,6 +1060,7 @@ def test_list_schemas_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] + assert args[0].parent == "parent_value" @@ -1078,6 +1095,7 @@ async def test_list_schemas_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] + assert args[0].parent == "parent_value" @@ -1222,11 +1240,13 @@ def test_delete_schema( 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. @@ -1249,6 +1269,7 @@ def test_delete_schema_empty_call(): client.delete_schema() call.assert_called() _, args, _ = call.mock_calls[0] + assert args[0] == schema.DeleteSchemaRequest() @@ -1268,11 +1289,13 @@ async def test_delete_schema_async( 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. @@ -1290,12 +1313,12 @@ def test_delete_schema_field_headers(): # Any value 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. @@ -1315,12 +1338,12 @@ async def test_delete_schema_field_headers_async(): # Any value 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. @@ -1340,6 +1363,7 @@ def test_delete_schema_flattened(): 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",) @@ -1348,6 +1372,7 @@ def test_delete_schema_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] + assert args[0].name == "name_value" @@ -1380,6 +1405,7 @@ async def test_delete_schema_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] + assert args[0].name == "name_value" @@ -1410,14 +1436,17 @@ def test_validate_schema( 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) @@ -1437,6 +1466,7 @@ def test_validate_schema_empty_call(): client.validate_schema() call.assert_called() _, args, _ = call.mock_calls[0] + assert args[0] == gp_schema.ValidateSchemaRequest() @@ -1458,11 +1488,13 @@ async def test_validate_schema_async( 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. @@ -1480,12 +1512,12 @@ def test_validate_schema_field_headers(): # Any value 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. @@ -1505,7 +1537,6 @@ async def test_validate_schema_field_headers_async(): # Any value 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. @@ -1513,6 +1544,7 @@ async def test_validate_schema_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( gp_schema.ValidateSchemaResponse() ) + await client.validate_schema(request) # Establish that the underlying gRPC stub method was called. @@ -1532,6 +1564,7 @@ def test_validate_schema_flattened(): 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( @@ -1542,7 +1575,9 @@ def test_validate_schema_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] + assert args[0].parent == "parent_value" + assert args[0].schema == gp_schema.Schema(name="name_value") @@ -1581,7 +1616,9 @@ async def test_validate_schema_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] + assert args[0].parent == "parent_value" + assert args[0].schema == gp_schema.Schema(name="name_value") @@ -1614,14 +1651,17 @@ def test_validate_message( 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) @@ -1641,6 +1681,7 @@ def test_validate_message_empty_call(): client.validate_message() call.assert_called() _, args, _ = call.mock_calls[0] + assert args[0] == schema.ValidateMessageRequest() @@ -1662,11 +1703,13 @@ async def test_validate_message_async( 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. @@ -1684,12 +1727,12 @@ def test_validate_message_field_headers(): # Any value 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. @@ -1709,7 +1752,6 @@ async def test_validate_message_field_headers_async(): # Any value 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. @@ -1717,6 +1759,7 @@ async def test_validate_message_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( schema.ValidateMessageResponse() ) + await client.validate_message(request) # Establish that the underlying gRPC stub method was called. @@ -1841,35 +1884,10 @@ def test_schema_service_base_transport(): getattr(transport, method)(request=object()) -@requires_google_auth_gte_1_25_0 def test_schema_service_base_transport_with_credentials_file(): # Instantiate the base transport with a credentials file with mock.patch.object( - 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 = (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", - ) - - -@requires_google_auth_lt_1_25_0 -def test_schema_service_base_transport_with_credentials_file_old_google_auth(): - # Instantiate the base transport with a credentials file - with mock.patch.object( - auth, "load_credentials_from_file", autospec=True + auth, "load_credentials_from_file" ) as load_creds, mock.patch( "google.pubsub_v1.services.schema_service.transports.SchemaServiceTransport._prep_wrapped_messages" ) as Transport: @@ -1890,7 +1908,7 @@ def test_schema_service_base_transport_with_credentials_file_old_google_auth(): 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(auth, "default", autospec=True) as adc, mock.patch( + with mock.patch.object(auth, "default") as adc, mock.patch( "google.pubsub_v1.services.schema_service.transports.SchemaServiceTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None @@ -1899,26 +1917,9 @@ def test_schema_service_base_transport_with_adc(): adc.assert_called_once() -@requires_google_auth_gte_1_25_0 def test_schema_service_auth_adc(): # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(auth, "default", autospec=True) as adc: - adc.return_value = (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, - ) - - -@requires_google_auth_lt_1_25_0 -def test_schema_service_auth_adc_old_google_auth(): - # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(auth, "default", autospec=True) as adc: + with mock.patch.object(auth, "default") as adc: adc.return_value = (credentials.AnonymousCredentials(), None) SchemaServiceClient() adc.assert_called_once_with( @@ -1930,44 +1931,14 @@ def test_schema_service_auth_adc_old_google_auth(): ) -@pytest.mark.parametrize( - "transport_class", - [ - transports.SchemaServiceGrpcTransport, - transports.SchemaServiceGrpcAsyncIOTransport, - ], -) -@requires_google_auth_gte_1_25_0 -def test_schema_service_transport_auth_adc(transport_class): +def test_schema_service_transport_auth_adc(): # If credentials and host are not provided, the transport class should use # ADC credentials. - with mock.patch.object(auth, "default", autospec=True) as adc: + with mock.patch.object(auth, "default") as adc: adc.return_value = (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", + transports.SchemaServiceGrpcTransport( + host="squid.clam.whelk", quota_project_id="octopus" ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.SchemaServiceGrpcTransport, - transports.SchemaServiceGrpcAsyncIOTransport, - ], -) -@requires_google_auth_lt_1_25_0 -def test_schema_service_transport_auth_adc_old_google_auth(transport_class): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(auth, "default", autospec=True) as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) - transport_class(quota_project_id="octopus") adc.assert_called_once_with( scopes=( "https://www.googleapis.com/auth/cloud-platform", @@ -1977,118 +1948,6 @@ def test_schema_service_transport_auth_adc_old_google_auth(transport_class): ) -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.SchemaServiceGrpcTransport, grpc_helpers), - (transports.SchemaServiceGrpcAsyncIOTransport, grpc_helpers_async), - ], -) -@requires_api_core_gte_1_26_0 -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(auth, "default", autospec=True) as adc, mock.patch.object( - grpc_helpers, "create_channel", autospec=True - ) as create_channel: - creds = credentials.AnonymousCredentials() - adc.return_value = (creds, None) - transport_class(quota_project_id="octopus", scopes=["1", "2"]) - - create_channel.assert_called_with( - "pubsub.googleapis.com", - 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), - ("grpc.keepalive_time_ms", 30000), - ], - ) - - -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.SchemaServiceGrpcTransport, grpc_helpers), - (transports.SchemaServiceGrpcAsyncIOTransport, grpc_helpers_async), - ], -) -@requires_api_core_lt_1_26_0 -def test_schema_service_transport_create_channel_old_api_core( - transport_class, grpc_helpers -): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(auth, "default", autospec=True) as adc, mock.patch.object( - grpc_helpers, "create_channel", autospec=True - ) as create_channel: - creds = credentials.AnonymousCredentials() - adc.return_value = (creds, None) - transport_class(quota_project_id="octopus") - - create_channel.assert_called_with( - "pubsub.googleapis.com", - credentials=creds, - credentials_file=None, - quota_project_id="octopus", - scopes=( - "https://www.googleapis.com/auth/cloud-platform", - "https://www.googleapis.com/auth/pubsub", - ), - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ("grpc.keepalive_time_ms", 30000), - ], - ) - - -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.SchemaServiceGrpcTransport, grpc_helpers), - (transports.SchemaServiceGrpcAsyncIOTransport, grpc_helpers_async), - ], -) -@requires_api_core_lt_1_26_0 -def test_schema_service_transport_create_channel_user_scopes( - transport_class, grpc_helpers -): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(auth, "default", autospec=True) as adc, mock.patch.object( - grpc_helpers, "create_channel", autospec=True - ) as create_channel: - creds = credentials.AnonymousCredentials() - adc.return_value = (creds, None) - - transport_class(quota_project_id="octopus", scopes=["1", "2"]) - - create_channel.assert_called_with( - "pubsub.googleapis.com", - credentials=creds, - credentials_file=None, - quota_project_id="octopus", - scopes=["1", "2"], - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ("grpc.keepalive_time_ms", 30000), - ], - ) - - @pytest.mark.parametrize( "transport_class", [ @@ -2291,6 +2150,7 @@ def test_schema_service_transport_channel_mtls_with_adc(transport_class): def test_schema_path(): project = "squid" schema = "clam" + expected = "projects/{project}/schemas/{schema}".format( project=project, schema=schema, ) @@ -2312,6 +2172,7 @@ def test_parse_schema_path(): def test_common_billing_account_path(): billing_account = "oyster" + expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -2332,6 +2193,7 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): folder = "cuttlefish" + expected = "folders/{folder}".format(folder=folder,) actual = SchemaServiceClient.common_folder_path(folder) assert expected == actual @@ -2350,6 +2212,7 @@ def test_parse_common_folder_path(): def test_common_organization_path(): organization = "winkle" + expected = "organizations/{organization}".format(organization=organization,) actual = SchemaServiceClient.common_organization_path(organization) assert expected == actual @@ -2368,6 +2231,7 @@ def test_parse_common_organization_path(): def test_common_project_path(): project = "scallop" + expected = "projects/{project}".format(project=project,) actual = SchemaServiceClient.common_project_path(project) assert expected == actual @@ -2387,6 +2251,7 @@ def test_parse_common_project_path(): def test_common_location_path(): project = "squid" location = "clam" + expected = "projects/{project}/locations/{location}".format( project=project, location=location, ) diff --git a/tests/unit/gapic/pubsub_v1/test_subscriber.py b/tests/unit/gapic/pubsub_v1/test_subscriber.py index f83661f03..96f03eb15 100644 --- a/tests/unit/gapic/pubsub_v1/test_subscriber.py +++ b/tests/unit/gapic/pubsub_v1/test_subscriber.py @@ -1,4 +1,5 @@ # -*- coding: utf-8 -*- + # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -13,10 +14,10 @@ # See the License for the specific language governing permissions and # limitations under the License. # + import os import mock import warnings -import packaging.version import grpc from grpc.experimental import aio @@ -24,7 +25,6 @@ import pytest from proto.marshal.rules.dates import DurationRule, TimestampRule - from google import auth from google.api_core import client_options from google.api_core import exceptions @@ -44,34 +44,9 @@ 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.services.subscriber.transports.base import _API_CORE_VERSION -from google.pubsub_v1.services.subscriber.transports.base import _GOOGLE_AUTH_VERSION from google.pubsub_v1.types import pubsub -# TODO(busunkim): Once google-api-core >= 1.26.0 is required: -# - Delete all the api-core and auth "less than" test cases -# - Delete these pytest markers (Make the "greater than or equal to" tests the default). -requires_google_auth_lt_1_25_0 = pytest.mark.skipif( - packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), - reason="This test requires google-auth < 1.25.0", -) -requires_google_auth_gte_1_25_0 = pytest.mark.skipif( - packaging.version.parse(_GOOGLE_AUTH_VERSION) < packaging.version.parse("1.25.0"), - reason="This test requires google-auth >= 1.25.0", -) - -requires_api_core_lt_1_26_0 = pytest.mark.skipif( - packaging.version.parse(_API_CORE_VERSION) >= packaging.version.parse("1.26.0"), - reason="This test requires google-api-core < 1.26.0", -) - -requires_api_core_gte_1_26_0 = pytest.mark.skipif( - packaging.version.parse(_API_CORE_VERSION) < packaging.version.parse("1.26.0"), - reason="This test requires google-api-core >= 1.26.0", -) - - def client_cert_source_callback(): return b"cert bytes", b"key bytes" @@ -484,21 +459,31 @@ def test_create_subscription(transport: str = "grpc", request_type=pubsub.Subscr filter="filter_value", detached=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 @@ -520,6 +505,7 @@ def test_create_subscription_empty_call(): client.create_subscription() call.assert_called() _, args, _ = call.mock_calls[0] + assert args[0] == pubsub.Subscription() @@ -551,21 +537,30 @@ async def test_create_subscription_async( detached=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 @@ -580,7 +575,6 @@ def test_create_subscription_field_headers(): # Any value 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. @@ -588,6 +582,7 @@ def test_create_subscription_field_headers(): 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. @@ -607,7 +602,6 @@ async def test_create_subscription_field_headers_async(): # Any value 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. @@ -615,6 +609,7 @@ async def test_create_subscription_field_headers_async(): 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. @@ -636,6 +631,7 @@ def test_create_subscription_flattened(): ) 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( @@ -649,11 +645,15 @@ def test_create_subscription_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] + assert args[0].name == "name_value" + assert args[0].topic == "topic_value" + assert args[0].push_config == pubsub.PushConfig( push_endpoint="push_endpoint_value" ) + assert args[0].ack_deadline_seconds == 2066 @@ -697,11 +697,15 @@ async def test_create_subscription_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] + assert args[0].name == "name_value" + assert args[0].topic == "topic_value" + assert args[0].push_config == pubsub.PushConfig( push_endpoint="push_endpoint_value" ) + assert args[0].ack_deadline_seconds == 2066 @@ -744,21 +748,31 @@ def test_get_subscription( filter="filter_value", detached=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 @@ -778,6 +792,7 @@ def test_get_subscription_empty_call(): client.get_subscription() call.assert_called() _, args, _ = call.mock_calls[0] + assert args[0] == pubsub.GetSubscriptionRequest() @@ -807,21 +822,30 @@ async def test_get_subscription_async( detached=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 @@ -836,12 +860,12 @@ def test_get_subscription_field_headers(): # Any value 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. @@ -863,12 +887,12 @@ async def test_get_subscription_field_headers_async(): # Any value 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. @@ -890,6 +914,7 @@ def test_get_subscription_flattened(): 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",) @@ -898,6 +923,7 @@ def test_get_subscription_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] + assert args[0].subscription == "subscription_value" @@ -930,6 +956,7 @@ async def test_get_subscription_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] + assert args[0].subscription == "subscription_value" @@ -970,21 +997,31 @@ def test_update_subscription( filter="filter_value", detached=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 @@ -1006,6 +1043,7 @@ def test_update_subscription_empty_call(): client.update_subscription() call.assert_called() _, args, _ = call.mock_calls[0] + assert args[0] == pubsub.UpdateSubscriptionRequest() @@ -1037,21 +1075,30 @@ async def test_update_subscription_async( detached=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 @@ -1066,7 +1113,6 @@ def test_update_subscription_field_headers(): # Any value 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. @@ -1074,6 +1120,7 @@ def test_update_subscription_field_headers(): 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. @@ -1096,7 +1143,6 @@ async def test_update_subscription_field_headers_async(): # Any value 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. @@ -1104,6 +1150,7 @@ async def test_update_subscription_field_headers_async(): 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. @@ -1138,15 +1185,19 @@ def test_list_subscriptions( 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" @@ -1168,6 +1219,7 @@ def test_list_subscriptions_empty_call(): client.list_subscriptions() call.assert_called() _, args, _ = call.mock_calls[0] + assert args[0] == pubsub.ListSubscriptionsRequest() @@ -1191,15 +1243,18 @@ async def test_list_subscriptions_async( 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" @@ -1214,7 +1269,6 @@ def test_list_subscriptions_field_headers(): # Any value 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. @@ -1222,6 +1276,7 @@ def test_list_subscriptions_field_headers(): 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. @@ -1241,7 +1296,6 @@ async def test_list_subscriptions_field_headers_async(): # Any value 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. @@ -1251,6 +1305,7 @@ async def test_list_subscriptions_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( pubsub.ListSubscriptionsResponse() ) + await client.list_subscriptions(request) # Establish that the underlying gRPC stub method was called. @@ -1272,6 +1327,7 @@ def test_list_subscriptions_flattened(): ) 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",) @@ -1280,6 +1336,7 @@ def test_list_subscriptions_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] + assert args[0].project == "project_value" @@ -1316,6 +1373,7 @@ async def test_list_subscriptions_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] + assert args[0].project == "project_value" @@ -1494,11 +1552,13 @@ def test_delete_subscription( ) 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. @@ -1523,6 +1583,7 @@ def test_delete_subscription_empty_call(): client.delete_subscription() call.assert_called() _, args, _ = call.mock_calls[0] + assert args[0] == pubsub.DeleteSubscriptionRequest() @@ -1544,11 +1605,13 @@ async def test_delete_subscription_async( ) 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. @@ -1566,7 +1629,6 @@ def test_delete_subscription_field_headers(): # Any value 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. @@ -1574,6 +1636,7 @@ def test_delete_subscription_field_headers(): 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. @@ -1595,7 +1658,6 @@ async def test_delete_subscription_field_headers_async(): # Any value 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. @@ -1603,6 +1665,7 @@ async def test_delete_subscription_field_headers_async(): 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. @@ -1626,6 +1689,7 @@ def test_delete_subscription_flattened(): ) 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",) @@ -1634,6 +1698,7 @@ def test_delete_subscription_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] + assert args[0].subscription == "subscription_value" @@ -1668,6 +1733,7 @@ async def test_delete_subscription_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] + assert args[0].subscription == "subscription_value" @@ -1700,11 +1766,13 @@ def test_modify_ack_deadline( ) 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. @@ -1729,6 +1797,7 @@ def test_modify_ack_deadline_empty_call(): client.modify_ack_deadline() call.assert_called() _, args, _ = call.mock_calls[0] + assert args[0] == pubsub.ModifyAckDeadlineRequest() @@ -1750,11 +1819,13 @@ async def test_modify_ack_deadline_async( ) 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. @@ -1772,7 +1843,6 @@ def test_modify_ack_deadline_field_headers(): # Any value 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. @@ -1780,6 +1850,7 @@ def test_modify_ack_deadline_field_headers(): 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. @@ -1801,7 +1872,6 @@ async def test_modify_ack_deadline_field_headers_async(): # Any value 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. @@ -1809,6 +1879,7 @@ async def test_modify_ack_deadline_field_headers_async(): 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. @@ -1832,6 +1903,7 @@ def test_modify_ack_deadline_flattened(): ) 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( @@ -1844,8 +1916,11 @@ def test_modify_ack_deadline_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] + assert args[0].subscription == "subscription_value" + assert args[0].ack_ids == ["ack_ids_value"] + assert args[0].ack_deadline_seconds == 2066 @@ -1887,8 +1962,11 @@ async def test_modify_ack_deadline_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] + assert args[0].subscription == "subscription_value" + assert args[0].ack_ids == ["ack_ids_value"] + assert args[0].ack_deadline_seconds == 2066 @@ -1920,11 +1998,13 @@ def test_acknowledge(transport: str = "grpc", request_type=pubsub.AcknowledgeReq 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. @@ -1947,6 +2027,7 @@ def test_acknowledge_empty_call(): client.acknowledge() call.assert_called() _, args, _ = call.mock_calls[0] + assert args[0] == pubsub.AcknowledgeRequest() @@ -1966,11 +2047,13 @@ async def test_acknowledge_async( 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. @@ -1988,12 +2071,12 @@ def test_acknowledge_field_headers(): # Any value 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. @@ -2015,12 +2098,12 @@ async def test_acknowledge_field_headers_async(): # Any value 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. @@ -2042,6 +2125,7 @@ def test_acknowledge_flattened(): 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( @@ -2052,7 +2136,9 @@ def test_acknowledge_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] + assert args[0].subscription == "subscription_value" + assert args[0].ack_ids == ["ack_ids_value"] @@ -2089,7 +2175,9 @@ async def test_acknowledge_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] + assert args[0].subscription == "subscription_value" + assert args[0].ack_ids == ["ack_ids_value"] @@ -2120,14 +2208,17 @@ def test_pull(transport: str = "grpc", request_type=pubsub.PullRequest): 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) @@ -2147,6 +2238,7 @@ def test_pull_empty_call(): client.pull() call.assert_called() _, args, _ = call.mock_calls[0] + assert args[0] == pubsub.PullRequest() @@ -2166,11 +2258,13 @@ async def test_pull_async( 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. @@ -2188,12 +2282,12 @@ def test_pull_field_headers(): # Any value 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. @@ -2215,12 +2309,12 @@ async def test_pull_field_headers_async(): # Any value 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. @@ -2242,6 +2336,7 @@ def test_pull_flattened(): 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. with warnings.catch_warnings(): @@ -2256,8 +2351,11 @@ def test_pull_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] + assert args[0].subscription == "subscription_value" + assert args[0].return_immediately == True + assert args[0].max_messages == 1277 @@ -2299,8 +2397,11 @@ async def test_pull_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] + assert args[0].subscription == "subscription_value" + assert args[0].return_immediately == True + assert args[0].max_messages == 1277 @@ -2329,17 +2430,20 @@ def test_streaming_pull( # Everything is optional in proto3 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. @@ -2362,6 +2466,7 @@ async def test_streaming_pull_async( # Everything is optional in proto3 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. @@ -2371,11 +2476,13 @@ async def test_streaming_pull_async( 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. @@ -2405,11 +2512,13 @@ def test_modify_push_config( ) 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. @@ -2434,6 +2543,7 @@ def test_modify_push_config_empty_call(): client.modify_push_config() call.assert_called() _, args, _ = call.mock_calls[0] + assert args[0] == pubsub.ModifyPushConfigRequest() @@ -2455,11 +2565,13 @@ async def test_modify_push_config_async( ) 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. @@ -2477,7 +2589,6 @@ def test_modify_push_config_field_headers(): # Any value 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. @@ -2485,6 +2596,7 @@ def test_modify_push_config_field_headers(): 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. @@ -2506,7 +2618,6 @@ async def test_modify_push_config_field_headers_async(): # Any value 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. @@ -2514,6 +2625,7 @@ async def test_modify_push_config_field_headers_async(): 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. @@ -2537,6 +2649,7 @@ def test_modify_push_config_flattened(): ) 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( @@ -2548,7 +2661,9 @@ def test_modify_push_config_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] + assert args[0].subscription == "subscription_value" + assert args[0].push_config == pubsub.PushConfig( push_endpoint="push_endpoint_value" ) @@ -2590,7 +2705,9 @@ async def test_modify_push_config_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] + assert args[0].subscription == "subscription_value" + assert args[0].push_config == pubsub.PushConfig( push_endpoint="push_endpoint_value" ) @@ -2623,16 +2740,21 @@ def test_get_snapshot(transport: str = "grpc", request_type=pubsub.GetSnapshotRe 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" @@ -2652,6 +2774,7 @@ def test_get_snapshot_empty_call(): client.get_snapshot() call.assert_called() _, args, _ = call.mock_calls[0] + assert args[0] == pubsub.GetSnapshotRequest() @@ -2673,16 +2796,20 @@ async def test_get_snapshot_async( 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" @@ -2697,12 +2824,12 @@ def test_get_snapshot_field_headers(): # Any value 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. @@ -2722,12 +2849,12 @@ async def test_get_snapshot_field_headers_async(): # Any value 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. @@ -2747,6 +2874,7 @@ def test_get_snapshot_flattened(): 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",) @@ -2755,6 +2883,7 @@ def test_get_snapshot_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] + assert args[0].snapshot == "snapshot_value" @@ -2787,6 +2916,7 @@ async def test_get_snapshot_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] + assert args[0].snapshot == "snapshot_value" @@ -2819,15 +2949,19 @@ def test_list_snapshots( 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" @@ -2847,6 +2981,7 @@ def test_list_snapshots_empty_call(): client.list_snapshots() call.assert_called() _, args, _ = call.mock_calls[0] + assert args[0] == pubsub.ListSnapshotsRequest() @@ -2868,15 +3003,18 @@ async def test_list_snapshots_async( 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" @@ -2891,12 +3029,12 @@ def test_list_snapshots_field_headers(): # Any value 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. @@ -2916,7 +3054,6 @@ async def test_list_snapshots_field_headers_async(): # Any value 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. @@ -2924,6 +3061,7 @@ async def test_list_snapshots_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( pubsub.ListSnapshotsResponse() ) + await client.list_snapshots(request) # Establish that the underlying gRPC stub method was called. @@ -2943,6 +3081,7 @@ def test_list_snapshots_flattened(): 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",) @@ -2951,6 +3090,7 @@ def test_list_snapshots_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] + assert args[0].project == "project_value" @@ -2985,6 +3125,7 @@ async def test_list_snapshots_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] + assert args[0].project == "project_value" @@ -3137,16 +3278,21 @@ def test_create_snapshot( 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" @@ -3166,6 +3312,7 @@ def test_create_snapshot_empty_call(): client.create_snapshot() call.assert_called() _, args, _ = call.mock_calls[0] + assert args[0] == pubsub.CreateSnapshotRequest() @@ -3187,16 +3334,20 @@ async def test_create_snapshot_async( 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" @@ -3211,12 +3362,12 @@ def test_create_snapshot_field_headers(): # Any value 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. @@ -3236,12 +3387,12 @@ async def test_create_snapshot_field_headers_async(): # Any value 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. @@ -3261,6 +3412,7 @@ def test_create_snapshot_flattened(): 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( @@ -3271,7 +3423,9 @@ def test_create_snapshot_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] + assert args[0].name == "name_value" + assert args[0].subscription == "subscription_value" @@ -3308,7 +3462,9 @@ async def test_create_snapshot_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] + assert args[0].name == "name_value" + assert args[0].subscription == "subscription_value" @@ -3341,16 +3497,21 @@ def test_update_snapshot( 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" @@ -3370,6 +3531,7 @@ def test_update_snapshot_empty_call(): client.update_snapshot() call.assert_called() _, args, _ = call.mock_calls[0] + assert args[0] == pubsub.UpdateSnapshotRequest() @@ -3391,16 +3553,20 @@ async def test_update_snapshot_async( 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" @@ -3415,12 +3581,12 @@ def test_update_snapshot_field_headers(): # Any value 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. @@ -3442,12 +3608,12 @@ async def test_update_snapshot_field_headers_async(): # Any value 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. @@ -3477,11 +3643,13 @@ def test_delete_snapshot( 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. @@ -3504,6 +3672,7 @@ def test_delete_snapshot_empty_call(): client.delete_snapshot() call.assert_called() _, args, _ = call.mock_calls[0] + assert args[0] == pubsub.DeleteSnapshotRequest() @@ -3523,11 +3692,13 @@ async def test_delete_snapshot_async( 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. @@ -3545,12 +3716,12 @@ def test_delete_snapshot_field_headers(): # Any value 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. @@ -3570,12 +3741,12 @@ async def test_delete_snapshot_field_headers_async(): # Any value 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. @@ -3595,6 +3766,7 @@ def test_delete_snapshot_flattened(): 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",) @@ -3603,6 +3775,7 @@ def test_delete_snapshot_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] + assert args[0].snapshot == "snapshot_value" @@ -3635,6 +3808,7 @@ async def test_delete_snapshot_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] + assert args[0].snapshot == "snapshot_value" @@ -3663,14 +3837,17 @@ def test_seek(transport: str = "grpc", request_type=pubsub.SeekRequest): 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) @@ -3690,6 +3867,7 @@ def test_seek_empty_call(): client.seek() call.assert_called() _, args, _ = call.mock_calls[0] + assert args[0] == pubsub.SeekRequest() @@ -3709,11 +3887,13 @@ async def test_seek_async( 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. @@ -3731,12 +3911,12 @@ def test_seek_field_headers(): # Any value 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. @@ -3758,12 +3938,12 @@ async def test_seek_field_headers_async(): # Any value 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. @@ -3897,35 +4077,10 @@ def test_subscriber_base_transport(): getattr(transport, method)(request=object()) -@requires_google_auth_gte_1_25_0 def test_subscriber_base_transport_with_credentials_file(): # Instantiate the base transport with a credentials file with mock.patch.object( - 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 = (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", - ) - - -@requires_google_auth_lt_1_25_0 -def test_subscriber_base_transport_with_credentials_file_old_google_auth(): - # Instantiate the base transport with a credentials file - with mock.patch.object( - auth, "load_credentials_from_file", autospec=True + auth, "load_credentials_from_file" ) as load_creds, mock.patch( "google.pubsub_v1.services.subscriber.transports.SubscriberTransport._prep_wrapped_messages" ) as Transport: @@ -3946,7 +4101,7 @@ def test_subscriber_base_transport_with_credentials_file_old_google_auth(): def test_subscriber_base_transport_with_adc(): # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(auth, "default", autospec=True) as adc, mock.patch( + with mock.patch.object(auth, "default") as adc, mock.patch( "google.pubsub_v1.services.subscriber.transports.SubscriberTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None @@ -3955,26 +4110,9 @@ def test_subscriber_base_transport_with_adc(): adc.assert_called_once() -@requires_google_auth_gte_1_25_0 def test_subscriber_auth_adc(): # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(auth, "default", autospec=True) as adc: - adc.return_value = (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, - ) - - -@requires_google_auth_lt_1_25_0 -def test_subscriber_auth_adc_old_google_auth(): - # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(auth, "default", autospec=True) as adc: + with mock.patch.object(auth, "default") as adc: adc.return_value = (credentials.AnonymousCredentials(), None) SubscriberClient() adc.assert_called_once_with( @@ -3986,38 +4124,14 @@ def test_subscriber_auth_adc_old_google_auth(): ) -@pytest.mark.parametrize( - "transport_class", - [transports.SubscriberGrpcTransport, transports.SubscriberGrpcAsyncIOTransport,], -) -@requires_google_auth_gte_1_25_0 -def test_subscriber_transport_auth_adc(transport_class): +def test_subscriber_transport_auth_adc(): # If credentials and host are not provided, the transport class should use # ADC credentials. - with mock.patch.object(auth, "default", autospec=True) as adc: + with mock.patch.object(auth, "default") as adc: adc.return_value = (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", + transports.SubscriberGrpcTransport( + host="squid.clam.whelk", quota_project_id="octopus" ) - - -@pytest.mark.parametrize( - "transport_class", - [transports.SubscriberGrpcTransport, transports.SubscriberGrpcAsyncIOTransport,], -) -@requires_google_auth_lt_1_25_0 -def test_subscriber_transport_auth_adc_old_google_auth(transport_class): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(auth, "default", autospec=True) as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) - transport_class(quota_project_id="octopus") adc.assert_called_once_with( scopes=( "https://www.googleapis.com/auth/cloud-platform", @@ -4027,116 +4141,6 @@ def test_subscriber_transport_auth_adc_old_google_auth(transport_class): ) -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.SubscriberGrpcTransport, grpc_helpers), - (transports.SubscriberGrpcAsyncIOTransport, grpc_helpers_async), - ], -) -@requires_api_core_gte_1_26_0 -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(auth, "default", autospec=True) as adc, mock.patch.object( - grpc_helpers, "create_channel", autospec=True - ) as create_channel: - creds = credentials.AnonymousCredentials() - adc.return_value = (creds, None) - transport_class(quota_project_id="octopus", scopes=["1", "2"]) - - create_channel.assert_called_with( - "pubsub.googleapis.com", - 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), - ("grpc.keepalive_time_ms", 30000), - ], - ) - - -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.SubscriberGrpcTransport, grpc_helpers), - (transports.SubscriberGrpcAsyncIOTransport, grpc_helpers_async), - ], -) -@requires_api_core_lt_1_26_0 -def test_subscriber_transport_create_channel_old_api_core( - transport_class, grpc_helpers -): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(auth, "default", autospec=True) as adc, mock.patch.object( - grpc_helpers, "create_channel", autospec=True - ) as create_channel: - creds = credentials.AnonymousCredentials() - adc.return_value = (creds, None) - transport_class(quota_project_id="octopus") - - create_channel.assert_called_with( - "pubsub.googleapis.com", - credentials=creds, - credentials_file=None, - quota_project_id="octopus", - scopes=( - "https://www.googleapis.com/auth/cloud-platform", - "https://www.googleapis.com/auth/pubsub", - ), - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ("grpc.keepalive_time_ms", 30000), - ], - ) - - -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.SubscriberGrpcTransport, grpc_helpers), - (transports.SubscriberGrpcAsyncIOTransport, grpc_helpers_async), - ], -) -@requires_api_core_lt_1_26_0 -def test_subscriber_transport_create_channel_user_scopes(transport_class, grpc_helpers): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(auth, "default", autospec=True) as adc, mock.patch.object( - grpc_helpers, "create_channel", autospec=True - ) as create_channel: - creds = credentials.AnonymousCredentials() - adc.return_value = (creds, None) - - transport_class(quota_project_id="octopus", scopes=["1", "2"]) - - create_channel.assert_called_with( - "pubsub.googleapis.com", - credentials=creds, - credentials_file=None, - quota_project_id="octopus", - scopes=["1", "2"], - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ("grpc.keepalive_time_ms", 30000), - ], - ) - - @pytest.mark.parametrize( "transport_class", [transports.SubscriberGrpcTransport, transports.SubscriberGrpcAsyncIOTransport], @@ -4330,6 +4334,7 @@ def test_subscriber_transport_channel_mtls_with_adc(transport_class): def test_snapshot_path(): project = "squid" snapshot = "clam" + expected = "projects/{project}/snapshots/{snapshot}".format( project=project, snapshot=snapshot, ) @@ -4352,6 +4357,7 @@ def test_parse_snapshot_path(): def test_subscription_path(): project = "oyster" subscription = "nudibranch" + expected = "projects/{project}/subscriptions/{subscription}".format( project=project, subscription=subscription, ) @@ -4374,6 +4380,7 @@ def test_parse_subscription_path(): 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 @@ -4393,6 +4400,7 @@ def test_parse_topic_path(): def test_common_billing_account_path(): billing_account = "squid" + expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -4413,6 +4421,7 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): folder = "whelk" + expected = "folders/{folder}".format(folder=folder,) actual = SubscriberClient.common_folder_path(folder) assert expected == actual @@ -4431,6 +4440,7 @@ def test_parse_common_folder_path(): def test_common_organization_path(): organization = "oyster" + expected = "organizations/{organization}".format(organization=organization,) actual = SubscriberClient.common_organization_path(organization) assert expected == actual @@ -4449,6 +4459,7 @@ def test_parse_common_organization_path(): def test_common_project_path(): project = "cuttlefish" + expected = "projects/{project}".format(project=project,) actual = SubscriberClient.common_project_path(project) assert expected == actual @@ -4468,6 +4479,7 @@ def test_parse_common_project_path(): def test_common_location_path(): project = "winkle" location = "nautilus" + expected = "projects/{project}/locations/{location}".format( project=project, location=location, ) From f85c71fd443066111e4914e694b5847d0f4f7264 Mon Sep 17 00:00:00 2001 From: yoshi-automation Date: Sun, 18 Jul 2021 04:52:38 +0000 Subject: [PATCH 06/18] fix: add async client to %name_%version/init.py chore: add autogenerated snippets chore: remove auth, policy, and options from the reserved names list feat: support self-signed JWT flow for service accounts chore: enable GAPIC metadata generation chore: sort subpackages in %namespace/%name/init.py PiperOrigin-RevId: 372197450 Source-Author: Google APIs Source-Date: Wed May 5 13:39:02 2021 -0700 Source-Repo: googleapis/googleapis Source-Sha: 83a7e1c8c2f7421ded45ed323eb1fda99ef5ea46 Source-Link: https://github.com/googleapis/googleapis/commit/83a7e1c8c2f7421ded45ed323eb1fda99ef5ea46 --- .coveragerc | 1 - examples/feature_fragments | 14 + google/pubsub/__init__.py | 48 +- google/pubsub_v1/__init__.py | 16 +- google/pubsub_v1/gapic_metadata.json | 361 +++++++ google/pubsub_v1/services/__init__.py | 1 - .../pubsub_v1/services/publisher/__init__.py | 2 - .../services/publisher/async_client.py | 68 +- google/pubsub_v1/services/publisher/client.py | 68 +- google/pubsub_v1/services/publisher/pagers.py | 2 - .../services/publisher/transports/__init__.py | 2 - .../services/publisher/transports/base.py | 227 +++-- .../services/publisher/transports/grpc.py | 51 +- .../publisher/transports/grpc_asyncio.py | 53 +- .../services/schema_service/__init__.py | 2 - .../services/schema_service/async_client.py | 61 +- .../services/schema_service/client.py | 60 +- .../services/schema_service/pagers.py | 2 - .../schema_service/transports/__init__.py | 2 - .../schema_service/transports/base.py | 159 ++- .../schema_service/transports/grpc.py | 51 +- .../schema_service/transports/grpc_asyncio.py | 53 +- .../pubsub_v1/services/subscriber/__init__.py | 2 - .../services/subscriber/async_client.py | 85 +- .../pubsub_v1/services/subscriber/client.py | 89 +- .../pubsub_v1/services/subscriber/pagers.py | 2 - .../subscriber/transports/__init__.py | 2 - .../services/subscriber/transports/base.py | 284 ++++-- .../services/subscriber/transports/grpc.py | 69 +- .../subscriber/transports/grpc_asyncio.py | 69 +- google/pubsub_v1/types/__init__.py | 2 - google/pubsub_v1/types/pubsub.py | 311 ++---- google/pubsub_v1/types/schema.py | 56 +- scripts/fixup_pubsub_v1_keywords.py | 68 +- synth.metadata | 9 +- tests/__init__.py | 15 + tests/unit/__init__.py | 15 + tests/unit/gapic/__init__.py | 15 + tests/unit/gapic/pubsub_v1/__init__.py | 1 - tests/unit/gapic/pubsub_v1/test_publisher.py | 731 ++++++++------ .../gapic/pubsub_v1/test_schema_service.py | 671 +++++++----- tests/unit/gapic/pubsub_v1/test_subscriber.py | 954 +++++++++--------- 42 files changed, 2658 insertions(+), 2096 deletions(-) create mode 100644 examples/feature_fragments create mode 100644 google/pubsub_v1/gapic_metadata.json create mode 100644 tests/__init__.py create mode 100644 tests/unit/gapic/__init__.py diff --git a/.coveragerc b/.coveragerc index a48e62f2e..96190b454 100644 --- a/.coveragerc +++ b/.coveragerc @@ -2,7 +2,6 @@ branch = True [report] -fail_under = 100 show_missing = True omit = google/cloud/__init__.py diff --git a/examples/feature_fragments b/examples/feature_fragments new file mode 100644 index 000000000..7d1b62477 --- /dev/null +++ b/examples/feature_fragments @@ -0,0 +1,14 @@ + + + + + + + + + + + + + +} diff --git a/google/pubsub/__init__.py b/google/pubsub/__init__.py index b146fadef..dfa5c7e04 100644 --- a/google/pubsub/__init__.py +++ b/google/pubsub/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -15,14 +14,15 @@ # limitations under the License. # -from google.pubsub_v1.services.publisher.async_client import PublisherAsyncClient 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.schema_service.client import SchemaServiceClient -from google.pubsub_v1.services.subscriber.async_client import SubscriberAsyncClient 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 @@ -41,10 +41,10 @@ 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 ListTopicSubscriptionsRequest -from google.pubsub_v1.types.pubsub import ListTopicSubscriptionsResponse 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 @@ -69,78 +69,78 @@ 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 Encoding 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 SchemaView 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", - "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", + "ListTopicSubscriptionsRequest", + "ListTopicSubscriptionsResponse", "MessageStoragePolicy", "ModifyAckDeadlineRequest", "ModifyPushConfigRequest", "PublishRequest", "PublishResponse", - "PublisherAsyncClient", - "PublisherClient", "PubsubMessage", "PullRequest", "PullResponse", "PushConfig", "ReceivedMessage", "RetryPolicy", - "Schema", - "SchemaServiceAsyncClient", - "SchemaServiceClient", "SchemaSettings", - "SchemaView", "SeekRequest", "SeekResponse", "Snapshot", "StreamingPullRequest", "StreamingPullResponse", - "SubscriberAsyncClient", - "SubscriberClient", "Subscription", "Topic", "UpdateSnapshotRequest", "UpdateSubscriptionRequest", "UpdateTopicRequest", + "CreateSchemaRequest", + "DeleteSchemaRequest", + "GetSchemaRequest", + "ListSchemasRequest", + "ListSchemasResponse", + "Schema", "ValidateMessageRequest", "ValidateMessageResponse", "ValidateSchemaRequest", "ValidateSchemaResponse", + "Encoding", + "SchemaView", ) diff --git a/google/pubsub_v1/__init__.py b/google/pubsub_v1/__init__.py index d5a1de488..500c756b8 100644 --- a/google/pubsub_v1/__init__.py +++ b/google/pubsub_v1/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -16,8 +15,12 @@ # 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 @@ -36,10 +39,10 @@ from .types.pubsub import ListSubscriptionsResponse from .types.pubsub import ListTopicSnapshotsRequest from .types.pubsub import ListTopicSnapshotsResponse -from .types.pubsub import ListTopicSubscriptionsRequest -from .types.pubsub import ListTopicSubscriptionsResponse 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 @@ -64,17 +67,16 @@ from .types.pubsub import UpdateTopicRequest from .types.schema import CreateSchemaRequest from .types.schema import DeleteSchemaRequest -from .types.schema import Encoding from .types.schema import GetSchemaRequest from .types.schema import ListSchemasRequest from .types.schema import ListSchemasResponse from .types.schema import Schema -from .types.schema import SchemaView 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__ = ( "AcknowledgeRequest", @@ -110,6 +112,7 @@ "ModifyPushConfigRequest", "PublishRequest", "PublishResponse", + "PublisherClient", "PubsubMessage", "PullRequest", "PullResponse", @@ -135,5 +138,4 @@ "ValidateMessageResponse", "ValidateSchemaRequest", "ValidateSchemaResponse", - "PublisherClient", ) diff --git a/google/pubsub_v1/gapic_metadata.json b/google/pubsub_v1/gapic_metadata.json new file mode 100644 index 000000000..4c5b86bd1 --- /dev/null +++ b/google/pubsub_v1/gapic_metadata.json @@ -0,0 +1,361 @@ + { + "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/google/pubsub_v1/services/__init__.py b/google/pubsub_v1/services/__init__.py index 42ffdf2bc..4de65971c 100644 --- a/google/pubsub_v1/services/__init__.py +++ b/google/pubsub_v1/services/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); diff --git a/google/pubsub_v1/services/publisher/__init__.py b/google/pubsub_v1/services/publisher/__init__.py index 970a1a3b4..98e50425d 100644 --- a/google/pubsub_v1/services/publisher/__init__.py +++ b/google/pubsub_v1/services/publisher/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from .client import PublisherClient from .async_client import PublisherAsyncClient diff --git a/google/pubsub_v1/services/publisher/async_client.py b/google/pubsub_v1/services/publisher/async_client.py index 056ba288d..53fa90fb2 100644 --- a/google/pubsub_v1/services/publisher/async_client.py +++ b/google/pubsub_v1/services/publisher/async_client.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict import functools import re @@ -22,19 +20,18 @@ import pkg_resources import google.api_core.client_options as ClientOptions # type: ignore -from google.api_core import exceptions # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore from google.api_core import gapic_v1 # type: ignore from google.api_core import retry as retries # type: ignore from google.api_core import timeout as timeouts # type: ignore -from google.auth import credentials # type: ignore +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 as iam_policy # type: ignore -from google.iam.v1 import policy_pb2 as policy # 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.publisher import pagers from google.pubsub_v1.types import pubsub from google.pubsub_v1.types import TimeoutType - from .transports.base import PublisherTransport, DEFAULT_CLIENT_INFO from .transports.grpc_asyncio import PublisherGrpcAsyncIOTransport from .client import PublisherClient @@ -56,25 +53,20 @@ class PublisherAsyncClient: 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 @@ -128,7 +120,7 @@ def transport(self) -> PublisherTransport: def __init__( self, *, - credentials: credentials.Credentials = None, + 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, @@ -165,7 +157,6 @@ def __init__( google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport creation failed for any reason. """ - self._client = PublisherClient( credentials=credentials, transport=transport, @@ -202,7 +193,6 @@ async def create_topic( 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 (TimeoutType): @@ -228,7 +218,6 @@ async def create_topic( # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -273,7 +262,6 @@ async def update_topic( Args: request (:class:`google.pubsub_v1.types.UpdateTopicRequest`): The request object. Request for the UpdateTopic method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (TimeoutType): @@ -286,7 +274,6 @@ async def update_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, @@ -347,7 +334,6 @@ async def 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 (TimeoutType): @@ -373,10 +359,8 @@ async def publish( # 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) @@ -436,7 +420,6 @@ async def get_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 (TimeoutType): @@ -462,7 +445,6 @@ async def get_topic( # If we have keyword arguments corresponding to fields on the # request, apply these. - if topic is not None: request.topic = topic @@ -518,7 +500,6 @@ async def list_topics( 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 (TimeoutType): @@ -548,7 +529,6 @@ async def list_topics( # If we have keyword arguments corresponding to fields on the # request, apply these. - if project is not None: request.project = project @@ -613,7 +593,6 @@ async def list_topic_subscriptions( 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 (TimeoutType): @@ -643,7 +622,6 @@ async def list_topic_subscriptions( # If we have keyword arguments corresponding to fields on the # request, apply these. - if topic is not None: request.topic = topic @@ -712,7 +690,6 @@ async def list_topic_snapshots( 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 (TimeoutType): @@ -742,7 +719,6 @@ async def list_topic_snapshots( # If we have keyword arguments corresponding to fields on the # request, apply these. - if topic is not None: request.topic = topic @@ -810,7 +786,6 @@ async def delete_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 (TimeoutType): @@ -832,7 +807,6 @@ async def delete_topic( # If we have keyword arguments corresponding to fields on the # request, apply these. - if topic is not None: request.topic = topic @@ -880,7 +854,6 @@ async def detach_subscription( request (:class:`google.pubsub_v1.types.DetachSubscriptionRequest`): The request object. Request for the DetachSubscription method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (TimeoutType): @@ -895,7 +868,6 @@ async def detach_subscription( """ # Create or coerce a protobuf request object. - request = pubsub.DetachSubscriptionRequest(request) # Wrap the RPC method; this adds retry and timeout information, @@ -929,16 +901,16 @@ async def detach_subscription( async def set_iam_policy( self, - request: iam_policy.SetIamPolicyRequest = None, + request: iam_policy_pb2.SetIamPolicyRequest = None, *, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: TimeoutType = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), - ) -> policy.Policy: + ) -> policy_pb2.Policy: r"""Sets the IAM access control policy on the specified function. Replaces any existing policy. Args: - request (:class:`~.iam_policy.SetIamPolicyRequest`): + 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, @@ -948,7 +920,7 @@ async def set_iam_policy( metadata (Sequence[Tuple[str, str]]): Strings which should be sent along with the request as metadata. Returns: - ~.policy.Policy: + ~.policy_pb2.Policy: Defines an Identity and Access Management (IAM) policy. It is used to specify access control policies for Cloud Platform resources. @@ -1012,7 +984,7 @@ async def set_iam_policy( # The request isn't a proto-plus wrapped type, # so it must be constructed via keyword expansion. if isinstance(request, dict): - request = iam_policy.SetIamPolicyRequest(**request) + request = iam_policy_pb2.SetIamPolicyRequest(**request) # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. @@ -1036,17 +1008,17 @@ async def set_iam_policy( async def get_iam_policy( self, - request: iam_policy.GetIamPolicyRequest = None, + request: iam_policy_pb2.GetIamPolicyRequest = None, *, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: TimeoutType = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), - ) -> policy.Policy: + ) -> 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.GetIamPolicyRequest`): + 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, @@ -1056,7 +1028,7 @@ async def get_iam_policy( metadata (Sequence[Tuple[str, str]]): Strings which should be sent along with the request as metadata. Returns: - ~.policy.Policy: + ~.policy_pb2.Policy: Defines an Identity and Access Management (IAM) policy. It is used to specify access control policies for Cloud Platform resources. @@ -1120,7 +1092,7 @@ async def get_iam_policy( # The request isn't a proto-plus wrapped type, # so it must be constructed via keyword expansion. if isinstance(request, dict): - request = iam_policy.GetIamPolicyRequest(**request) + request = iam_policy_pb2.GetIamPolicyRequest(**request) # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. @@ -1144,17 +1116,17 @@ async def get_iam_policy( async def test_iam_permissions( self, - request: iam_policy.TestIamPermissionsRequest = None, + request: iam_policy_pb2.TestIamPermissionsRequest = None, *, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: TimeoutType = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), - ) -> iam_policy.TestIamPermissionsResponse: + ) -> 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.TestIamPermissionsRequest`): + 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, @@ -1164,7 +1136,7 @@ async def test_iam_permissions( metadata (Sequence[Tuple[str, str]]): Strings which should be sent along with the request as metadata. Returns: - ~.iam_policy.TestIamPermissionsResponse: + ~iam_policy_pb2.PolicyTestIamPermissionsResponse: Response message for ``TestIamPermissions`` method. """ # Create or coerce a protobuf request object. @@ -1172,7 +1144,7 @@ async def test_iam_permissions( # The request isn't a proto-plus wrapped type, # so it must be constructed via keyword expansion. if isinstance(request, dict): - request = iam_policy.TestIamPermissionsRequest(**request) + request = iam_policy_pb2.TestIamPermissionsRequest(**request) # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. diff --git a/google/pubsub_v1/services/publisher/client.py b/google/pubsub_v1/services/publisher/client.py index 3a3db1ebe..2e63a1d58 100644 --- a/google/pubsub_v1/services/publisher/client.py +++ b/google/pubsub_v1/services/publisher/client.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from distutils import util import functools @@ -24,24 +22,23 @@ import pkg_resources from google.api_core import client_options as client_options_lib # type: ignore -from google.api_core import exceptions # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore from google.api_core import gapic_v1 # type: ignore from google.api_core import retry as retries # type: ignore from google.api_core import timeout as timeouts # type: ignore -from google.auth import credentials # type: ignore +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 -from google.iam.v1 import iam_policy_pb2 as iam_policy # type: ignore -from google.iam.v1 import policy_pb2 as policy # 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.publisher import pagers from google.pubsub_v1.types import pubsub from google.pubsub_v1.types import TimeoutType import grpc - from .transports.base import PublisherTransport, DEFAULT_CLIENT_INFO from .transports.grpc import PublisherGrpcTransport from .transports.grpc_asyncio import PublisherGrpcAsyncIOTransport @@ -277,7 +274,7 @@ def parse_common_location_path(path: str) -> Dict[str, str]: def __init__( self, *, - credentials: Optional[credentials.Credentials] = None, + 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, @@ -427,7 +424,6 @@ def create_topic( 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 (TimeoutType): @@ -455,10 +451,8 @@ def create_topic( # 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 @@ -493,7 +487,6 @@ def update_topic( Args: request (google.pubsub_v1.types.UpdateTopicRequest): The request object. Request for the UpdateTopic method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (TimeoutType): @@ -506,7 +499,6 @@ def update_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 @@ -562,7 +554,6 @@ def 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 (TimeoutType): @@ -590,10 +581,8 @@ def publish( # 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: @@ -637,7 +626,6 @@ def get_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 (TimeoutType): @@ -665,10 +653,8 @@ def get_topic( # 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 @@ -710,7 +696,6 @@ def list_topics( 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 (TimeoutType): @@ -742,10 +727,8 @@ def list_topics( # 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 @@ -796,7 +779,6 @@ def list_topic_subscriptions( 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 (TimeoutType): @@ -828,10 +810,8 @@ def list_topic_subscriptions( # 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 @@ -886,7 +866,6 @@ def list_topic_snapshots( 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 (TimeoutType): @@ -918,10 +897,8 @@ def list_topic_snapshots( # 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 @@ -975,7 +952,6 @@ def delete_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 (TimeoutType): @@ -999,10 +975,8 @@ def delete_topic( # 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 @@ -1040,7 +1014,6 @@ def detach_subscription( request (google.pubsub_v1.types.DetachSubscriptionRequest): The request object. Request for the DetachSubscription method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (TimeoutType): @@ -1055,7 +1028,6 @@ def detach_subscription( """ # 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 @@ -1083,17 +1055,17 @@ def detach_subscription( def set_iam_policy( self, - request: iam_policy.SetIamPolicyRequest = None, + request: iam_policy_pb2.SetIamPolicyRequest = None, *, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: TimeoutType = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), - ) -> policy.Policy: + ) -> policy_pb2.Policy: r"""Sets the IAM access control policy on the specified function. Replaces any existing policy. Args: - request (:class:`~.iam_policy.SetIamPolicyRequest`): + 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, @@ -1103,7 +1075,7 @@ def set_iam_policy( metadata (Sequence[Tuple[str, str]]): Strings which should be sent along with the request as metadata. Returns: - ~.policy.Policy: + ~.policy_pb2.Policy: Defines an Identity and Access Management (IAM) policy. It is used to specify access control policies for Cloud Platform resources. @@ -1170,7 +1142,7 @@ def set_iam_policy( # The request isn't a proto-plus wrapped type, # so it must be constructed via keyword expansion. if isinstance(request, dict): - request = iam_policy.SetIamPolicyRequest(**request) + request = iam_policy_pb2.SetIamPolicyRequest(**request) # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. @@ -1194,18 +1166,18 @@ def set_iam_policy( def get_iam_policy( self, - request: iam_policy.GetIamPolicyRequest = None, + request: iam_policy_pb2.GetIamPolicyRequest = None, *, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: TimeoutType = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), - ) -> policy.Policy: + ) -> 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.GetIamPolicyRequest`): + 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, @@ -1215,7 +1187,7 @@ def get_iam_policy( metadata (Sequence[Tuple[str, str]]): Strings which should be sent along with the request as metadata. Returns: - ~.policy.Policy: + ~.policy_pb2.Policy: Defines an Identity and Access Management (IAM) policy. It is used to specify access control policies for Cloud Platform resources. @@ -1282,7 +1254,7 @@ def get_iam_policy( # The request isn't a proto-plus wrapped type, # so it must be constructed via keyword expansion. if isinstance(request, dict): - request = iam_policy.GetIamPolicyRequest(**request) + request = iam_policy_pb2.GetIamPolicyRequest(**request) # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. @@ -1306,18 +1278,18 @@ def get_iam_policy( def test_iam_permissions( self, - request: iam_policy.TestIamPermissionsRequest = None, + request: iam_policy_pb2.TestIamPermissionsRequest = None, *, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: TimeoutType = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), - ) -> iam_policy.TestIamPermissionsResponse: + ) -> 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.TestIamPermissionsRequest`): + 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, @@ -1327,7 +1299,7 @@ def test_iam_permissions( metadata (Sequence[Tuple[str, str]]): Strings which should be sent along with the request as metadata. Returns: - ~.iam_policy.TestIamPermissionsResponse: + ~.iam_policy_pb2.TestIamPermissionsResponse: Response message for ``TestIamPermissions`` method. """ # Create or coerce a protobuf request object. @@ -1335,7 +1307,7 @@ def test_iam_permissions( # The request isn't a proto-plus wrapped type, # so it must be constructed via keyword expansion. if isinstance(request, dict): - request = iam_policy.TestIamPermissionsRequest(**request) + request = iam_policy_pb2.TestIamPermissionsRequest(**request) # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. diff --git a/google/pubsub_v1/services/publisher/pagers.py b/google/pubsub_v1/services/publisher/pagers.py index e8836d410..592e3d507 100644 --- a/google/pubsub_v1/services/publisher/pagers.py +++ b/google/pubsub_v1/services/publisher/pagers.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from typing import ( Any, AsyncIterable, diff --git a/google/pubsub_v1/services/publisher/transports/__init__.py b/google/pubsub_v1/services/publisher/transports/__init__.py index 9eec7fc5d..34066edc3 100644 --- a/google/pubsub_v1/services/publisher/transports/__init__.py +++ b/google/pubsub_v1/services/publisher/transports/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from typing import Dict, Type diff --git a/google/pubsub_v1/services/publisher/transports/base.py b/google/pubsub_v1/services/publisher/transports/base.py index b1111a841..77edf35a9 100644 --- a/google/pubsub_v1/services/publisher/transports/base.py +++ b/google/pubsub_v1/services/publisher/transports/base.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,23 +13,23 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import abc -import typing +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union +import packaging.version import pkg_resources -from google import auth # type: ignore -from google.api_core import exceptions # type: ignore +import google.auth # type: ignore +import google.api_core # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore from google.api_core import gapic_v1 # type: ignore from google.api_core import retry as retries # type: ignore -from google.auth import credentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore -from google.iam.v1 import iam_policy_pb2 as iam_policy # type: ignore -from google.iam.v1 import policy_pb2 as policy # type: ignore -from google.protobuf import empty_pb2 as empty # 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( client_library_version=pkg_resources.get_distribution( @@ -40,6 +39,17 @@ except pkg_resources.DistributionNotFound: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() +try: + # google.auth.__version__ was added in 1.26.0 + _GOOGLE_AUTH_VERSION = google.auth.__version__ +except AttributeError: + try: # try pkg_resources if it is available + _GOOGLE_AUTH_VERSION = pkg_resources.get_distribution("google-auth").version + except pkg_resources.DistributionNotFound: # pragma: NO COVER + _GOOGLE_AUTH_VERSION = None + +_API_CORE_VERSION = google.api_core.__version__ + class PublisherTransport(abc.ABC): """Abstract transport class for Publisher.""" @@ -49,21 +59,24 @@ class PublisherTransport(abc.ABC): "https://www.googleapis.com/auth/pubsub", ) + DEFAULT_HOST: str = "pubsub.googleapis.com" + def __init__( self, *, - host: str = "pubsub.googleapis.com", - credentials: credentials.Credentials = None, - credentials_file: typing.Optional[str] = None, - scopes: typing.Optional[typing.Sequence[str]] = AUTH_SCOPES, - quota_project_id: typing.Optional[str] = None, + 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, **kwargs, ) -> None: """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + 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 @@ -72,7 +85,7 @@ def __init__( 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. - scope (Optional[Sequence[str]]): A list of scopes. + 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): @@ -86,29 +99,76 @@ def __init__( host += ":443" self._host = host + scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) + # Save the scopes. self._scopes = scopes or self.AUTH_SCOPES # If no credentials are provided, then determine the appropriate # defaults. if credentials and credentials_file: - raise exceptions.DuplicateCredentialArgs( + raise core_exceptions.DuplicateCredentialArgs( "'credentials_file' and 'credentials' are mutually exclusive" ) if credentials_file is not None: - credentials, _ = auth.load_credentials_from_file( - credentials_file, scopes=self._scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, **scopes_kwargs, quota_project_id=quota_project_id ) elif credentials is None: - credentials, _ = auth.default( - scopes=self._scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.default( + **scopes_kwargs, quota_project_id=quota_project_id ) # Save the credentials. self._credentials = credentials + # TODO(busunkim): These two class methods are in the base transport + # to avoid duplicating code across the transport classes. These functions + # should be deleted once the minimum required versions of google-api-core + # and google-auth are increased. + + # TODO: Remove this function once google-auth >= 1.25.0 is required + @classmethod + def _get_scopes_kwargs( + cls, host: str, scopes: Optional[Sequence[str]] + ) -> Dict[str, Optional[Sequence[str]]]: + """Returns scopes kwargs to pass to google-auth methods depending on the google-auth version""" + + scopes_kwargs = {} + + if _GOOGLE_AUTH_VERSION and ( + packaging.version.parse(_GOOGLE_AUTH_VERSION) + >= packaging.version.parse("1.25.0") + ): + scopes_kwargs = {"scopes": scopes, "default_scopes": cls.AUTH_SCOPES} + else: + scopes_kwargs = {"scopes": scopes or cls.AUTH_SCOPES} + + return scopes_kwargs + + # TODO: Remove this function once google-api-core >= 1.26.0 is required + @classmethod + def _get_self_signed_jwt_kwargs( + cls, host: str, scopes: Optional[Sequence[str]] + ) -> Dict[str, Union[Optional[Sequence[str]], str]]: + """Returns kwargs to pass to grpc_helpers.create_channel depending on the google-api-core version""" + + self_signed_jwt_kwargs: Dict[str, Union[Optional[Sequence[str]], str]] = {} + + if _API_CORE_VERSION and ( + packaging.version.parse(_API_CORE_VERSION) + >= packaging.version.parse("1.26.0") + ): + self_signed_jwt_kwargs["default_scopes"] = cls.AUTH_SCOPES + self_signed_jwt_kwargs["scopes"] = scopes + self_signed_jwt_kwargs["default_host"] = cls.DEFAULT_HOST + else: + self_signed_jwt_kwargs["scopes"] = scopes or cls.AUTH_SCOPES + + return self_signed_jwt_kwargs + def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. self._wrapped_methods = { @@ -118,7 +178,9 @@ def _prep_wrapped_messages(self, client_info): initial=0.1, maximum=60.0, multiplier=1.3, - predicate=retries.if_exception_type(exceptions.ServiceUnavailable,), + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), deadline=60.0, ), default_timeout=60.0, @@ -130,7 +192,9 @@ def _prep_wrapped_messages(self, client_info): initial=0.1, maximum=60.0, multiplier=1.3, - predicate=retries.if_exception_type(exceptions.ServiceUnavailable,), + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), deadline=60.0, ), default_timeout=60.0, @@ -143,13 +207,13 @@ def _prep_wrapped_messages(self, client_info): maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.Aborted, - exceptions.Cancelled, - exceptions.DeadlineExceeded, - exceptions.InternalServerError, - exceptions.ResourceExhausted, - exceptions.ServiceUnavailable, - exceptions.Unknown, + core_exceptions.Aborted, + core_exceptions.Cancelled, + core_exceptions.DeadlineExceeded, + core_exceptions.InternalServerError, + core_exceptions.ResourceExhausted, + core_exceptions.ServiceUnavailable, + core_exceptions.Unknown, ), deadline=60.0, ), @@ -163,9 +227,9 @@ def _prep_wrapped_messages(self, client_info): maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.Aborted, - exceptions.ServiceUnavailable, - exceptions.Unknown, + core_exceptions.Aborted, + core_exceptions.ServiceUnavailable, + core_exceptions.Unknown, ), deadline=60.0, ), @@ -179,9 +243,9 @@ def _prep_wrapped_messages(self, client_info): maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.Aborted, - exceptions.ServiceUnavailable, - exceptions.Unknown, + core_exceptions.Aborted, + core_exceptions.ServiceUnavailable, + core_exceptions.Unknown, ), deadline=60.0, ), @@ -195,9 +259,9 @@ def _prep_wrapped_messages(self, client_info): maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.Aborted, - exceptions.ServiceUnavailable, - exceptions.Unknown, + core_exceptions.Aborted, + core_exceptions.ServiceUnavailable, + core_exceptions.Unknown, ), deadline=60.0, ), @@ -211,9 +275,9 @@ def _prep_wrapped_messages(self, client_info): maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.Aborted, - exceptions.ServiceUnavailable, - exceptions.Unknown, + core_exceptions.Aborted, + core_exceptions.ServiceUnavailable, + core_exceptions.Unknown, ), deadline=60.0, ), @@ -226,7 +290,9 @@ def _prep_wrapped_messages(self, client_info): initial=0.1, maximum=60.0, multiplier=1.3, - predicate=retries.if_exception_type(exceptions.ServiceUnavailable,), + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), deadline=60.0, ), default_timeout=60.0, @@ -238,7 +304,9 @@ def _prep_wrapped_messages(self, client_info): initial=0.1, maximum=60.0, multiplier=1.3, - predicate=retries.if_exception_type(exceptions.ServiceUnavailable,), + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), deadline=60.0, ), default_timeout=60.0, @@ -249,57 +317,51 @@ def _prep_wrapped_messages(self, client_info): @property def create_topic( self, - ) -> typing.Callable[ - [pubsub.Topic], typing.Union[pubsub.Topic, typing.Awaitable[pubsub.Topic]] - ]: + ) -> Callable[[pubsub.Topic], Union[pubsub.Topic, Awaitable[pubsub.Topic]]]: raise NotImplementedError() @property def update_topic( self, - ) -> typing.Callable[ - [pubsub.UpdateTopicRequest], - typing.Union[pubsub.Topic, typing.Awaitable[pubsub.Topic]], + ) -> Callable[ + [pubsub.UpdateTopicRequest], Union[pubsub.Topic, Awaitable[pubsub.Topic]] ]: raise NotImplementedError() @property def publish( self, - ) -> typing.Callable[ + ) -> Callable[ [pubsub.PublishRequest], - typing.Union[pubsub.PublishResponse, typing.Awaitable[pubsub.PublishResponse]], + Union[pubsub.PublishResponse, Awaitable[pubsub.PublishResponse]], ]: raise NotImplementedError() @property def get_topic( self, - ) -> typing.Callable[ - [pubsub.GetTopicRequest], - typing.Union[pubsub.Topic, typing.Awaitable[pubsub.Topic]], + ) -> Callable[ + [pubsub.GetTopicRequest], Union[pubsub.Topic, Awaitable[pubsub.Topic]] ]: raise NotImplementedError() @property def list_topics( self, - ) -> typing.Callable[ + ) -> Callable[ [pubsub.ListTopicsRequest], - typing.Union[ - pubsub.ListTopicsResponse, typing.Awaitable[pubsub.ListTopicsResponse] - ], + Union[pubsub.ListTopicsResponse, Awaitable[pubsub.ListTopicsResponse]], ]: raise NotImplementedError() @property def list_topic_subscriptions( self, - ) -> typing.Callable[ + ) -> Callable[ [pubsub.ListTopicSubscriptionsRequest], - typing.Union[ + Union[ pubsub.ListTopicSubscriptionsResponse, - typing.Awaitable[pubsub.ListTopicSubscriptionsResponse], + Awaitable[pubsub.ListTopicSubscriptionsResponse], ], ]: raise NotImplementedError() @@ -307,11 +369,11 @@ def list_topic_subscriptions( @property def list_topic_snapshots( self, - ) -> typing.Callable[ + ) -> Callable[ [pubsub.ListTopicSnapshotsRequest], - typing.Union[ + Union[ pubsub.ListTopicSnapshotsResponse, - typing.Awaitable[pubsub.ListTopicSnapshotsResponse], + Awaitable[pubsub.ListTopicSnapshotsResponse], ], ]: raise NotImplementedError() @@ -319,20 +381,19 @@ def list_topic_snapshots( @property def delete_topic( self, - ) -> typing.Callable[ - [pubsub.DeleteTopicRequest], - typing.Union[empty.Empty, typing.Awaitable[empty.Empty]], + ) -> Callable[ + [pubsub.DeleteTopicRequest], Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]] ]: raise NotImplementedError() @property def detach_subscription( self, - ) -> typing.Callable[ + ) -> Callable[ [pubsub.DetachSubscriptionRequest], - typing.Union[ + Union[ pubsub.DetachSubscriptionResponse, - typing.Awaitable[pubsub.DetachSubscriptionResponse], + Awaitable[pubsub.DetachSubscriptionResponse], ], ]: raise NotImplementedError() @@ -340,29 +401,29 @@ def detach_subscription( @property def set_iam_policy( self, - ) -> typing.Callable[ - [iam_policy.SetIamPolicyRequest], - typing.Union[policy.Policy, typing.Awaitable[policy.Policy]], + ) -> Callable[ + [iam_policy_pb2.SetIamPolicyRequest], + Union[policy_pb2.Policy, Awaitable[policy_pb2.Policy]], ]: raise NotImplementedError() @property def get_iam_policy( self, - ) -> typing.Callable[ - [iam_policy.GetIamPolicyRequest], - typing.Union[policy.Policy, typing.Awaitable[policy.Policy]], + ) -> Callable[ + [iam_policy_pb2.GetIamPolicyRequest], + Union[policy_pb2.Policy, Awaitable[policy_pb2.Policy]], ]: raise NotImplementedError() @property def test_iam_permissions( self, - ) -> typing.Callable[ - [iam_policy.TestIamPermissionsRequest], - typing.Union[ - iam_policy.TestIamPermissionsResponse, - typing.Awaitable[iam_policy.TestIamPermissionsResponse], + ) -> Callable[ + [iam_policy_pb2.TestIamPermissionsRequest], + Union[ + iam_policy_pb2.TestIamPermissionsResponse, + Awaitable[iam_policy_pb2.TestIamPermissionsResponse], ], ]: raise NotImplementedError() diff --git a/google/pubsub_v1/services/publisher/transports/grpc.py b/google/pubsub_v1/services/publisher/transports/grpc.py index 0b9ddc8e2..55c1c5e83 100644 --- a/google/pubsub_v1/services/publisher/transports/grpc.py +++ b/google/pubsub_v1/services/publisher/transports/grpc.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,23 +13,21 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple +from typing import Callable, Dict, Optional, Sequence, Tuple, Union from google.api_core import grpc_helpers # type: ignore from google.api_core import gapic_v1 # type: ignore -from google import auth # type: ignore -from google.auth import credentials # type: ignore +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 as iam_policy # type: ignore -from google.iam.v1 import policy_pb2 as policy # type: ignore -from google.protobuf import empty_pb2 as empty # 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 @@ -54,7 +51,7 @@ def __init__( self, *, host: str = "pubsub.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Sequence[str] = None, channel: grpc.Channel = None, @@ -68,7 +65,8 @@ def __init__( """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + 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 @@ -179,7 +177,7 @@ def __init__( def create_channel( cls, host: str = "pubsub.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Optional[Sequence[str]] = None, quota_project_id: Optional[str] = None, @@ -210,13 +208,15 @@ def create_channel( google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` and ``credentials_file`` are passed. """ - scopes = scopes or cls.AUTH_SCOPES + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + return grpc_helpers.create_channel( host, credentials=credentials, credentials_file=credentials_file, - scopes=scopes, quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, **kwargs, ) @@ -415,7 +415,7 @@ def list_topic_snapshots( return self._stubs["list_topic_snapshots"] @property - def delete_topic(self) -> Callable[[pubsub.DeleteTopicRequest], empty.Empty]: + 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 @@ -439,7 +439,7 @@ def delete_topic(self) -> Callable[[pubsub.DeleteTopicRequest], empty.Empty]: self._stubs["delete_topic"] = self.grpc_channel.unary_unary( "/google.pubsub.v1.Publisher/DeleteTopic", request_serializer=pubsub.DeleteTopicRequest.serialize, - response_deserializer=empty.Empty.FromString, + response_deserializer=empty_pb2.Empty.FromString, ) return self._stubs["delete_topic"] @@ -478,7 +478,7 @@ def detach_subscription( @property def set_iam_policy( self, - ) -> Callable[[iam_policy.SetIamPolicyRequest], policy.Policy]: + ) -> 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. @@ -495,15 +495,15 @@ def set_iam_policy( 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.SetIamPolicyRequest.SerializeToString, - response_deserializer=policy.Policy.FromString, + 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.GetIamPolicyRequest], policy.Policy]: + ) -> 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 @@ -521,8 +521,8 @@ def get_iam_policy( 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.GetIamPolicyRequest.SerializeToString, - response_deserializer=policy.Policy.FromString, + request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, ) return self._stubs["get_iam_policy"] @@ -530,7 +530,8 @@ def get_iam_policy( def test_iam_permissions( self, ) -> Callable[ - [iam_policy.TestIamPermissionsRequest], iam_policy.TestIamPermissionsResponse + [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 @@ -549,8 +550,8 @@ def test_iam_permissions( 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.TestIamPermissionsRequest.SerializeToString, - response_deserializer=iam_policy.TestIamPermissionsResponse.FromString, + request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString, + response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString, ) return self._stubs["test_iam_permissions"] diff --git a/google/pubsub_v1/services/publisher/transports/grpc_asyncio.py b/google/pubsub_v1/services/publisher/transports/grpc_asyncio.py index 6a3a096f0..bc633fc21 100644 --- a/google/pubsub_v1/services/publisher/transports/grpc_asyncio.py +++ b/google/pubsub_v1/services/publisher/transports/grpc_asyncio.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,24 +13,22 @@ # 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 +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union from google.api_core import gapic_v1 # type: ignore from google.api_core import grpc_helpers_async # type: ignore -from google import auth # type: ignore -from google.auth import credentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore +import packaging.version import grpc # type: ignore from grpc.experimental import aio # type: ignore -from google.iam.v1 import iam_policy_pb2 as iam_policy # type: ignore -from google.iam.v1 import policy_pb2 as policy # type: ignore -from google.protobuf import empty_pb2 as empty # 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 @@ -57,7 +54,7 @@ class PublisherGrpcAsyncIOTransport(PublisherTransport): def create_channel( cls, host: str = "pubsub.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: Optional[str] = None, scopes: Optional[Sequence[str]] = None, quota_project_id: Optional[str] = None, @@ -84,13 +81,15 @@ def create_channel( Returns: aio.Channel: A gRPC AsyncIO channel object. """ - scopes = scopes or cls.AUTH_SCOPES + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + return grpc_helpers_async.create_channel( host, credentials=credentials, credentials_file=credentials_file, - scopes=scopes, quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, **kwargs, ) @@ -98,7 +97,7 @@ def __init__( self, *, host: str = "pubsub.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: Optional[str] = None, scopes: Optional[Sequence[str]] = None, channel: aio.Channel = None, @@ -112,7 +111,8 @@ def __init__( """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + 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 @@ -170,7 +170,6 @@ def __init__( # 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 @@ -426,7 +425,7 @@ def list_topic_snapshots( @property def delete_topic( self, - ) -> Callable[[pubsub.DeleteTopicRequest], Awaitable[empty.Empty]]: + ) -> 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 @@ -450,7 +449,7 @@ def delete_topic( self._stubs["delete_topic"] = self.grpc_channel.unary_unary( "/google.pubsub.v1.Publisher/DeleteTopic", request_serializer=pubsub.DeleteTopicRequest.serialize, - response_deserializer=empty.Empty.FromString, + response_deserializer=empty_pb2.Empty.FromString, ) return self._stubs["delete_topic"] @@ -489,7 +488,7 @@ def detach_subscription( @property def set_iam_policy( self, - ) -> Callable[[iam_policy.SetIamPolicyRequest], Awaitable[policy.Policy]]: + ) -> 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. @@ -506,15 +505,15 @@ def set_iam_policy( 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.SetIamPolicyRequest.SerializeToString, - response_deserializer=policy.Policy.FromString, + 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.GetIamPolicyRequest], Awaitable[policy.Policy]]: + ) -> 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 @@ -532,8 +531,8 @@ def get_iam_policy( 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.GetIamPolicyRequest.SerializeToString, - response_deserializer=policy.Policy.FromString, + request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, ) return self._stubs["get_iam_policy"] @@ -541,8 +540,8 @@ def get_iam_policy( def test_iam_permissions( self, ) -> Callable[ - [iam_policy.TestIamPermissionsRequest], - Awaitable[iam_policy.TestIamPermissionsResponse], + [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 @@ -561,8 +560,8 @@ def test_iam_permissions( 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.TestIamPermissionsRequest.SerializeToString, - response_deserializer=iam_policy.TestIamPermissionsResponse.FromString, + request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString, + response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString, ) return self._stubs["test_iam_permissions"] diff --git a/google/pubsub_v1/services/schema_service/__init__.py b/google/pubsub_v1/services/schema_service/__init__.py index d93cff56f..523d5b5f5 100644 --- a/google/pubsub_v1/services/schema_service/__init__.py +++ b/google/pubsub_v1/services/schema_service/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from .client import SchemaServiceClient from .async_client import SchemaServiceAsyncClient diff --git a/google/pubsub_v1/services/schema_service/async_client.py b/google/pubsub_v1/services/schema_service/async_client.py index 9aeb62990..c2d6e9c7b 100644 --- a/google/pubsub_v1/services/schema_service/async_client.py +++ b/google/pubsub_v1/services/schema_service/async_client.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict import functools import re @@ -22,18 +20,17 @@ import pkg_resources import google.api_core.client_options as ClientOptions # type: ignore -from google.api_core import exceptions # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore from google.api_core import gapic_v1 # type: ignore from google.api_core import retry as retries # type: ignore -from google.auth import credentials # type: ignore +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 as iam_policy # type: ignore -from google.iam.v1 import policy_pb2 as policy # 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 @@ -49,31 +46,26 @@ class SchemaServiceAsyncClient: 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 @@ -127,7 +119,7 @@ def transport(self) -> SchemaServiceTransport: def __init__( self, *, - credentials: credentials.Credentials = None, + 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, @@ -164,7 +156,6 @@ def __init__( google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport creation failed for any reason. """ - self._client = SchemaServiceClient( credentials=credentials, transport=transport, @@ -216,7 +207,6 @@ async def create_schema( 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. @@ -241,7 +231,6 @@ async def create_schema( # 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: @@ -290,7 +279,6 @@ async def get_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. @@ -315,7 +303,6 @@ async def get_schema( # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -361,7 +348,6 @@ async def list_schemas( 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. @@ -390,7 +376,6 @@ async def list_schemas( # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent @@ -442,7 +427,6 @@ async def delete_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. @@ -463,7 +447,6 @@ async def delete_schema( # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -516,7 +499,6 @@ async def validate_schema( 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. @@ -541,7 +523,6 @@ async def validate_schema( # 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: @@ -581,7 +562,6 @@ async def validate_message( request (:class:`google.pubsub_v1.types.ValidateMessageRequest`): The request object. Request for the `ValidateMessage` method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -593,7 +573,6 @@ async def validate_message( Response for the ValidateMessage method. """ # Create or coerce a protobuf request object. - request = schema.ValidateMessageRequest(request) # Wrap the RPC method; this adds retry and timeout information, @@ -618,16 +597,16 @@ async def validate_message( async def set_iam_policy( self, - request: iam_policy.SetIamPolicyRequest = None, + request: iam_policy_pb2.SetIamPolicyRequest = None, *, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), - ) -> policy.Policy: + ) -> policy_pb2.Policy: r"""Sets the IAM access control policy on the specified function. Replaces any existing policy. Args: - request (:class:`~.iam_policy.SetIamPolicyRequest`): + 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, @@ -636,7 +615,7 @@ async def set_iam_policy( metadata (Sequence[Tuple[str, str]]): Strings which should be sent along with the request as metadata. Returns: - ~.policy.Policy: + ~.policy_pb2.Policy: Defines an Identity and Access Management (IAM) policy. It is used to specify access control policies for Cloud Platform resources. @@ -700,7 +679,7 @@ async def set_iam_policy( # The request isn't a proto-plus wrapped type, # so it must be constructed via keyword expansion. if isinstance(request, dict): - request = iam_policy.SetIamPolicyRequest(**request) + request = iam_policy_pb2.SetIamPolicyRequest(**request) # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. @@ -724,17 +703,17 @@ async def set_iam_policy( async def get_iam_policy( self, - request: iam_policy.GetIamPolicyRequest = None, + request: iam_policy_pb2.GetIamPolicyRequest = None, *, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), - ) -> policy.Policy: + ) -> 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.GetIamPolicyRequest`): + 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, @@ -743,7 +722,7 @@ async def get_iam_policy( metadata (Sequence[Tuple[str, str]]): Strings which should be sent along with the request as metadata. Returns: - ~.policy.Policy: + ~.policy_pb2.Policy: Defines an Identity and Access Management (IAM) policy. It is used to specify access control policies for Cloud Platform resources. @@ -807,7 +786,7 @@ async def get_iam_policy( # The request isn't a proto-plus wrapped type, # so it must be constructed via keyword expansion. if isinstance(request, dict): - request = iam_policy.GetIamPolicyRequest(**request) + request = iam_policy_pb2.GetIamPolicyRequest(**request) # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. @@ -831,17 +810,17 @@ async def get_iam_policy( async def test_iam_permissions( self, - request: iam_policy.TestIamPermissionsRequest = None, + request: iam_policy_pb2.TestIamPermissionsRequest = None, *, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), - ) -> iam_policy.TestIamPermissionsResponse: + ) -> 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.TestIamPermissionsRequest`): + 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, @@ -850,7 +829,7 @@ async def test_iam_permissions( metadata (Sequence[Tuple[str, str]]): Strings which should be sent along with the request as metadata. Returns: - ~.iam_policy.TestIamPermissionsResponse: + ~iam_policy_pb2.PolicyTestIamPermissionsResponse: Response message for ``TestIamPermissions`` method. """ # Create or coerce a protobuf request object. @@ -858,7 +837,7 @@ async def test_iam_permissions( # The request isn't a proto-plus wrapped type, # so it must be constructed via keyword expansion. if isinstance(request, dict): - request = iam_policy.TestIamPermissionsRequest(**request) + request = iam_policy_pb2.TestIamPermissionsRequest(**request) # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. diff --git a/google/pubsub_v1/services/schema_service/client.py b/google/pubsub_v1/services/schema_service/client.py index 5f65a0388..3fe5f64ff 100644 --- a/google/pubsub_v1/services/schema_service/client.py +++ b/google/pubsub_v1/services/schema_service/client.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from distutils import util import os @@ -23,21 +21,20 @@ import pkg_resources from google.api_core import client_options as client_options_lib # type: ignore -from google.api_core import exceptions # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore from google.api_core import gapic_v1 # type: ignore from google.api_core import retry as retries # type: ignore -from google.auth import credentials # type: ignore +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 -from google.iam.v1 import iam_policy_pb2 as iam_policy # type: ignore -from google.iam.v1 import policy_pb2 as policy # 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 @@ -231,7 +228,7 @@ def parse_common_location_path(path: str) -> Dict[str, str]: def __init__( self, *, - credentials: Optional[credentials.Credentials] = None, + 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, @@ -385,7 +382,6 @@ def create_schema( 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. @@ -412,10 +408,8 @@ def create_schema( # 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: @@ -460,7 +454,6 @@ def get_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. @@ -487,10 +480,8 @@ def get_schema( # 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 @@ -532,7 +523,6 @@ def list_schemas( 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. @@ -563,10 +553,8 @@ def list_schemas( # 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 @@ -614,7 +602,6 @@ def delete_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. @@ -637,10 +624,8 @@ def delete_schema( # 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 @@ -689,7 +674,6 @@ def validate_schema( 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. @@ -716,10 +700,8 @@ def validate_schema( # 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: @@ -755,7 +737,6 @@ def validate_message( request (google.pubsub_v1.types.ValidateMessageRequest): The request object. Request for the `ValidateMessage` method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -767,7 +748,6 @@ def validate_message( Response for the ValidateMessage method. """ # 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 @@ -793,16 +773,16 @@ def validate_message( def set_iam_policy( self, - request: iam_policy.SetIamPolicyRequest = None, + request: iam_policy_pb2.SetIamPolicyRequest = None, *, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), - ) -> policy.Policy: + ) -> policy_pb2.Policy: r"""Sets the IAM access control policy on the specified function. Replaces any existing policy. Args: - request (:class:`~.iam_policy.SetIamPolicyRequest`): + 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, @@ -811,7 +791,7 @@ def set_iam_policy( metadata (Sequence[Tuple[str, str]]): Strings which should be sent along with the request as metadata. Returns: - ~.policy.Policy: + ~.policy_pb2.Policy: Defines an Identity and Access Management (IAM) policy. It is used to specify access control policies for Cloud Platform resources. @@ -875,7 +855,7 @@ def set_iam_policy( # The request isn't a proto-plus wrapped type, # so it must be constructed via keyword expansion. if isinstance(request, dict): - request = iam_policy.SetIamPolicyRequest(**request) + request = iam_policy_pb2.SetIamPolicyRequest(**request) # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. @@ -899,17 +879,17 @@ def set_iam_policy( def get_iam_policy( self, - request: iam_policy.GetIamPolicyRequest = None, + request: iam_policy_pb2.GetIamPolicyRequest = None, *, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), - ) -> policy.Policy: + ) -> 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.GetIamPolicyRequest`): + 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, @@ -918,7 +898,7 @@ def get_iam_policy( metadata (Sequence[Tuple[str, str]]): Strings which should be sent along with the request as metadata. Returns: - ~.policy.Policy: + ~.policy_pb2.Policy: Defines an Identity and Access Management (IAM) policy. It is used to specify access control policies for Cloud Platform resources. @@ -982,7 +962,7 @@ def get_iam_policy( # The request isn't a proto-plus wrapped type, # so it must be constructed via keyword expansion. if isinstance(request, dict): - request = iam_policy.GetIamPolicyRequest(**request) + request = iam_policy_pb2.GetIamPolicyRequest(**request) # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. @@ -1006,17 +986,17 @@ def get_iam_policy( def test_iam_permissions( self, - request: iam_policy.TestIamPermissionsRequest = None, + request: iam_policy_pb2.TestIamPermissionsRequest = None, *, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), - ) -> iam_policy.TestIamPermissionsResponse: + ) -> 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.TestIamPermissionsRequest`): + 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, @@ -1025,7 +1005,7 @@ def test_iam_permissions( metadata (Sequence[Tuple[str, str]]): Strings which should be sent along with the request as metadata. Returns: - ~.iam_policy.TestIamPermissionsResponse: + ~.iam_policy_pb2.TestIamPermissionsResponse: Response message for ``TestIamPermissions`` method. """ # Create or coerce a protobuf request object. @@ -1033,7 +1013,7 @@ def test_iam_permissions( # The request isn't a proto-plus wrapped type, # so it must be constructed via keyword expansion. if isinstance(request, dict): - request = iam_policy.TestIamPermissionsRequest(**request) + request = iam_policy_pb2.TestIamPermissionsRequest(**request) # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. diff --git a/google/pubsub_v1/services/schema_service/pagers.py b/google/pubsub_v1/services/schema_service/pagers.py index 2712f37c6..a6bf1ccc0 100644 --- a/google/pubsub_v1/services/schema_service/pagers.py +++ b/google/pubsub_v1/services/schema_service/pagers.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from typing import ( Any, AsyncIterable, diff --git a/google/pubsub_v1/services/schema_service/transports/__init__.py b/google/pubsub_v1/services/schema_service/transports/__init__.py index 015410d3d..81ebf8d1c 100644 --- a/google/pubsub_v1/services/schema_service/transports/__init__.py +++ b/google/pubsub_v1/services/schema_service/transports/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from typing import Dict, Type diff --git a/google/pubsub_v1/services/schema_service/transports/base.py b/google/pubsub_v1/services/schema_service/transports/base.py index fec2169ae..1b00274b6 100644 --- a/google/pubsub_v1/services/schema_service/transports/base.py +++ b/google/pubsub_v1/services/schema_service/transports/base.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,24 +13,24 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import abc -import typing +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union +import packaging.version import pkg_resources -from google import auth # type: ignore -from google.api_core import exceptions # type: ignore +import google.auth # type: ignore +import google.api_core # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore from google.api_core import gapic_v1 # type: ignore from google.api_core import retry as retries # type: ignore -from google.auth import credentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore -from google.iam.v1 import iam_policy_pb2 as iam_policy # type: ignore -from google.iam.v1 import policy_pb2 as policy # type: ignore -from google.protobuf import empty_pb2 as empty # 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( client_library_version=pkg_resources.get_distribution( @@ -41,6 +40,17 @@ except pkg_resources.DistributionNotFound: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() +try: + # google.auth.__version__ was added in 1.26.0 + _GOOGLE_AUTH_VERSION = google.auth.__version__ +except AttributeError: + try: # try pkg_resources if it is available + _GOOGLE_AUTH_VERSION = pkg_resources.get_distribution("google-auth").version + except pkg_resources.DistributionNotFound: # pragma: NO COVER + _GOOGLE_AUTH_VERSION = None + +_API_CORE_VERSION = google.api_core.__version__ + class SchemaServiceTransport(abc.ABC): """Abstract transport class for SchemaService.""" @@ -50,21 +60,24 @@ class SchemaServiceTransport(abc.ABC): "https://www.googleapis.com/auth/pubsub", ) + DEFAULT_HOST: str = "pubsub.googleapis.com" + def __init__( self, *, - host: str = "pubsub.googleapis.com", - credentials: credentials.Credentials = None, - credentials_file: typing.Optional[str] = None, - scopes: typing.Optional[typing.Sequence[str]] = AUTH_SCOPES, - quota_project_id: typing.Optional[str] = None, + 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, **kwargs, ) -> None: """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + 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 @@ -73,7 +86,7 @@ def __init__( 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. - scope (Optional[Sequence[str]]): A list of scopes. + 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): @@ -87,29 +100,76 @@ def __init__( host += ":443" self._host = host + scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) + # Save the scopes. self._scopes = scopes or self.AUTH_SCOPES # If no credentials are provided, then determine the appropriate # defaults. if credentials and credentials_file: - raise exceptions.DuplicateCredentialArgs( + raise core_exceptions.DuplicateCredentialArgs( "'credentials_file' and 'credentials' are mutually exclusive" ) if credentials_file is not None: - credentials, _ = auth.load_credentials_from_file( - credentials_file, scopes=self._scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, **scopes_kwargs, quota_project_id=quota_project_id ) elif credentials is None: - credentials, _ = auth.default( - scopes=self._scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.default( + **scopes_kwargs, quota_project_id=quota_project_id ) # Save the credentials. self._credentials = credentials + # TODO(busunkim): These two class methods are in the base transport + # to avoid duplicating code across the transport classes. These functions + # should be deleted once the minimum required versions of google-api-core + # and google-auth are increased. + + # TODO: Remove this function once google-auth >= 1.25.0 is required + @classmethod + def _get_scopes_kwargs( + cls, host: str, scopes: Optional[Sequence[str]] + ) -> Dict[str, Optional[Sequence[str]]]: + """Returns scopes kwargs to pass to google-auth methods depending on the google-auth version""" + + scopes_kwargs = {} + + if _GOOGLE_AUTH_VERSION and ( + packaging.version.parse(_GOOGLE_AUTH_VERSION) + >= packaging.version.parse("1.25.0") + ): + scopes_kwargs = {"scopes": scopes, "default_scopes": cls.AUTH_SCOPES} + else: + scopes_kwargs = {"scopes": scopes or cls.AUTH_SCOPES} + + return scopes_kwargs + + # TODO: Remove this function once google-api-core >= 1.26.0 is required + @classmethod + def _get_self_signed_jwt_kwargs( + cls, host: str, scopes: Optional[Sequence[str]] + ) -> Dict[str, Union[Optional[Sequence[str]], str]]: + """Returns kwargs to pass to grpc_helpers.create_channel depending on the google-api-core version""" + + self_signed_jwt_kwargs: Dict[str, Union[Optional[Sequence[str]], str]] = {} + + if _API_CORE_VERSION and ( + packaging.version.parse(_API_CORE_VERSION) + >= packaging.version.parse("1.26.0") + ): + self_signed_jwt_kwargs["default_scopes"] = cls.AUTH_SCOPES + self_signed_jwt_kwargs["scopes"] = scopes + self_signed_jwt_kwargs["default_host"] = cls.DEFAULT_HOST + else: + self_signed_jwt_kwargs["scopes"] = scopes or cls.AUTH_SCOPES + + return self_signed_jwt_kwargs + def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. self._wrapped_methods = { @@ -136,49 +196,45 @@ def _prep_wrapped_messages(self, client_info): @property def create_schema( self, - ) -> typing.Callable[ + ) -> Callable[ [gp_schema.CreateSchemaRequest], - typing.Union[gp_schema.Schema, typing.Awaitable[gp_schema.Schema]], + Union[gp_schema.Schema, Awaitable[gp_schema.Schema]], ]: raise NotImplementedError() @property def get_schema( self, - ) -> typing.Callable[ - [schema.GetSchemaRequest], - typing.Union[schema.Schema, typing.Awaitable[schema.Schema]], + ) -> Callable[ + [schema.GetSchemaRequest], Union[schema.Schema, Awaitable[schema.Schema]] ]: raise NotImplementedError() @property def list_schemas( self, - ) -> typing.Callable[ + ) -> Callable[ [schema.ListSchemasRequest], - typing.Union[ - schema.ListSchemasResponse, typing.Awaitable[schema.ListSchemasResponse] - ], + Union[schema.ListSchemasResponse, Awaitable[schema.ListSchemasResponse]], ]: raise NotImplementedError() @property def delete_schema( self, - ) -> typing.Callable[ - [schema.DeleteSchemaRequest], - typing.Union[empty.Empty, typing.Awaitable[empty.Empty]], + ) -> Callable[ + [schema.DeleteSchemaRequest], Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]] ]: raise NotImplementedError() @property def validate_schema( self, - ) -> typing.Callable[ + ) -> Callable[ [gp_schema.ValidateSchemaRequest], - typing.Union[ + Union[ gp_schema.ValidateSchemaResponse, - typing.Awaitable[gp_schema.ValidateSchemaResponse], + Awaitable[gp_schema.ValidateSchemaResponse], ], ]: raise NotImplementedError() @@ -186,11 +242,10 @@ def validate_schema( @property def validate_message( self, - ) -> typing.Callable[ + ) -> Callable[ [schema.ValidateMessageRequest], - typing.Union[ - schema.ValidateMessageResponse, - typing.Awaitable[schema.ValidateMessageResponse], + Union[ + schema.ValidateMessageResponse, Awaitable[schema.ValidateMessageResponse] ], ]: raise NotImplementedError() @@ -198,29 +253,29 @@ def validate_message( @property def set_iam_policy( self, - ) -> typing.Callable[ - [iam_policy.SetIamPolicyRequest], - typing.Union[policy.Policy, typing.Awaitable[policy.Policy]], + ) -> Callable[ + [iam_policy_pb2.SetIamPolicyRequest], + Union[policy_pb2.Policy, Awaitable[policy_pb2.Policy]], ]: raise NotImplementedError() @property def get_iam_policy( self, - ) -> typing.Callable[ - [iam_policy.GetIamPolicyRequest], - typing.Union[policy.Policy, typing.Awaitable[policy.Policy]], + ) -> Callable[ + [iam_policy_pb2.GetIamPolicyRequest], + Union[policy_pb2.Policy, Awaitable[policy_pb2.Policy]], ]: raise NotImplementedError() @property def test_iam_permissions( self, - ) -> typing.Callable[ - [iam_policy.TestIamPermissionsRequest], - typing.Union[ - iam_policy.TestIamPermissionsResponse, - typing.Awaitable[iam_policy.TestIamPermissionsResponse], + ) -> Callable[ + [iam_policy_pb2.TestIamPermissionsRequest], + Union[ + iam_policy_pb2.TestIamPermissionsResponse, + Awaitable[iam_policy_pb2.TestIamPermissionsResponse], ], ]: raise NotImplementedError() diff --git a/google/pubsub_v1/services/schema_service/transports/grpc.py b/google/pubsub_v1/services/schema_service/transports/grpc.py index ed9822e01..ebf4d6e9f 100644 --- a/google/pubsub_v1/services/schema_service/transports/grpc.py +++ b/google/pubsub_v1/services/schema_service/transports/grpc.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,24 +13,22 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple +from typing import Callable, Dict, Optional, Sequence, Tuple, Union from google.api_core import grpc_helpers # type: ignore from google.api_core import gapic_v1 # type: ignore -from google import auth # type: ignore -from google.auth import credentials # type: ignore +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 as iam_policy # type: ignore -from google.iam.v1 import policy_pb2 as policy # type: ignore -from google.protobuf import empty_pb2 as empty # 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 @@ -54,7 +51,7 @@ def __init__( self, *, host: str = "pubsub.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Sequence[str] = None, channel: grpc.Channel = None, @@ -68,7 +65,8 @@ def __init__( """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + 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 @@ -179,7 +177,7 @@ def __init__( def create_channel( cls, host: str = "pubsub.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Optional[Sequence[str]] = None, quota_project_id: Optional[str] = None, @@ -210,13 +208,15 @@ def create_channel( google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` and ``credentials_file`` are passed. """ - scopes = scopes or cls.AUTH_SCOPES + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + return grpc_helpers.create_channel( host, credentials=credentials, credentials_file=credentials_file, - scopes=scopes, quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, **kwargs, ) @@ -303,7 +303,7 @@ def list_schemas( return self._stubs["list_schemas"] @property - def delete_schema(self) -> Callable[[schema.DeleteSchemaRequest], empty.Empty]: + def delete_schema(self) -> Callable[[schema.DeleteSchemaRequest], empty_pb2.Empty]: r"""Return a callable for the delete schema method over gRPC. Deletes a schema. @@ -322,7 +322,7 @@ def delete_schema(self) -> Callable[[schema.DeleteSchemaRequest], empty.Empty]: self._stubs["delete_schema"] = self.grpc_channel.unary_unary( "/google.pubsub.v1.SchemaService/DeleteSchema", request_serializer=schema.DeleteSchemaRequest.serialize, - response_deserializer=empty.Empty.FromString, + response_deserializer=empty_pb2.Empty.FromString, ) return self._stubs["delete_schema"] @@ -381,7 +381,7 @@ def validate_message( @property def set_iam_policy( self, - ) -> Callable[[iam_policy.SetIamPolicyRequest], policy.Policy]: + ) -> 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. @@ -398,15 +398,15 @@ def set_iam_policy( 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.SetIamPolicyRequest.SerializeToString, - response_deserializer=policy.Policy.FromString, + 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.GetIamPolicyRequest], policy.Policy]: + ) -> 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 @@ -424,8 +424,8 @@ def get_iam_policy( 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.GetIamPolicyRequest.SerializeToString, - response_deserializer=policy.Policy.FromString, + request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, ) return self._stubs["get_iam_policy"] @@ -433,7 +433,8 @@ def get_iam_policy( def test_iam_permissions( self, ) -> Callable[ - [iam_policy.TestIamPermissionsRequest], iam_policy.TestIamPermissionsResponse + [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 @@ -452,8 +453,8 @@ def test_iam_permissions( 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.TestIamPermissionsRequest.SerializeToString, - response_deserializer=iam_policy.TestIamPermissionsResponse.FromString, + request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString, + response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString, ) return self._stubs["test_iam_permissions"] diff --git a/google/pubsub_v1/services/schema_service/transports/grpc_asyncio.py b/google/pubsub_v1/services/schema_service/transports/grpc_asyncio.py index c7cb3ac63..9adebdf9f 100644 --- a/google/pubsub_v1/services/schema_service/transports/grpc_asyncio.py +++ b/google/pubsub_v1/services/schema_service/transports/grpc_asyncio.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,25 +13,23 @@ # 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 +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union from google.api_core import gapic_v1 # type: ignore from google.api_core import grpc_helpers_async # type: ignore -from google import auth # type: ignore -from google.auth import credentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore +import packaging.version import grpc # type: ignore from grpc.experimental import aio # type: ignore -from google.iam.v1 import iam_policy_pb2 as iam_policy # type: ignore -from google.iam.v1 import policy_pb2 as policy # type: ignore -from google.protobuf import empty_pb2 as empty # 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 @@ -57,7 +54,7 @@ class SchemaServiceGrpcAsyncIOTransport(SchemaServiceTransport): def create_channel( cls, host: str = "pubsub.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: Optional[str] = None, scopes: Optional[Sequence[str]] = None, quota_project_id: Optional[str] = None, @@ -84,13 +81,15 @@ def create_channel( Returns: aio.Channel: A gRPC AsyncIO channel object. """ - scopes = scopes or cls.AUTH_SCOPES + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + return grpc_helpers_async.create_channel( host, credentials=credentials, credentials_file=credentials_file, - scopes=scopes, quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, **kwargs, ) @@ -98,7 +97,7 @@ def __init__( self, *, host: str = "pubsub.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: Optional[str] = None, scopes: Optional[Sequence[str]] = None, channel: aio.Channel = None, @@ -112,7 +111,8 @@ def __init__( """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + 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 @@ -170,7 +170,6 @@ def __init__( # 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 @@ -311,7 +310,7 @@ def list_schemas( @property def delete_schema( self, - ) -> Callable[[schema.DeleteSchemaRequest], Awaitable[empty.Empty]]: + ) -> Callable[[schema.DeleteSchemaRequest], Awaitable[empty_pb2.Empty]]: r"""Return a callable for the delete schema method over gRPC. Deletes a schema. @@ -330,7 +329,7 @@ def delete_schema( self._stubs["delete_schema"] = self.grpc_channel.unary_unary( "/google.pubsub.v1.SchemaService/DeleteSchema", request_serializer=schema.DeleteSchemaRequest.serialize, - response_deserializer=empty.Empty.FromString, + response_deserializer=empty_pb2.Empty.FromString, ) return self._stubs["delete_schema"] @@ -393,7 +392,7 @@ def validate_message( @property def set_iam_policy( self, - ) -> Callable[[iam_policy.SetIamPolicyRequest], Awaitable[policy.Policy]]: + ) -> 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. @@ -410,15 +409,15 @@ def set_iam_policy( 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.SetIamPolicyRequest.SerializeToString, - response_deserializer=policy.Policy.FromString, + 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.GetIamPolicyRequest], Awaitable[policy.Policy]]: + ) -> 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 @@ -436,8 +435,8 @@ def get_iam_policy( 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.GetIamPolicyRequest.SerializeToString, - response_deserializer=policy.Policy.FromString, + request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, ) return self._stubs["get_iam_policy"] @@ -445,8 +444,8 @@ def get_iam_policy( def test_iam_permissions( self, ) -> Callable[ - [iam_policy.TestIamPermissionsRequest], - Awaitable[iam_policy.TestIamPermissionsResponse], + [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 @@ -465,8 +464,8 @@ def test_iam_permissions( 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.TestIamPermissionsRequest.SerializeToString, - response_deserializer=iam_policy.TestIamPermissionsResponse.FromString, + request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString, + response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString, ) return self._stubs["test_iam_permissions"] diff --git a/google/pubsub_v1/services/subscriber/__init__.py b/google/pubsub_v1/services/subscriber/__init__.py index 361085a5e..0961d69d1 100644 --- a/google/pubsub_v1/services/subscriber/__init__.py +++ b/google/pubsub_v1/services/subscriber/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from .client import SubscriberClient from .async_client import SubscriberAsyncClient diff --git a/google/pubsub_v1/services/subscriber/async_client.py b/google/pubsub_v1/services/subscriber/async_client.py index 7dbc3c5ed..589fc090a 100644 --- a/google/pubsub_v1/services/subscriber/async_client.py +++ b/google/pubsub_v1/services/subscriber/async_client.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict import functools import re @@ -32,19 +30,18 @@ import pkg_resources import google.api_core.client_options as ClientOptions # type: ignore -from google.api_core import exceptions # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore from google.api_core import gapic_v1 # type: ignore from google.api_core import retry as retries # type: ignore -from google.auth import credentials # type: ignore +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 as iam_policy # type: ignore -from google.iam.v1 import policy_pb2 as policy # type: ignore -from google.protobuf import duration_pb2 as duration # type: ignore -from google.protobuf import timestamp_pb2 as timestamp # 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 @@ -68,25 +65,20 @@ class SubscriberAsyncClient: 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 @@ -140,7 +132,7 @@ def transport(self) -> SubscriberTransport: def __init__( self, *, - credentials: credentials.Credentials = None, + 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, @@ -177,7 +169,6 @@ def __init__( google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport creation failed for any reason. """ - self._client = SubscriberClient( credentials=credentials, transport=transport, @@ -276,7 +267,6 @@ async def create_subscription( 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. @@ -301,7 +291,6 @@ async def create_subscription( # 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: @@ -364,7 +353,6 @@ async def get_subscription( 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. @@ -389,7 +377,6 @@ async def get_subscription( # If we have keyword arguments corresponding to fields on the # request, apply these. - if subscription is not None: request.subscription = subscription @@ -442,7 +429,6 @@ async def update_subscription( request (:class:`google.pubsub_v1.types.UpdateSubscriptionRequest`): The request object. Request for the UpdateSubscription method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -454,7 +440,6 @@ async def update_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, @@ -508,7 +493,6 @@ async def list_subscriptions( 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. @@ -537,7 +521,6 @@ async def list_subscriptions( # If we have keyword arguments corresponding to fields on the # request, apply these. - if project is not None: request.project = project @@ -605,7 +588,6 @@ async def delete_subscription( 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. @@ -626,7 +608,6 @@ async def delete_subscription( # If we have keyword arguments corresponding to fields on the # request, apply these. - if subscription is not None: request.subscription = subscription @@ -708,7 +689,6 @@ async def modify_ack_deadline( 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. @@ -729,12 +709,10 @@ async def modify_ack_deadline( # 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) @@ -804,7 +782,6 @@ async def acknowledge( 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. @@ -825,10 +802,8 @@ async def acknowledge( # 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) @@ -910,7 +885,6 @@ async def pull( 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. @@ -935,7 +909,6 @@ async def pull( # 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: @@ -1087,7 +1060,6 @@ async def modify_push_config( 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. @@ -1108,7 +1080,6 @@ async def modify_push_config( # 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: @@ -1169,7 +1140,6 @@ async def get_snapshot( 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. @@ -1200,7 +1170,6 @@ async def get_snapshot( # If we have keyword arguments corresponding to fields on the # request, apply these. - if snapshot is not None: request.snapshot = snapshot @@ -1261,7 +1230,6 @@ async def list_snapshots( 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. @@ -1290,7 +1258,6 @@ async def list_snapshots( # If we have keyword arguments corresponding to fields on the # request, apply these. - if project is not None: request.project = project @@ -1392,7 +1359,6 @@ async def create_snapshot( 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. @@ -1423,7 +1389,6 @@ async def create_snapshot( # 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: @@ -1476,7 +1441,6 @@ async def update_snapshot( request (:class:`google.pubsub_v1.types.UpdateSnapshotRequest`): The request object. Request for the UpdateSnapshot method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -1494,7 +1458,6 @@ async def update_snapshot( """ # Create or coerce a protobuf request object. - request = pubsub.UpdateSnapshotRequest(request) # Wrap the RPC method; this adds retry and timeout information, @@ -1557,7 +1520,6 @@ async def delete_snapshot( 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. @@ -1578,7 +1540,6 @@ async def delete_snapshot( # If we have keyword arguments corresponding to fields on the # request, apply these. - if snapshot is not None: request.snapshot = snapshot @@ -1629,7 +1590,6 @@ async def seek( Args: request (:class:`google.pubsub_v1.types.SeekRequest`): The request object. Request for the `Seek` method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -1641,7 +1601,6 @@ async def seek( 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, @@ -1679,16 +1638,16 @@ async def seek( async def set_iam_policy( self, - request: iam_policy.SetIamPolicyRequest = None, + request: iam_policy_pb2.SetIamPolicyRequest = None, *, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), - ) -> policy.Policy: + ) -> policy_pb2.Policy: r"""Sets the IAM access control policy on the specified function. Replaces any existing policy. Args: - request (:class:`~.iam_policy.SetIamPolicyRequest`): + 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, @@ -1697,7 +1656,7 @@ async def set_iam_policy( metadata (Sequence[Tuple[str, str]]): Strings which should be sent along with the request as metadata. Returns: - ~.policy.Policy: + ~.policy_pb2.Policy: Defines an Identity and Access Management (IAM) policy. It is used to specify access control policies for Cloud Platform resources. @@ -1761,7 +1720,7 @@ async def set_iam_policy( # The request isn't a proto-plus wrapped type, # so it must be constructed via keyword expansion. if isinstance(request, dict): - request = iam_policy.SetIamPolicyRequest(**request) + request = iam_policy_pb2.SetIamPolicyRequest(**request) # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. @@ -1785,17 +1744,17 @@ async def set_iam_policy( async def get_iam_policy( self, - request: iam_policy.GetIamPolicyRequest = None, + request: iam_policy_pb2.GetIamPolicyRequest = None, *, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), - ) -> policy.Policy: + ) -> 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.GetIamPolicyRequest`): + 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, @@ -1804,7 +1763,7 @@ async def get_iam_policy( metadata (Sequence[Tuple[str, str]]): Strings which should be sent along with the request as metadata. Returns: - ~.policy.Policy: + ~.policy_pb2.Policy: Defines an Identity and Access Management (IAM) policy. It is used to specify access control policies for Cloud Platform resources. @@ -1868,7 +1827,7 @@ async def get_iam_policy( # The request isn't a proto-plus wrapped type, # so it must be constructed via keyword expansion. if isinstance(request, dict): - request = iam_policy.GetIamPolicyRequest(**request) + request = iam_policy_pb2.GetIamPolicyRequest(**request) # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. @@ -1892,17 +1851,17 @@ async def get_iam_policy( async def test_iam_permissions( self, - request: iam_policy.TestIamPermissionsRequest = None, + request: iam_policy_pb2.TestIamPermissionsRequest = None, *, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), - ) -> iam_policy.TestIamPermissionsResponse: + ) -> 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.TestIamPermissionsRequest`): + 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, @@ -1911,7 +1870,7 @@ async def test_iam_permissions( metadata (Sequence[Tuple[str, str]]): Strings which should be sent along with the request as metadata. Returns: - ~.iam_policy.TestIamPermissionsResponse: + ~iam_policy_pb2.PolicyTestIamPermissionsResponse: Response message for ``TestIamPermissions`` method. """ # Create or coerce a protobuf request object. @@ -1919,7 +1878,7 @@ async def test_iam_permissions( # The request isn't a proto-plus wrapped type, # so it must be constructed via keyword expansion. if isinstance(request, dict): - request = iam_policy.TestIamPermissionsRequest(**request) + request = iam_policy_pb2.TestIamPermissionsRequest(**request) # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. diff --git a/google/pubsub_v1/services/subscriber/client.py b/google/pubsub_v1/services/subscriber/client.py index e2fbde711..1c69f3b41 100644 --- a/google/pubsub_v1/services/subscriber/client.py +++ b/google/pubsub_v1/services/subscriber/client.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from distutils import util import functools @@ -35,24 +33,23 @@ import pkg_resources from google.api_core import client_options as client_options_lib # type: ignore -from google.api_core import exceptions # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore from google.api_core import gapic_v1 # type: ignore from google.api_core import retry as retries # type: ignore -from google.auth import credentials # type: ignore +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 -from google.iam.v1 import iam_policy_pb2 as iam_policy # type: ignore -from google.iam.v1 import policy_pb2 as policy # type: ignore -from google.protobuf import duration_pb2 as duration # type: ignore -from google.protobuf import timestamp_pb2 as timestamp # 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 import grpc - from .transports.base import SubscriberTransport, DEFAULT_CLIENT_INFO from .transports.grpc import SubscriberGrpcTransport from .transports.grpc_asyncio import SubscriberGrpcAsyncIOTransport @@ -290,7 +287,7 @@ def parse_common_location_path(path: str) -> Dict[str, str]: def __init__( self, *, - credentials: Optional[credentials.Credentials] = None, + 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, @@ -502,7 +499,6 @@ def create_subscription( 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. @@ -529,10 +525,8 @@ def create_subscription( # 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: @@ -581,7 +575,6 @@ def get_subscription( 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. @@ -608,10 +601,8 @@ def get_subscription( # 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 @@ -650,7 +641,6 @@ def update_subscription( request (google.pubsub_v1.types.UpdateSubscriptionRequest): The request object. Request for the UpdateSubscription method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -662,7 +652,6 @@ def update_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 @@ -711,7 +700,6 @@ def list_subscriptions( 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. @@ -742,10 +730,8 @@ def list_subscriptions( # 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 @@ -799,7 +785,6 @@ def delete_subscription( 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. @@ -822,10 +807,8 @@ def delete_subscription( # 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 @@ -897,7 +880,6 @@ def modify_ack_deadline( 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. @@ -920,10 +902,8 @@ def modify_ack_deadline( # 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: @@ -987,7 +967,6 @@ def acknowledge( 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. @@ -1010,10 +989,8 @@ def acknowledge( # 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: @@ -1087,7 +1064,6 @@ def pull( 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. @@ -1114,10 +1090,8 @@ def pull( # 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: @@ -1244,7 +1218,6 @@ def modify_push_config( 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. @@ -1267,10 +1240,8 @@ def modify_push_config( # 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: @@ -1321,7 +1292,6 @@ def get_snapshot( 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. @@ -1354,10 +1324,8 @@ def get_snapshot( # 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 @@ -1404,7 +1372,6 @@ def list_snapshots( 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. @@ -1435,10 +1402,8 @@ def list_snapshots( # 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 @@ -1526,7 +1491,6 @@ def create_snapshot( 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. @@ -1559,10 +1523,8 @@ def create_snapshot( # 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: @@ -1605,7 +1567,6 @@ def update_snapshot( request (google.pubsub_v1.types.UpdateSnapshotRequest): The request object. Request for the UpdateSnapshot method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -1623,7 +1584,6 @@ def update_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 @@ -1681,7 +1641,6 @@ def delete_snapshot( 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. @@ -1704,10 +1663,8 @@ def delete_snapshot( # 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 @@ -1748,7 +1705,6 @@ def seek( Args: request (google.pubsub_v1.types.SeekRequest): The request object. Request for the `Seek` method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -1760,7 +1716,6 @@ def seek( 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 @@ -1788,17 +1743,17 @@ def seek( def set_iam_policy( self, - request: iam_policy.SetIamPolicyRequest = None, + request: iam_policy_pb2.SetIamPolicyRequest = None, *, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), - ) -> policy.Policy: + ) -> policy_pb2.Policy: r"""Sets the IAM access control policy on the specified function. Replaces any existing policy. Args: - request (:class:`~.iam_policy.SetIamPolicyRequest`): + 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, @@ -1807,7 +1762,7 @@ def set_iam_policy( metadata (Sequence[Tuple[str, str]]): Strings which should be sent along with the request as metadata. Returns: - ~.policy.Policy: + ~.policy_pb2.Policy: Defines an Identity and Access Management (IAM) policy. It is used to specify access control policies for Cloud Platform resources. @@ -1874,7 +1829,7 @@ def set_iam_policy( # The request isn't a proto-plus wrapped type, # so it must be constructed via keyword expansion. if isinstance(request, dict): - request = iam_policy.SetIamPolicyRequest(**request) + request = iam_policy_pb2.SetIamPolicyRequest(**request) # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. @@ -1898,18 +1853,18 @@ def set_iam_policy( def get_iam_policy( self, - request: iam_policy.GetIamPolicyRequest = None, + request: iam_policy_pb2.GetIamPolicyRequest = None, *, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), - ) -> policy.Policy: + ) -> 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.GetIamPolicyRequest`): + 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, @@ -1918,7 +1873,7 @@ def get_iam_policy( metadata (Sequence[Tuple[str, str]]): Strings which should be sent along with the request as metadata. Returns: - ~.policy.Policy: + ~.policy_pb2.Policy: Defines an Identity and Access Management (IAM) policy. It is used to specify access control policies for Cloud Platform resources. @@ -1985,7 +1940,7 @@ def get_iam_policy( # The request isn't a proto-plus wrapped type, # so it must be constructed via keyword expansion. if isinstance(request, dict): - request = iam_policy.GetIamPolicyRequest(**request) + request = iam_policy_pb2.GetIamPolicyRequest(**request) # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. @@ -2009,18 +1964,18 @@ def get_iam_policy( def test_iam_permissions( self, - request: iam_policy.TestIamPermissionsRequest = None, + request: iam_policy_pb2.TestIamPermissionsRequest = None, *, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), - ) -> iam_policy.TestIamPermissionsResponse: + ) -> 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.TestIamPermissionsRequest`): + 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, @@ -2029,7 +1984,7 @@ def test_iam_permissions( metadata (Sequence[Tuple[str, str]]): Strings which should be sent along with the request as metadata. Returns: - ~.iam_policy.TestIamPermissionsResponse: + ~.iam_policy_pb2.TestIamPermissionsResponse: Response message for ``TestIamPermissions`` method. """ # Create or coerce a protobuf request object. @@ -2037,7 +1992,7 @@ def test_iam_permissions( # The request isn't a proto-plus wrapped type, # so it must be constructed via keyword expansion. if isinstance(request, dict): - request = iam_policy.TestIamPermissionsRequest(**request) + request = iam_policy_pb2.TestIamPermissionsRequest(**request) # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. diff --git a/google/pubsub_v1/services/subscriber/pagers.py b/google/pubsub_v1/services/subscriber/pagers.py index b7ec9f6e3..3e0de8ddc 100644 --- a/google/pubsub_v1/services/subscriber/pagers.py +++ b/google/pubsub_v1/services/subscriber/pagers.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from typing import ( Any, AsyncIterable, diff --git a/google/pubsub_v1/services/subscriber/transports/__init__.py b/google/pubsub_v1/services/subscriber/transports/__init__.py index 0246cfeca..023406c8f 100644 --- a/google/pubsub_v1/services/subscriber/transports/__init__.py +++ b/google/pubsub_v1/services/subscriber/transports/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from typing import Dict, Type diff --git a/google/pubsub_v1/services/subscriber/transports/base.py b/google/pubsub_v1/services/subscriber/transports/base.py index b8a1b97b3..51189d8bf 100644 --- a/google/pubsub_v1/services/subscriber/transports/base.py +++ b/google/pubsub_v1/services/subscriber/transports/base.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,23 +13,23 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import abc -import typing +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union +import packaging.version import pkg_resources -from google import auth # type: ignore -from google.api_core import exceptions # type: ignore +import google.auth # type: ignore +import google.api_core # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore from google.api_core import gapic_v1 # type: ignore from google.api_core import retry as retries # type: ignore -from google.auth import credentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore -from google.iam.v1 import iam_policy_pb2 as iam_policy # type: ignore -from google.iam.v1 import policy_pb2 as policy # type: ignore -from google.protobuf import empty_pb2 as empty # 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( client_library_version=pkg_resources.get_distribution( @@ -40,6 +39,17 @@ except pkg_resources.DistributionNotFound: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() +try: + # google.auth.__version__ was added in 1.26.0 + _GOOGLE_AUTH_VERSION = google.auth.__version__ +except AttributeError: + try: # try pkg_resources if it is available + _GOOGLE_AUTH_VERSION = pkg_resources.get_distribution("google-auth").version + except pkg_resources.DistributionNotFound: # pragma: NO COVER + _GOOGLE_AUTH_VERSION = None + +_API_CORE_VERSION = google.api_core.__version__ + class SubscriberTransport(abc.ABC): """Abstract transport class for Subscriber.""" @@ -49,21 +59,24 @@ class SubscriberTransport(abc.ABC): "https://www.googleapis.com/auth/pubsub", ) + DEFAULT_HOST: str = "pubsub.googleapis.com" + def __init__( self, *, - host: str = "pubsub.googleapis.com", - credentials: credentials.Credentials = None, - credentials_file: typing.Optional[str] = None, - scopes: typing.Optional[typing.Sequence[str]] = AUTH_SCOPES, - quota_project_id: typing.Optional[str] = None, + 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, **kwargs, ) -> None: """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + 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 @@ -72,7 +85,7 @@ def __init__( 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. - scope (Optional[Sequence[str]]): A list of scopes. + 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): @@ -86,29 +99,76 @@ def __init__( host += ":443" self._host = host + scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) + # Save the scopes. self._scopes = scopes or self.AUTH_SCOPES # If no credentials are provided, then determine the appropriate # defaults. if credentials and credentials_file: - raise exceptions.DuplicateCredentialArgs( + raise core_exceptions.DuplicateCredentialArgs( "'credentials_file' and 'credentials' are mutually exclusive" ) if credentials_file is not None: - credentials, _ = auth.load_credentials_from_file( - credentials_file, scopes=self._scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, **scopes_kwargs, quota_project_id=quota_project_id ) elif credentials is None: - credentials, _ = auth.default( - scopes=self._scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.default( + **scopes_kwargs, quota_project_id=quota_project_id ) # Save the credentials. self._credentials = credentials + # TODO(busunkim): These two class methods are in the base transport + # to avoid duplicating code across the transport classes. These functions + # should be deleted once the minimum required versions of google-api-core + # and google-auth are increased. + + # TODO: Remove this function once google-auth >= 1.25.0 is required + @classmethod + def _get_scopes_kwargs( + cls, host: str, scopes: Optional[Sequence[str]] + ) -> Dict[str, Optional[Sequence[str]]]: + """Returns scopes kwargs to pass to google-auth methods depending on the google-auth version""" + + scopes_kwargs = {} + + if _GOOGLE_AUTH_VERSION and ( + packaging.version.parse(_GOOGLE_AUTH_VERSION) + >= packaging.version.parse("1.25.0") + ): + scopes_kwargs = {"scopes": scopes, "default_scopes": cls.AUTH_SCOPES} + else: + scopes_kwargs = {"scopes": scopes or cls.AUTH_SCOPES} + + return scopes_kwargs + + # TODO: Remove this function once google-api-core >= 1.26.0 is required + @classmethod + def _get_self_signed_jwt_kwargs( + cls, host: str, scopes: Optional[Sequence[str]] + ) -> Dict[str, Union[Optional[Sequence[str]], str]]: + """Returns kwargs to pass to grpc_helpers.create_channel depending on the google-api-core version""" + + self_signed_jwt_kwargs: Dict[str, Union[Optional[Sequence[str]], str]] = {} + + if _API_CORE_VERSION and ( + packaging.version.parse(_API_CORE_VERSION) + >= packaging.version.parse("1.26.0") + ): + self_signed_jwt_kwargs["default_scopes"] = cls.AUTH_SCOPES + self_signed_jwt_kwargs["scopes"] = scopes + self_signed_jwt_kwargs["default_host"] = cls.DEFAULT_HOST + else: + self_signed_jwt_kwargs["scopes"] = scopes or cls.AUTH_SCOPES + + return self_signed_jwt_kwargs + def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. self._wrapped_methods = { @@ -119,9 +179,9 @@ def _prep_wrapped_messages(self, client_info): maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.Aborted, - exceptions.ServiceUnavailable, - exceptions.Unknown, + core_exceptions.Aborted, + core_exceptions.ServiceUnavailable, + core_exceptions.Unknown, ), deadline=60.0, ), @@ -135,9 +195,9 @@ def _prep_wrapped_messages(self, client_info): maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.Aborted, - exceptions.ServiceUnavailable, - exceptions.Unknown, + core_exceptions.Aborted, + core_exceptions.ServiceUnavailable, + core_exceptions.Unknown, ), deadline=60.0, ), @@ -150,7 +210,9 @@ def _prep_wrapped_messages(self, client_info): initial=0.1, maximum=60.0, multiplier=1.3, - predicate=retries.if_exception_type(exceptions.ServiceUnavailable,), + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), deadline=60.0, ), default_timeout=60.0, @@ -163,9 +225,9 @@ def _prep_wrapped_messages(self, client_info): maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.Aborted, - exceptions.ServiceUnavailable, - exceptions.Unknown, + core_exceptions.Aborted, + core_exceptions.ServiceUnavailable, + core_exceptions.Unknown, ), deadline=60.0, ), @@ -178,7 +240,9 @@ def _prep_wrapped_messages(self, client_info): initial=0.1, maximum=60.0, multiplier=1.3, - predicate=retries.if_exception_type(exceptions.ServiceUnavailable,), + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), deadline=60.0, ), default_timeout=60.0, @@ -190,7 +254,9 @@ def _prep_wrapped_messages(self, client_info): initial=0.1, maximum=60.0, multiplier=1.3, - predicate=retries.if_exception_type(exceptions.ServiceUnavailable,), + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), deadline=60.0, ), default_timeout=60.0, @@ -202,7 +268,9 @@ def _prep_wrapped_messages(self, client_info): initial=0.1, maximum=60.0, multiplier=1.3, - predicate=retries.if_exception_type(exceptions.ServiceUnavailable,), + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), deadline=60.0, ), default_timeout=60.0, @@ -215,9 +283,9 @@ def _prep_wrapped_messages(self, client_info): maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.Aborted, - exceptions.ServiceUnavailable, - exceptions.Unknown, + core_exceptions.Aborted, + core_exceptions.ServiceUnavailable, + core_exceptions.Unknown, ), deadline=60.0, ), @@ -231,11 +299,11 @@ def _prep_wrapped_messages(self, client_info): maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.Aborted, - exceptions.DeadlineExceeded, - exceptions.InternalServerError, - exceptions.ResourceExhausted, - exceptions.ServiceUnavailable, + core_exceptions.Aborted, + core_exceptions.DeadlineExceeded, + core_exceptions.InternalServerError, + core_exceptions.ResourceExhausted, + core_exceptions.ServiceUnavailable, ), deadline=900.0, ), @@ -248,7 +316,9 @@ def _prep_wrapped_messages(self, client_info): initial=0.1, maximum=60.0, multiplier=1.3, - predicate=retries.if_exception_type(exceptions.ServiceUnavailable,), + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), deadline=60.0, ), default_timeout=60.0, @@ -261,9 +331,9 @@ def _prep_wrapped_messages(self, client_info): maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.Aborted, - exceptions.ServiceUnavailable, - exceptions.Unknown, + core_exceptions.Aborted, + core_exceptions.ServiceUnavailable, + core_exceptions.Unknown, ), deadline=60.0, ), @@ -277,9 +347,9 @@ def _prep_wrapped_messages(self, client_info): maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.Aborted, - exceptions.ServiceUnavailable, - exceptions.Unknown, + core_exceptions.Aborted, + core_exceptions.ServiceUnavailable, + core_exceptions.Unknown, ), deadline=60.0, ), @@ -292,7 +362,9 @@ def _prep_wrapped_messages(self, client_info): initial=0.1, maximum=60.0, multiplier=1.3, - predicate=retries.if_exception_type(exceptions.ServiceUnavailable,), + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), deadline=60.0, ), default_timeout=60.0, @@ -304,7 +376,9 @@ def _prep_wrapped_messages(self, client_info): initial=0.1, maximum=60.0, multiplier=1.3, - predicate=retries.if_exception_type(exceptions.ServiceUnavailable,), + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), deadline=60.0, ), default_timeout=60.0, @@ -316,7 +390,9 @@ def _prep_wrapped_messages(self, client_info): initial=0.1, maximum=60.0, multiplier=1.3, - predicate=retries.if_exception_type(exceptions.ServiceUnavailable,), + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), deadline=60.0, ), default_timeout=60.0, @@ -329,9 +405,9 @@ def _prep_wrapped_messages(self, client_info): maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.Aborted, - exceptions.ServiceUnavailable, - exceptions.Unknown, + core_exceptions.Aborted, + core_exceptions.ServiceUnavailable, + core_exceptions.Unknown, ), deadline=60.0, ), @@ -343,38 +419,38 @@ def _prep_wrapped_messages(self, client_info): @property def create_subscription( self, - ) -> typing.Callable[ + ) -> Callable[ [pubsub.Subscription], - typing.Union[pubsub.Subscription, typing.Awaitable[pubsub.Subscription]], + Union[pubsub.Subscription, Awaitable[pubsub.Subscription]], ]: raise NotImplementedError() @property def get_subscription( self, - ) -> typing.Callable[ + ) -> Callable[ [pubsub.GetSubscriptionRequest], - typing.Union[pubsub.Subscription, typing.Awaitable[pubsub.Subscription]], + Union[pubsub.Subscription, Awaitable[pubsub.Subscription]], ]: raise NotImplementedError() @property def update_subscription( self, - ) -> typing.Callable[ + ) -> Callable[ [pubsub.UpdateSubscriptionRequest], - typing.Union[pubsub.Subscription, typing.Awaitable[pubsub.Subscription]], + Union[pubsub.Subscription, Awaitable[pubsub.Subscription]], ]: raise NotImplementedError() @property def list_subscriptions( self, - ) -> typing.Callable[ + ) -> Callable[ [pubsub.ListSubscriptionsRequest], - typing.Union[ + Union[ pubsub.ListSubscriptionsResponse, - typing.Awaitable[pubsub.ListSubscriptionsResponse], + Awaitable[pubsub.ListSubscriptionsResponse], ], ]: raise NotImplementedError() @@ -382,141 +458,133 @@ def list_subscriptions( @property def delete_subscription( self, - ) -> typing.Callable[ + ) -> Callable[ [pubsub.DeleteSubscriptionRequest], - typing.Union[empty.Empty, typing.Awaitable[empty.Empty]], + Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]], ]: raise NotImplementedError() @property def modify_ack_deadline( self, - ) -> typing.Callable[ + ) -> Callable[ [pubsub.ModifyAckDeadlineRequest], - typing.Union[empty.Empty, typing.Awaitable[empty.Empty]], + Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]], ]: raise NotImplementedError() @property def acknowledge( self, - ) -> typing.Callable[ - [pubsub.AcknowledgeRequest], - typing.Union[empty.Empty, typing.Awaitable[empty.Empty]], + ) -> Callable[ + [pubsub.AcknowledgeRequest], Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]] ]: raise NotImplementedError() @property def pull( self, - ) -> typing.Callable[ - [pubsub.PullRequest], - typing.Union[pubsub.PullResponse, typing.Awaitable[pubsub.PullResponse]], + ) -> Callable[ + [pubsub.PullRequest], Union[pubsub.PullResponse, Awaitable[pubsub.PullResponse]] ]: raise NotImplementedError() @property def streaming_pull( self, - ) -> typing.Callable[ + ) -> Callable[ [pubsub.StreamingPullRequest], - typing.Union[ - pubsub.StreamingPullResponse, typing.Awaitable[pubsub.StreamingPullResponse] - ], + Union[pubsub.StreamingPullResponse, Awaitable[pubsub.StreamingPullResponse]], ]: raise NotImplementedError() @property def modify_push_config( self, - ) -> typing.Callable[ + ) -> Callable[ [pubsub.ModifyPushConfigRequest], - typing.Union[empty.Empty, typing.Awaitable[empty.Empty]], + Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]], ]: raise NotImplementedError() @property def get_snapshot( self, - ) -> typing.Callable[ - [pubsub.GetSnapshotRequest], - typing.Union[pubsub.Snapshot, typing.Awaitable[pubsub.Snapshot]], + ) -> Callable[ + [pubsub.GetSnapshotRequest], Union[pubsub.Snapshot, Awaitable[pubsub.Snapshot]] ]: raise NotImplementedError() @property def list_snapshots( self, - ) -> typing.Callable[ + ) -> Callable[ [pubsub.ListSnapshotsRequest], - typing.Union[ - pubsub.ListSnapshotsResponse, typing.Awaitable[pubsub.ListSnapshotsResponse] - ], + Union[pubsub.ListSnapshotsResponse, Awaitable[pubsub.ListSnapshotsResponse]], ]: raise NotImplementedError() @property def create_snapshot( self, - ) -> typing.Callable[ + ) -> Callable[ [pubsub.CreateSnapshotRequest], - typing.Union[pubsub.Snapshot, typing.Awaitable[pubsub.Snapshot]], + Union[pubsub.Snapshot, Awaitable[pubsub.Snapshot]], ]: raise NotImplementedError() @property def update_snapshot( self, - ) -> typing.Callable[ + ) -> Callable[ [pubsub.UpdateSnapshotRequest], - typing.Union[pubsub.Snapshot, typing.Awaitable[pubsub.Snapshot]], + Union[pubsub.Snapshot, Awaitable[pubsub.Snapshot]], ]: raise NotImplementedError() @property def delete_snapshot( self, - ) -> typing.Callable[ + ) -> Callable[ [pubsub.DeleteSnapshotRequest], - typing.Union[empty.Empty, typing.Awaitable[empty.Empty]], + Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]], ]: raise NotImplementedError() @property def seek( self, - ) -> typing.Callable[ - [pubsub.SeekRequest], - typing.Union[pubsub.SeekResponse, typing.Awaitable[pubsub.SeekResponse]], + ) -> Callable[ + [pubsub.SeekRequest], Union[pubsub.SeekResponse, Awaitable[pubsub.SeekResponse]] ]: raise NotImplementedError() @property def set_iam_policy( self, - ) -> typing.Callable[ - [iam_policy.SetIamPolicyRequest], - typing.Union[policy.Policy, typing.Awaitable[policy.Policy]], + ) -> Callable[ + [iam_policy_pb2.SetIamPolicyRequest], + Union[policy_pb2.Policy, Awaitable[policy_pb2.Policy]], ]: raise NotImplementedError() @property def get_iam_policy( self, - ) -> typing.Callable[ - [iam_policy.GetIamPolicyRequest], - typing.Union[policy.Policy, typing.Awaitable[policy.Policy]], + ) -> Callable[ + [iam_policy_pb2.GetIamPolicyRequest], + Union[policy_pb2.Policy, Awaitable[policy_pb2.Policy]], ]: raise NotImplementedError() @property def test_iam_permissions( self, - ) -> typing.Callable[ - [iam_policy.TestIamPermissionsRequest], - typing.Union[ - iam_policy.TestIamPermissionsResponse, - typing.Awaitable[iam_policy.TestIamPermissionsResponse], + ) -> Callable[ + [iam_policy_pb2.TestIamPermissionsRequest], + Union[ + iam_policy_pb2.TestIamPermissionsResponse, + Awaitable[iam_policy_pb2.TestIamPermissionsResponse], ], ]: raise NotImplementedError() diff --git a/google/pubsub_v1/services/subscriber/transports/grpc.py b/google/pubsub_v1/services/subscriber/transports/grpc.py index b3f26f1f0..7668b02e7 100644 --- a/google/pubsub_v1/services/subscriber/transports/grpc.py +++ b/google/pubsub_v1/services/subscriber/transports/grpc.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,23 +13,21 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple +from typing import Callable, Dict, Optional, Sequence, Tuple, Union from google.api_core import grpc_helpers # type: ignore from google.api_core import gapic_v1 # type: ignore -from google import auth # type: ignore -from google.auth import credentials # type: ignore +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 as iam_policy # type: ignore -from google.iam.v1 import policy_pb2 as policy # type: ignore -from google.protobuf import empty_pb2 as empty # 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 @@ -56,7 +53,7 @@ def __init__( self, *, host: str = "pubsub.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Sequence[str] = None, channel: grpc.Channel = None, @@ -70,7 +67,8 @@ def __init__( """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + 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 @@ -181,7 +179,7 @@ def __init__( def create_channel( cls, host: str = "pubsub.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Optional[Sequence[str]] = None, quota_project_id: Optional[str] = None, @@ -212,13 +210,15 @@ def create_channel( google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` and ``credentials_file`` are passed. """ - scopes = scopes or cls.AUTH_SCOPES + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + return grpc_helpers.create_channel( host, credentials=credentials, credentials_file=credentials_file, - scopes=scopes, quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, **kwargs, ) @@ -349,7 +349,7 @@ def list_subscriptions( @property def delete_subscription( self, - ) -> Callable[[pubsub.DeleteSubscriptionRequest], empty.Empty]: + ) -> 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 @@ -373,14 +373,14 @@ def delete_subscription( self._stubs["delete_subscription"] = self.grpc_channel.unary_unary( "/google.pubsub.v1.Subscriber/DeleteSubscription", request_serializer=pubsub.DeleteSubscriptionRequest.serialize, - response_deserializer=empty.Empty.FromString, + response_deserializer=empty_pb2.Empty.FromString, ) return self._stubs["delete_subscription"] @property def modify_ack_deadline( self, - ) -> Callable[[pubsub.ModifyAckDeadlineRequest], empty.Empty]: + ) -> 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 @@ -404,12 +404,12 @@ def modify_ack_deadline( self._stubs["modify_ack_deadline"] = self.grpc_channel.unary_unary( "/google.pubsub.v1.Subscriber/ModifyAckDeadline", request_serializer=pubsub.ModifyAckDeadlineRequest.serialize, - response_deserializer=empty.Empty.FromString, + response_deserializer=empty_pb2.Empty.FromString, ) return self._stubs["modify_ack_deadline"] @property - def acknowledge(self) -> Callable[[pubsub.AcknowledgeRequest], empty.Empty]: + 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 @@ -435,7 +435,7 @@ def acknowledge(self) -> Callable[[pubsub.AcknowledgeRequest], empty.Empty]: self._stubs["acknowledge"] = self.grpc_channel.unary_unary( "/google.pubsub.v1.Subscriber/Acknowledge", request_serializer=pubsub.AcknowledgeRequest.serialize, - response_deserializer=empty.Empty.FromString, + response_deserializer=empty_pb2.Empty.FromString, ) return self._stubs["acknowledge"] @@ -501,7 +501,7 @@ def streaming_pull( @property def modify_push_config( self, - ) -> Callable[[pubsub.ModifyPushConfigRequest], empty.Empty]: + ) -> 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. @@ -526,7 +526,7 @@ def modify_push_config( self._stubs["modify_push_config"] = self.grpc_channel.unary_unary( "/google.pubsub.v1.Subscriber/ModifyPushConfig", request_serializer=pubsub.ModifyPushConfigRequest.serialize, - response_deserializer=empty.Empty.FromString, + response_deserializer=empty_pb2.Empty.FromString, ) return self._stubs["modify_push_config"] @@ -667,7 +667,9 @@ def update_snapshot( return self._stubs["update_snapshot"] @property - def delete_snapshot(self) -> Callable[[pubsub.DeleteSnapshotRequest], empty.Empty]: + 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] @@ -695,7 +697,7 @@ def delete_snapshot(self) -> Callable[[pubsub.DeleteSnapshotRequest], empty.Empt self._stubs["delete_snapshot"] = self.grpc_channel.unary_unary( "/google.pubsub.v1.Subscriber/DeleteSnapshot", request_serializer=pubsub.DeleteSnapshotRequest.serialize, - response_deserializer=empty.Empty.FromString, + response_deserializer=empty_pb2.Empty.FromString, ) return self._stubs["delete_snapshot"] @@ -734,7 +736,7 @@ def seek(self) -> Callable[[pubsub.SeekRequest], pubsub.SeekResponse]: @property def set_iam_policy( self, - ) -> Callable[[iam_policy.SetIamPolicyRequest], policy.Policy]: + ) -> 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. @@ -751,15 +753,15 @@ def set_iam_policy( 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.SetIamPolicyRequest.SerializeToString, - response_deserializer=policy.Policy.FromString, + 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.GetIamPolicyRequest], policy.Policy]: + ) -> 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 @@ -777,8 +779,8 @@ def get_iam_policy( 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.GetIamPolicyRequest.SerializeToString, - response_deserializer=policy.Policy.FromString, + request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, ) return self._stubs["get_iam_policy"] @@ -786,7 +788,8 @@ def get_iam_policy( def test_iam_permissions( self, ) -> Callable[ - [iam_policy.TestIamPermissionsRequest], iam_policy.TestIamPermissionsResponse + [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 @@ -805,8 +808,8 @@ def test_iam_permissions( 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.TestIamPermissionsRequest.SerializeToString, - response_deserializer=iam_policy.TestIamPermissionsResponse.FromString, + request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString, + response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString, ) return self._stubs["test_iam_permissions"] diff --git a/google/pubsub_v1/services/subscriber/transports/grpc_asyncio.py b/google/pubsub_v1/services/subscriber/transports/grpc_asyncio.py index bc385d317..6ebf0746a 100644 --- a/google/pubsub_v1/services/subscriber/transports/grpc_asyncio.py +++ b/google/pubsub_v1/services/subscriber/transports/grpc_asyncio.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,24 +13,22 @@ # 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 +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union from google.api_core import gapic_v1 # type: ignore from google.api_core import grpc_helpers_async # type: ignore -from google import auth # type: ignore -from google.auth import credentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore +import packaging.version import grpc # type: ignore from grpc.experimental import aio # type: ignore -from google.iam.v1 import iam_policy_pb2 as iam_policy # type: ignore -from google.iam.v1 import policy_pb2 as policy # type: ignore -from google.protobuf import empty_pb2 as empty # 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 @@ -59,7 +56,7 @@ class SubscriberGrpcAsyncIOTransport(SubscriberTransport): def create_channel( cls, host: str = "pubsub.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: Optional[str] = None, scopes: Optional[Sequence[str]] = None, quota_project_id: Optional[str] = None, @@ -86,13 +83,15 @@ def create_channel( Returns: aio.Channel: A gRPC AsyncIO channel object. """ - scopes = scopes or cls.AUTH_SCOPES + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + return grpc_helpers_async.create_channel( host, credentials=credentials, credentials_file=credentials_file, - scopes=scopes, quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, **kwargs, ) @@ -100,7 +99,7 @@ def __init__( self, *, host: str = "pubsub.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: Optional[str] = None, scopes: Optional[Sequence[str]] = None, channel: aio.Channel = None, @@ -114,7 +113,8 @@ def __init__( """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + 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 @@ -172,7 +172,6 @@ def __init__( # 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 @@ -355,7 +354,7 @@ def list_subscriptions( @property def delete_subscription( self, - ) -> Callable[[pubsub.DeleteSubscriptionRequest], Awaitable[empty.Empty]]: + ) -> 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 @@ -379,14 +378,14 @@ def delete_subscription( self._stubs["delete_subscription"] = self.grpc_channel.unary_unary( "/google.pubsub.v1.Subscriber/DeleteSubscription", request_serializer=pubsub.DeleteSubscriptionRequest.serialize, - response_deserializer=empty.Empty.FromString, + response_deserializer=empty_pb2.Empty.FromString, ) return self._stubs["delete_subscription"] @property def modify_ack_deadline( self, - ) -> Callable[[pubsub.ModifyAckDeadlineRequest], Awaitable[empty.Empty]]: + ) -> 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 @@ -410,14 +409,14 @@ def modify_ack_deadline( self._stubs["modify_ack_deadline"] = self.grpc_channel.unary_unary( "/google.pubsub.v1.Subscriber/ModifyAckDeadline", request_serializer=pubsub.ModifyAckDeadlineRequest.serialize, - response_deserializer=empty.Empty.FromString, + response_deserializer=empty_pb2.Empty.FromString, ) return self._stubs["modify_ack_deadline"] @property def acknowledge( self, - ) -> Callable[[pubsub.AcknowledgeRequest], Awaitable[empty.Empty]]: + ) -> 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 @@ -443,7 +442,7 @@ def acknowledge( self._stubs["acknowledge"] = self.grpc_channel.unary_unary( "/google.pubsub.v1.Subscriber/Acknowledge", request_serializer=pubsub.AcknowledgeRequest.serialize, - response_deserializer=empty.Empty.FromString, + response_deserializer=empty_pb2.Empty.FromString, ) return self._stubs["acknowledge"] @@ -511,7 +510,7 @@ def streaming_pull( @property def modify_push_config( self, - ) -> Callable[[pubsub.ModifyPushConfigRequest], Awaitable[empty.Empty]]: + ) -> 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. @@ -536,7 +535,7 @@ def modify_push_config( self._stubs["modify_push_config"] = self.grpc_channel.unary_unary( "/google.pubsub.v1.Subscriber/ModifyPushConfig", request_serializer=pubsub.ModifyPushConfigRequest.serialize, - response_deserializer=empty.Empty.FromString, + response_deserializer=empty_pb2.Empty.FromString, ) return self._stubs["modify_push_config"] @@ -683,7 +682,7 @@ def update_snapshot( @property def delete_snapshot( self, - ) -> Callable[[pubsub.DeleteSnapshotRequest], Awaitable[empty.Empty]]: + ) -> 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] @@ -711,7 +710,7 @@ def delete_snapshot( self._stubs["delete_snapshot"] = self.grpc_channel.unary_unary( "/google.pubsub.v1.Subscriber/DeleteSnapshot", request_serializer=pubsub.DeleteSnapshotRequest.serialize, - response_deserializer=empty.Empty.FromString, + response_deserializer=empty_pb2.Empty.FromString, ) return self._stubs["delete_snapshot"] @@ -750,7 +749,7 @@ def seek(self) -> Callable[[pubsub.SeekRequest], Awaitable[pubsub.SeekResponse]] @property def set_iam_policy( self, - ) -> Callable[[iam_policy.SetIamPolicyRequest], Awaitable[policy.Policy]]: + ) -> 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. @@ -767,15 +766,15 @@ def set_iam_policy( 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.SetIamPolicyRequest.SerializeToString, - response_deserializer=policy.Policy.FromString, + 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.GetIamPolicyRequest], Awaitable[policy.Policy]]: + ) -> 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 @@ -793,8 +792,8 @@ def get_iam_policy( 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.GetIamPolicyRequest.SerializeToString, - response_deserializer=policy.Policy.FromString, + request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, ) return self._stubs["get_iam_policy"] @@ -802,8 +801,8 @@ def get_iam_policy( def test_iam_permissions( self, ) -> Callable[ - [iam_policy.TestIamPermissionsRequest], - Awaitable[iam_policy.TestIamPermissionsResponse], + [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 @@ -822,8 +821,8 @@ def test_iam_permissions( 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.TestIamPermissionsRequest.SerializeToString, - response_deserializer=iam_policy.TestIamPermissionsResponse.FromString, + request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString, + response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString, ) return self._stubs["test_iam_permissions"] diff --git a/google/pubsub_v1/types/__init__.py b/google/pubsub_v1/types/__init__.py index 5203abfe7..ebc8b5399 100644 --- a/google/pubsub_v1/types/__init__.py +++ b/google/pubsub_v1/types/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from typing import Union from .pubsub import ( diff --git a/google/pubsub_v1/types/pubsub.py b/google/pubsub_v1/types/pubsub.py index 6fb73e8c9..c332309d0 100644 --- a/google/pubsub_v1/types/pubsub.py +++ b/google/pubsub_v1/types/pubsub.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,13 +13,11 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import proto # type: ignore - -from google.protobuf import duration_pb2 as duration # type: ignore -from google.protobuf import field_mask_pb2 as field_mask # type: ignore -from google.protobuf import timestamp_pb2 as timestamp # 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 @@ -91,12 +88,11 @@ class MessageStoragePolicy(proto.Message): not a valid configuration. """ - allowed_persistence_regions = proto.RepeatedField(proto.STRING, number=1) + 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 @@ -108,14 +104,12 @@ class SchemaSettings(proto.Message): The encoding of messages validated against ``schema``. """ - schema = proto.Field(proto.STRING, number=1) - + 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 @@ -149,19 +143,14 @@ class Topic(proto.Message): if it is set in any requests. """ - name = proto.Field(proto.STRING, number=1) - - labels = proto.MapField(proto.STRING, proto.STRING, number=2) - + 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) - + 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) + satisfies_pzs = proto.Field(proto.BOOL, number=7,) class PubsubMessage(proto.Message): @@ -207,32 +196,28 @@ class PubsubMessage(proto.Message): 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.Timestamp,) - - ordering_key = proto.Field(proto.STRING, number=5) + 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) + 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. @@ -246,13 +231,13 @@ class UpdateTopicRequest(proto.Message): """ topic = proto.Field(proto.MESSAGE, number=1, message="Topic",) - - update_mask = proto.Field(proto.MESSAGE, number=2, message=field_mask.FieldMask,) + 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 @@ -261,14 +246,12 @@ class PublishRequest(proto.Message): Required. The messages to publish. """ - topic = proto.Field(proto.STRING, number=1) - + 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 @@ -277,12 +260,11 @@ class PublishResponse(proto.Message): within the topic. """ - message_ids = proto.RepeatedField(proto.STRING, number=1) + 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. @@ -296,16 +278,13 @@ class ListTopicsRequest(proto.Message): 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) + 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. @@ -320,13 +299,11 @@ def raw_page(self): return self topics = proto.RepeatedField(proto.MESSAGE, number=1, message="Topic",) - - next_page_token = proto.Field(proto.STRING, number=2) + 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 @@ -342,16 +319,13 @@ class ListTopicSubscriptionsRequest(proto.Message): 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) + 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 @@ -366,14 +340,12 @@ class ListTopicSubscriptionsResponse(proto.Message): def raw_page(self): return self - subscriptions = proto.RepeatedField(proto.STRING, number=1) - - next_page_token = proto.Field(proto.STRING, number=2) + 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 @@ -387,16 +359,13 @@ class ListTopicSnapshotsRequest(proto.Message): 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) + 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 @@ -411,44 +380,40 @@ class ListTopicSnapshotsResponse(proto.Message): def raw_page(self): return self - snapshots = proto.RepeatedField(proto.STRING, number=1) - - next_page_token = proto.Field(proto.STRING, number=2) + 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) + 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) + 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 @@ -563,37 +528,25 @@ class Subscription(proto.Message): endpoint will not be made. """ - name = proto.Field(proto.STRING, number=1) - - topic = proto.Field(proto.STRING, number=2) - + 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) - + 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.Duration, + 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) - + 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) - + 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) + detached = proto.Field(proto.BOOL, number=15,) class RetryPolicy(proto.Message): @@ -623,9 +576,12 @@ class RetryPolicy(proto.Message): seconds. """ - minimum_backoff = proto.Field(proto.MESSAGE, number=1, message=duration.Duration,) - - maximum_backoff = proto.Field(proto.MESSAGE, number=2, message=duration.Duration,) + 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): @@ -667,9 +623,8 @@ class DeadLetterPolicy(proto.Message): 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) + dead_letter_topic = proto.Field(proto.STRING, number=1,) + max_delivery_attempts = proto.Field(proto.INT32, number=2,) class ExpirationPolicy(proto.Message): @@ -687,12 +642,11 @@ class ExpirationPolicy(proto.Message): associated resource never expires. """ - ttl = proto.Field(proto.MESSAGE, number=1, message=duration.Duration,) + ttl = proto.Field(proto.MESSAGE, number=1, message=duration_pb2.Duration,) class PushConfig(proto.Message): r"""Configuration for a push delivery endpoint. - Attributes: push_endpoint (str): A URL locating the endpoint to which messages should be @@ -759,14 +713,11 @@ class OidcToken(proto.Message): 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) + 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, ) @@ -774,7 +725,6 @@ class OidcToken(proto.Message): class ReceivedMessage(proto.Message): r"""A message and its corresponding acknowledgment ID. - Attributes: ack_id (str): This ID can be used to acknowledge the @@ -802,28 +752,24 @@ class ReceivedMessage(proto.Message): will be 0. """ - ack_id = proto.Field(proto.STRING, number=1) - + 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) + 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) + 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. @@ -834,13 +780,13 @@ class UpdateSubscriptionRequest(proto.Message): """ subscription = proto.Field(proto.MESSAGE, number=1, message="Subscription",) - - update_mask = proto.Field(proto.MESSAGE, number=2, message=field_mask.FieldMask,) + 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 @@ -854,16 +800,13 @@ class ListSubscriptionsRequest(proto.Message): 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) + 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. @@ -880,25 +823,22 @@ def raw_page(self): subscriptions = proto.RepeatedField( proto.MESSAGE, number=1, message="Subscription", ) - - next_page_token = proto.Field(proto.STRING, number=2) + 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) + 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 @@ -913,14 +853,12 @@ class ModifyPushConfigRequest(proto.Message): not called. """ - subscription = proto.Field(proto.STRING, number=1) - + 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 @@ -942,16 +880,13 @@ class PullRequest(proto.Message): 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) + 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 @@ -968,7 +903,6 @@ class PullResponse(proto.Message): class ModifyAckDeadlineRequest(proto.Message): r"""Request for the ModifyAckDeadline method. - Attributes: subscription (str): Required. The name of the subscription. Format is @@ -988,16 +922,13 @@ class ModifyAckDeadlineRequest(proto.Message): 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) + 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 @@ -1009,9 +940,8 @@ class AcknowledgeRequest(proto.Message): ``Pull`` response. Must not be empty. """ - subscription = proto.Field(proto.STRING, number=1) - - ack_ids = proto.RepeatedField(proto.STRING, number=2) + subscription = proto.Field(proto.STRING, number=1,) + ack_ids = proto.RepeatedField(proto.STRING, number=2,) class StreamingPullRequest(proto.Message): @@ -1098,21 +1028,14 @@ class StreamingPullRequest(proto.Message): ``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) + 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): @@ -1132,7 +1055,6 @@ class StreamingPullResponse(proto.Message): class CreateSnapshotRequest(proto.Message): r"""Request for the ``CreateSnapshot`` method. - Attributes: name (str): Required. User-provided name for this snapshot. If the name @@ -1158,16 +1080,13 @@ class CreateSnapshotRequest(proto.Message): 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) + 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. @@ -1178,8 +1097,9 @@ class UpdateSnapshotRequest(proto.Message): """ snapshot = proto.Field(proto.MESSAGE, number=1, message="Snapshot",) - - update_mask = proto.Field(proto.MESSAGE, number=2, message=field_mask.FieldMask,) + update_mask = proto.Field( + proto.MESSAGE, number=2, message=field_mask_pb2.FieldMask, + ) class Snapshot(proto.Message): @@ -1214,30 +1134,25 @@ class Snapshot(proto.Message): (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.Timestamp,) - - labels = proto.MapField(proto.STRING, proto.STRING, number=4) + 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) + 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 @@ -1251,16 +1166,13 @@ class ListSnapshotsRequest(proto.Message): 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) + 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. @@ -1275,25 +1187,22 @@ def raw_page(self): return self snapshots = proto.RepeatedField(proto.MESSAGE, number=1, message="Snapshot",) - - next_page_token = proto.Field(proto.STRING, number=2) + 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) + snapshot = proto.Field(proto.STRING, number=1,) class SeekRequest(proto.Message): r"""Request for the ``Seek`` method. - Attributes: subscription (str): Required. The subscription to affect. @@ -1317,17 +1226,15 @@ class SeekRequest(proto.Message): ``projects/{project}/snapshots/{snap}``. """ - subscription = proto.Field(proto.STRING, number=1) - + subscription = proto.Field(proto.STRING, number=1,) time = proto.Field( - proto.MESSAGE, number=2, oneof="target", message=timestamp.Timestamp, + proto.MESSAGE, number=2, oneof="target", message=timestamp_pb2.Timestamp, ) - - snapshot = proto.Field(proto.STRING, number=3, oneof="target") + snapshot = proto.Field(proto.STRING, number=3, oneof="target",) class SeekResponse(proto.Message): - r"""Response for the ``Seek`` method (this response is empty).""" + r"""Response for the ``Seek`` method (this response is empty). """ __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/pubsub_v1/types/schema.py b/google/pubsub_v1/types/schema.py index e4f71d132..d15837cbd 100644 --- a/google/pubsub_v1/types/schema.py +++ b/google/pubsub_v1/types/schema.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import proto # type: ignore @@ -55,7 +53,6 @@ class Encoding(proto.Enum): class Schema(proto.Message): r"""A schema resource. - Attributes: name (str): Required. Name of the schema. Format is @@ -74,16 +71,13 @@ class Type(proto.Enum): PROTOCOL_BUFFER = 1 AVRO = 2 - name = proto.Field(proto.STRING, number=1) - + name = proto.Field(proto.STRING, number=1,) type_ = proto.Field(proto.ENUM, number=2, enum=Type,) - - definition = proto.Field(proto.STRING, number=3) + 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 @@ -103,16 +97,13 @@ class CreateSchemaRequest(proto.Message): for resource name constraints. """ - parent = proto.Field(proto.STRING, number=1) - + parent = proto.Field(proto.STRING, number=1,) schema = proto.Field(proto.MESSAGE, number=2, message="Schema",) - - schema_id = proto.Field(proto.STRING, number=3) + 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 @@ -123,14 +114,12 @@ class GetSchemaRequest(proto.Message): ``definition``. Set to ``FULL`` to retrieve all fields. """ - name = proto.Field(proto.STRING, number=1) - + 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. @@ -148,18 +137,14 @@ class ListSchemasRequest(proto.Message): next page of data. """ - parent = proto.Field(proto.STRING, number=1) - + 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) + 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. @@ -174,25 +159,22 @@ def raw_page(self): return self schemas = proto.RepeatedField(proto.MESSAGE, number=1, message="Schema",) - - next_page_token = proto.Field(proto.STRING, number=2) + 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) + 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 @@ -201,18 +183,16 @@ class ValidateSchemaRequest(proto.Message): Required. The schema object to validate. """ - parent = proto.Field(proto.STRING, number=1) - + 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.""" + r"""Response for the ``ValidateSchema`` method. """ class ValidateMessageRequest(proto.Message): r"""Request for the ``ValidateMessage`` method. - Attributes: parent (str): Required. The name of the project in which to validate @@ -229,21 +209,17 @@ class ValidateMessageRequest(proto.Message): The encoding expected for messages """ - parent = proto.Field(proto.STRING, number=1) - - name = proto.Field(proto.STRING, number=2, oneof="schema_spec") - + 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) - + 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.""" + r"""Response for the ``ValidateMessage`` method. """ __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/scripts/fixup_pubsub_v1_keywords.py b/scripts/fixup_pubsub_v1_keywords.py index 071e3665f..7262e021e 100644 --- a/scripts/fixup_pubsub_v1_keywords.py +++ b/scripts/fixup_pubsub_v1_keywords.py @@ -1,6 +1,5 @@ #! /usr/bin/env python3 # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -15,7 +14,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import argparse import os import libcst as cst @@ -41,42 +39,40 @@ def partition( 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', ), - 'create_topic': ('name', 'labels', 'message_storage_policy', 'kms_key_name', 'schema_settings', 'satisfies_pzs', ), - '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', ), - + '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', ), + 'create_topic': ('name', 'labels', 'message_storage_policy', 'kms_key_name', 'schema_settings', 'satisfies_pzs', ), + '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: @@ -107,7 +103,7 @@ def leave_Call(self, original: cst.Call, updated: cst.Call) -> cst.CSTNode: value=cst.Dict([ cst.DictElement( cst.SimpleString("'{}'".format(name)), - cst.Element(value=arg.value) +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 diff --git a/synth.metadata b/synth.metadata index 02509864d..14ace7289 100644 --- a/synth.metadata +++ b/synth.metadata @@ -11,8 +11,8 @@ "git": { "name": "googleapis", "remote": "https://github.com/googleapis/googleapis.git", - "sha": "5a04154e7c7c0e98e0e4085f6e2c67bd5bff6ff8", - "internalRef": "371362703" + "sha": "83a7e1c8c2f7421ded45ed323eb1fda99ef5ea46", + "internalRef": "372197450" } } ], @@ -93,11 +93,13 @@ "docs/_templates/layout.html", "docs/conf.py", "docs/multiprocessing.rst", + "examples/feature_fragments", "google/cloud/pubsub_v1/proto/pubsub.proto", "google/cloud/pubsub_v1/proto/schema.proto", "google/pubsub/__init__.py", "google/pubsub/py.typed", "google/pubsub_v1/__init__.py", + "google/pubsub_v1/gapic_metadata.json", "google/pubsub_v1/py.typed", "google/pubsub_v1/services/__init__.py", "google/pubsub_v1/services/publisher/__init__.py", @@ -143,6 +145,9 @@ "scripts/readme-gen/templates/install_portaudio.tmpl.rst", "setup.cfg", "testing/.gitignore", + "tests/__init__.py", + "tests/unit/__init__.py", + "tests/unit/gapic/__init__.py", "tests/unit/gapic/pubsub_v1/__init__.py", "tests/unit/gapic/pubsub_v1/test_publisher.py", "tests/unit/gapic/pubsub_v1/test_schema_service.py", diff --git a/tests/__init__.py b/tests/__init__.py new file mode 100644 index 000000000..4de65971c --- /dev/null +++ b/tests/__init__.py @@ -0,0 +1,15 @@ +# -*- 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/tests/unit/__init__.py b/tests/unit/__init__.py index e69de29bb..4de65971c 100644 --- a/tests/unit/__init__.py +++ b/tests/unit/__init__.py @@ -0,0 +1,15 @@ +# -*- 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/tests/unit/gapic/__init__.py b/tests/unit/gapic/__init__.py new file mode 100644 index 000000000..4de65971c --- /dev/null +++ b/tests/unit/gapic/__init__.py @@ -0,0 +1,15 @@ +# -*- 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/tests/unit/gapic/pubsub_v1/__init__.py b/tests/unit/gapic/pubsub_v1/__init__.py index 42ffdf2bc..4de65971c 100644 --- a/tests/unit/gapic/pubsub_v1/__init__.py +++ b/tests/unit/gapic/pubsub_v1/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); diff --git a/tests/unit/gapic/pubsub_v1/test_publisher.py b/tests/unit/gapic/pubsub_v1/test_publisher.py index 5434ae944..61af19cc7 100644 --- a/tests/unit/gapic/pubsub_v1/test_publisher.py +++ b/tests/unit/gapic/pubsub_v1/test_publisher.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,9 +13,9 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import os import mock +import packaging.version import grpc from grpc.experimental import aio @@ -24,26 +23,52 @@ import pytest from proto.marshal.rules.dates import DurationRule, TimestampRule -from google import auth + from google.api_core import client_options -from google.api_core import exceptions +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.auth import credentials +from google.auth import credentials as ga_credentials from google.auth.exceptions import MutualTLSChannelError -from google.iam.v1 import iam_policy_pb2 as iam_policy # type: ignore -from google.iam.v1 import options_pb2 as options # type: ignore -from google.iam.v1 import policy_pb2 as policy # type: ignore +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 field_mask_pb2 as field_mask # type: ignore -from google.protobuf import timestamp_pb2 as timestamp # 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.services.publisher.transports.base import _API_CORE_VERSION +from google.pubsub_v1.services.publisher.transports.base import _GOOGLE_AUTH_VERSION from google.pubsub_v1.types import pubsub from google.pubsub_v1.types import schema +import google.auth + + +# TODO(busunkim): Once google-api-core >= 1.26.0 is required: +# - Delete all the api-core and auth "less than" test cases +# - Delete these pytest markers (Make the "greater than or equal to" tests the default). +requires_google_auth_lt_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), + reason="This test requires google-auth < 1.25.0", +) +requires_google_auth_gte_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) < packaging.version.parse("1.25.0"), + reason="This test requires google-auth >= 1.25.0", +) + +requires_api_core_lt_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) >= packaging.version.parse("1.26.0"), + reason="This test requires google-api-core < 1.26.0", +) + +requires_api_core_gte_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) < packaging.version.parse("1.26.0"), + reason="This test requires google-api-core >= 1.26.0", +) def client_cert_source_callback(): @@ -87,7 +112,7 @@ def test__get_default_mtls_endpoint(): @pytest.mark.parametrize("client_class", [PublisherClient, PublisherAsyncClient,]) def test_publisher_client_from_service_account_info(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_info" ) as factory: @@ -102,7 +127,7 @@ def test_publisher_client_from_service_account_info(client_class): @pytest.mark.parametrize("client_class", [PublisherClient, PublisherAsyncClient,]) def test_publisher_client_from_service_account_file(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_file" ) as factory: @@ -151,7 +176,7 @@ def test_publisher_client_get_transport_class(): 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=credentials.AnonymousCredentials()) + transport = transport_class(credentials=ga_credentials.AnonymousCredentials()) client = client_class(transport=transport) gtc.assert_not_called() @@ -433,7 +458,7 @@ def test_publisher_client_client_options_from_dict(): def test_create_topic(transport: str = "grpc", request_type=pubsub.Topic): client = PublisherClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -446,23 +471,17 @@ def test_create_topic(transport: str = "grpc", request_type=pubsub.Topic): 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 @@ -474,7 +493,7 @@ 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=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -482,7 +501,6 @@ def test_create_topic_empty_call(): client.create_topic() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == pubsub.Topic() @@ -491,7 +509,7 @@ async def test_create_topic_async( transport: str = "grpc_asyncio", request_type=pubsub.Topic ): client = PublisherAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -508,22 +526,17 @@ async def test_create_topic_async( 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 @@ -533,17 +546,17 @@ async def test_create_topic_async_from_dict(): def test_create_topic_field_headers(): - client = PublisherClient(credentials=credentials.AnonymousCredentials(),) + 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. @@ -558,17 +571,17 @@ def test_create_topic_field_headers(): @pytest.mark.asyncio async def test_create_topic_field_headers_async(): - client = PublisherAsyncClient(credentials=credentials.AnonymousCredentials(),) + 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. @@ -582,13 +595,12 @@ async def test_create_topic_field_headers_async(): def test_create_topic_flattened(): - client = PublisherClient(credentials=credentials.AnonymousCredentials(),) + 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",) @@ -597,12 +609,11 @@ def test_create_topic_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" def test_create_topic_flattened_error(): - client = PublisherClient(credentials=credentials.AnonymousCredentials(),) + client = PublisherClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -614,7 +625,7 @@ def test_create_topic_flattened_error(): @pytest.mark.asyncio async def test_create_topic_flattened_async(): - client = PublisherAsyncClient(credentials=credentials.AnonymousCredentials(),) + 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: @@ -630,13 +641,12 @@ async def test_create_topic_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" @pytest.mark.asyncio async def test_create_topic_flattened_error_async(): - client = PublisherAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = PublisherAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -648,7 +658,7 @@ async def test_create_topic_flattened_error_async(): def test_update_topic(transport: str = "grpc", request_type=pubsub.UpdateTopicRequest): client = PublisherClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -661,23 +671,17 @@ def test_update_topic(transport: str = "grpc", request_type=pubsub.UpdateTopicRe 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 @@ -689,7 +693,7 @@ 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=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -697,7 +701,6 @@ def test_update_topic_empty_call(): client.update_topic() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == pubsub.UpdateTopicRequest() @@ -706,7 +709,7 @@ async def test_update_topic_async( transport: str = "grpc_asyncio", request_type=pubsub.UpdateTopicRequest ): client = PublisherAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -723,22 +726,17 @@ async def test_update_topic_async( 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 @@ -748,17 +746,17 @@ async def test_update_topic_async_from_dict(): def test_update_topic_field_headers(): - client = PublisherClient(credentials=credentials.AnonymousCredentials(),) + 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. @@ -773,17 +771,17 @@ def test_update_topic_field_headers(): @pytest.mark.asyncio async def test_update_topic_field_headers_async(): - client = PublisherAsyncClient(credentials=credentials.AnonymousCredentials(),) + 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. @@ -798,7 +796,7 @@ async def test_update_topic_field_headers_async(): def test_publish(transport: str = "grpc", request_type=pubsub.PublishRequest): client = PublisherClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -809,19 +807,15 @@ def test_publish(transport: str = "grpc", request_type=pubsub.PublishRequest): 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"] @@ -833,7 +827,7 @@ 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=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -841,7 +835,6 @@ def test_publish_empty_call(): client.publish() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == pubsub.PublishRequest() @@ -850,7 +843,7 @@ async def test_publish_async( transport: str = "grpc_asyncio", request_type=pubsub.PublishRequest ): client = PublisherAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -863,18 +856,15 @@ async def test_publish_async( 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"] @@ -884,17 +874,17 @@ async def test_publish_async_from_dict(): def test_publish_field_headers(): - client = PublisherClient(credentials=credentials.AnonymousCredentials(),) + 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. @@ -909,11 +899,12 @@ def test_publish_field_headers(): @pytest.mark.asyncio async def test_publish_field_headers_async(): - client = PublisherAsyncClient(credentials=credentials.AnonymousCredentials(),) + 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. @@ -921,7 +912,6 @@ async def test_publish_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( pubsub.PublishResponse() ) - await client.publish(request) # Establish that the underlying gRPC stub method was called. @@ -935,13 +925,12 @@ async def test_publish_field_headers_async(): def test_publish_flattened(): - client = PublisherClient(credentials=credentials.AnonymousCredentials(),) + 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( @@ -952,14 +941,12 @@ def test_publish_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].topic == "topic_value" - assert args[0].messages == [pubsub.PubsubMessage(data=b"data_blob")] def test_publish_flattened_error(): - client = PublisherClient(credentials=credentials.AnonymousCredentials(),) + client = PublisherClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -973,7 +960,7 @@ def test_publish_flattened_error(): @pytest.mark.asyncio async def test_publish_flattened_async(): - client = PublisherAsyncClient(credentials=credentials.AnonymousCredentials(),) + 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: @@ -993,15 +980,13 @@ async def test_publish_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].topic == "topic_value" - assert args[0].messages == [pubsub.PubsubMessage(data=b"data_blob")] @pytest.mark.asyncio async def test_publish_flattened_error_async(): - client = PublisherAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = PublisherAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1015,7 +1000,7 @@ async def test_publish_flattened_error_async(): def test_get_topic(transport: str = "grpc", request_type=pubsub.GetTopicRequest): client = PublisherClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1028,23 +1013,17 @@ def test_get_topic(transport: str = "grpc", request_type=pubsub.GetTopicRequest) 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 @@ -1056,7 +1035,7 @@ 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=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1064,7 +1043,6 @@ def test_get_topic_empty_call(): client.get_topic() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == pubsub.GetTopicRequest() @@ -1073,7 +1051,7 @@ async def test_get_topic_async( transport: str = "grpc_asyncio", request_type=pubsub.GetTopicRequest ): client = PublisherAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1090,22 +1068,17 @@ async def test_get_topic_async( 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 @@ -1115,17 +1088,17 @@ async def test_get_topic_async_from_dict(): def test_get_topic_field_headers(): - client = PublisherClient(credentials=credentials.AnonymousCredentials(),) + 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. @@ -1140,17 +1113,17 @@ def test_get_topic_field_headers(): @pytest.mark.asyncio async def test_get_topic_field_headers_async(): - client = PublisherAsyncClient(credentials=credentials.AnonymousCredentials(),) + 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. @@ -1164,13 +1137,12 @@ async def test_get_topic_field_headers_async(): def test_get_topic_flattened(): - client = PublisherClient(credentials=credentials.AnonymousCredentials(),) + 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",) @@ -1179,12 +1151,11 @@ def test_get_topic_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].topic == "topic_value" def test_get_topic_flattened_error(): - client = PublisherClient(credentials=credentials.AnonymousCredentials(),) + client = PublisherClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1196,7 +1167,7 @@ def test_get_topic_flattened_error(): @pytest.mark.asyncio async def test_get_topic_flattened_async(): - client = PublisherAsyncClient(credentials=credentials.AnonymousCredentials(),) + 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: @@ -1212,13 +1183,12 @@ async def test_get_topic_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].topic == "topic_value" @pytest.mark.asyncio async def test_get_topic_flattened_error_async(): - client = PublisherAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = PublisherAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1230,7 +1200,7 @@ async def test_get_topic_flattened_error_async(): def test_list_topics(transport: str = "grpc", request_type=pubsub.ListTopicsRequest): client = PublisherClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1243,19 +1213,15 @@ def test_list_topics(transport: str = "grpc", request_type=pubsub.ListTopicsRequ 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" @@ -1267,7 +1233,7 @@ 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=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1275,7 +1241,6 @@ def test_list_topics_empty_call(): client.list_topics() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == pubsub.ListTopicsRequest() @@ -1284,7 +1249,7 @@ async def test_list_topics_async( transport: str = "grpc_asyncio", request_type=pubsub.ListTopicsRequest ): client = PublisherAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1297,18 +1262,15 @@ async def test_list_topics_async( 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" @@ -1318,17 +1280,17 @@ async def test_list_topics_async_from_dict(): def test_list_topics_field_headers(): - client = PublisherClient(credentials=credentials.AnonymousCredentials(),) + 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. @@ -1343,11 +1305,12 @@ def test_list_topics_field_headers(): @pytest.mark.asyncio async def test_list_topics_field_headers_async(): - client = PublisherAsyncClient(credentials=credentials.AnonymousCredentials(),) + 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. @@ -1355,7 +1318,6 @@ async def test_list_topics_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( pubsub.ListTopicsResponse() ) - await client.list_topics(request) # Establish that the underlying gRPC stub method was called. @@ -1369,13 +1331,12 @@ async def test_list_topics_field_headers_async(): def test_list_topics_flattened(): - client = PublisherClient(credentials=credentials.AnonymousCredentials(),) + 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",) @@ -1384,12 +1345,11 @@ def test_list_topics_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].project == "project_value" def test_list_topics_flattened_error(): - client = PublisherClient(credentials=credentials.AnonymousCredentials(),) + client = PublisherClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1401,7 +1361,7 @@ def test_list_topics_flattened_error(): @pytest.mark.asyncio async def test_list_topics_flattened_async(): - client = PublisherAsyncClient(credentials=credentials.AnonymousCredentials(),) + 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: @@ -1419,13 +1379,12 @@ async def test_list_topics_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].project == "project_value" @pytest.mark.asyncio async def test_list_topics_flattened_error_async(): - client = PublisherAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = PublisherAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1436,7 +1395,7 @@ async def test_list_topics_flattened_error_async(): def test_list_topics_pager(): - client = PublisherClient(credentials=credentials.AnonymousCredentials,) + 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: @@ -1466,7 +1425,7 @@ def test_list_topics_pager(): def test_list_topics_pages(): - client = PublisherClient(credentials=credentials.AnonymousCredentials,) + 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: @@ -1488,7 +1447,7 @@ def test_list_topics_pages(): @pytest.mark.asyncio async def test_list_topics_async_pager(): - client = PublisherAsyncClient(credentials=credentials.AnonymousCredentials,) + client = PublisherAsyncClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1517,7 +1476,7 @@ async def test_list_topics_async_pager(): @pytest.mark.asyncio async def test_list_topics_async_pages(): - client = PublisherAsyncClient(credentials=credentials.AnonymousCredentials,) + client = PublisherAsyncClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1545,7 +1504,7 @@ def test_list_topic_subscriptions( transport: str = "grpc", request_type=pubsub.ListTopicSubscriptionsRequest ): client = PublisherClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1561,21 +1520,16 @@ def test_list_topic_subscriptions( 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" @@ -1587,7 +1541,7 @@ 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=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1597,7 +1551,6 @@ def test_list_topic_subscriptions_empty_call(): client.list_topic_subscriptions() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == pubsub.ListTopicSubscriptionsRequest() @@ -1606,7 +1559,7 @@ async def test_list_topic_subscriptions_async( transport: str = "grpc_asyncio", request_type=pubsub.ListTopicSubscriptionsRequest ): client = PublisherAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1624,20 +1577,16 @@ async def test_list_topic_subscriptions_async( 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" @@ -1647,11 +1596,12 @@ async def test_list_topic_subscriptions_async_from_dict(): def test_list_topic_subscriptions_field_headers(): - client = PublisherClient(credentials=credentials.AnonymousCredentials(),) + 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. @@ -1659,7 +1609,6 @@ def test_list_topic_subscriptions_field_headers(): 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. @@ -1674,11 +1623,12 @@ def test_list_topic_subscriptions_field_headers(): @pytest.mark.asyncio async def test_list_topic_subscriptions_field_headers_async(): - client = PublisherAsyncClient(credentials=credentials.AnonymousCredentials(),) + 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. @@ -1688,7 +1638,6 @@ async def test_list_topic_subscriptions_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( pubsub.ListTopicSubscriptionsResponse() ) - await client.list_topic_subscriptions(request) # Establish that the underlying gRPC stub method was called. @@ -1702,7 +1651,7 @@ async def test_list_topic_subscriptions_field_headers_async(): def test_list_topic_subscriptions_flattened(): - client = PublisherClient(credentials=credentials.AnonymousCredentials(),) + client = PublisherClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1710,7 +1659,6 @@ def test_list_topic_subscriptions_flattened(): ) 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",) @@ -1719,12 +1667,11 @@ def test_list_topic_subscriptions_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].topic == "topic_value" def test_list_topic_subscriptions_flattened_error(): - client = PublisherClient(credentials=credentials.AnonymousCredentials(),) + client = PublisherClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1736,7 +1683,7 @@ def test_list_topic_subscriptions_flattened_error(): @pytest.mark.asyncio async def test_list_topic_subscriptions_flattened_async(): - client = PublisherAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = PublisherAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1756,13 +1703,12 @@ async def test_list_topic_subscriptions_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].topic == "topic_value" @pytest.mark.asyncio async def test_list_topic_subscriptions_flattened_error_async(): - client = PublisherAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = PublisherAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1773,7 +1719,7 @@ async def test_list_topic_subscriptions_flattened_error_async(): def test_list_topic_subscriptions_pager(): - client = PublisherClient(credentials=credentials.AnonymousCredentials,) + client = PublisherClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1808,7 +1754,7 @@ def test_list_topic_subscriptions_pager(): def test_list_topic_subscriptions_pages(): - client = PublisherClient(credentials=credentials.AnonymousCredentials,) + client = PublisherClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1835,7 +1781,7 @@ def test_list_topic_subscriptions_pages(): @pytest.mark.asyncio async def test_list_topic_subscriptions_async_pager(): - client = PublisherAsyncClient(credentials=credentials.AnonymousCredentials,) + client = PublisherAsyncClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1869,7 +1815,7 @@ async def test_list_topic_subscriptions_async_pager(): @pytest.mark.asyncio async def test_list_topic_subscriptions_async_pages(): - client = PublisherAsyncClient(credentials=credentials.AnonymousCredentials,) + client = PublisherAsyncClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1902,7 +1848,7 @@ def test_list_topic_snapshots( transport: str = "grpc", request_type=pubsub.ListTopicSnapshotsRequest ): client = PublisherClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1917,21 +1863,16 @@ def test_list_topic_snapshots( 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" @@ -1943,7 +1884,7 @@ 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=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1953,7 +1894,6 @@ def test_list_topic_snapshots_empty_call(): client.list_topic_snapshots() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == pubsub.ListTopicSnapshotsRequest() @@ -1962,7 +1902,7 @@ async def test_list_topic_snapshots_async( transport: str = "grpc_asyncio", request_type=pubsub.ListTopicSnapshotsRequest ): client = PublisherAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1979,20 +1919,16 @@ async def test_list_topic_snapshots_async( 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" @@ -2002,11 +1938,12 @@ async def test_list_topic_snapshots_async_from_dict(): def test_list_topic_snapshots_field_headers(): - client = PublisherClient(credentials=credentials.AnonymousCredentials(),) + 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. @@ -2014,7 +1951,6 @@ def test_list_topic_snapshots_field_headers(): 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. @@ -2029,11 +1965,12 @@ def test_list_topic_snapshots_field_headers(): @pytest.mark.asyncio async def test_list_topic_snapshots_field_headers_async(): - client = PublisherAsyncClient(credentials=credentials.AnonymousCredentials(),) + 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. @@ -2043,7 +1980,6 @@ async def test_list_topic_snapshots_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( pubsub.ListTopicSnapshotsResponse() ) - await client.list_topic_snapshots(request) # Establish that the underlying gRPC stub method was called. @@ -2057,7 +1993,7 @@ async def test_list_topic_snapshots_field_headers_async(): def test_list_topic_snapshots_flattened(): - client = PublisherClient(credentials=credentials.AnonymousCredentials(),) + client = PublisherClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -2065,7 +2001,6 @@ def test_list_topic_snapshots_flattened(): ) 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",) @@ -2074,12 +2009,11 @@ def test_list_topic_snapshots_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].topic == "topic_value" def test_list_topic_snapshots_flattened_error(): - client = PublisherClient(credentials=credentials.AnonymousCredentials(),) + client = PublisherClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -2091,7 +2025,7 @@ def test_list_topic_snapshots_flattened_error(): @pytest.mark.asyncio async def test_list_topic_snapshots_flattened_async(): - client = PublisherAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = PublisherAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -2111,13 +2045,12 @@ async def test_list_topic_snapshots_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].topic == "topic_value" @pytest.mark.asyncio async def test_list_topic_snapshots_flattened_error_async(): - client = PublisherAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = PublisherAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -2128,7 +2061,7 @@ async def test_list_topic_snapshots_flattened_error_async(): def test_list_topic_snapshots_pager(): - client = PublisherClient(credentials=credentials.AnonymousCredentials,) + client = PublisherClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -2161,7 +2094,7 @@ def test_list_topic_snapshots_pager(): def test_list_topic_snapshots_pages(): - client = PublisherClient(credentials=credentials.AnonymousCredentials,) + client = PublisherClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -2186,7 +2119,7 @@ def test_list_topic_snapshots_pages(): @pytest.mark.asyncio async def test_list_topic_snapshots_async_pager(): - client = PublisherAsyncClient(credentials=credentials.AnonymousCredentials,) + client = PublisherAsyncClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -2218,7 +2151,7 @@ async def test_list_topic_snapshots_async_pager(): @pytest.mark.asyncio async def test_list_topic_snapshots_async_pages(): - client = PublisherAsyncClient(credentials=credentials.AnonymousCredentials,) + client = PublisherAsyncClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -2247,7 +2180,7 @@ async def test_list_topic_snapshots_async_pages(): def test_delete_topic(transport: str = "grpc", request_type=pubsub.DeleteTopicRequest): client = PublisherClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -2258,13 +2191,11 @@ def test_delete_topic(transport: str = "grpc", request_type=pubsub.DeleteTopicRe 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. @@ -2279,7 +2210,7 @@ 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=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2287,7 +2218,6 @@ def test_delete_topic_empty_call(): client.delete_topic() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == pubsub.DeleteTopicRequest() @@ -2296,7 +2226,7 @@ async def test_delete_topic_async( transport: str = "grpc_asyncio", request_type=pubsub.DeleteTopicRequest ): client = PublisherAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -2307,13 +2237,11 @@ async def test_delete_topic_async( 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. @@ -2326,17 +2254,17 @@ async def test_delete_topic_async_from_dict(): def test_delete_topic_field_headers(): - client = PublisherClient(credentials=credentials.AnonymousCredentials(),) + 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. @@ -2351,17 +2279,17 @@ def test_delete_topic_field_headers(): @pytest.mark.asyncio async def test_delete_topic_field_headers_async(): - client = PublisherAsyncClient(credentials=credentials.AnonymousCredentials(),) + 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. @@ -2375,13 +2303,12 @@ async def test_delete_topic_field_headers_async(): def test_delete_topic_flattened(): - client = PublisherClient(credentials=credentials.AnonymousCredentials(),) + 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",) @@ -2390,12 +2317,11 @@ def test_delete_topic_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].topic == "topic_value" def test_delete_topic_flattened_error(): - client = PublisherClient(credentials=credentials.AnonymousCredentials(),) + client = PublisherClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -2407,7 +2333,7 @@ def test_delete_topic_flattened_error(): @pytest.mark.asyncio async def test_delete_topic_flattened_async(): - client = PublisherAsyncClient(credentials=credentials.AnonymousCredentials(),) + 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: @@ -2423,13 +2349,12 @@ async def test_delete_topic_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].topic == "topic_value" @pytest.mark.asyncio async def test_delete_topic_flattened_error_async(): - client = PublisherAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = PublisherAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -2443,7 +2368,7 @@ def test_detach_subscription( transport: str = "grpc", request_type=pubsub.DetachSubscriptionRequest ): client = PublisherClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -2456,17 +2381,14 @@ def test_detach_subscription( ) 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) @@ -2478,7 +2400,7 @@ 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=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2488,7 +2410,6 @@ def test_detach_subscription_empty_call(): client.detach_subscription() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == pubsub.DetachSubscriptionRequest() @@ -2497,7 +2418,7 @@ async def test_detach_subscription_async( transport: str = "grpc_asyncio", request_type=pubsub.DetachSubscriptionRequest ): client = PublisherAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -2512,13 +2433,11 @@ async def test_detach_subscription_async( 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. @@ -2531,11 +2450,12 @@ async def test_detach_subscription_async_from_dict(): def test_detach_subscription_field_headers(): - client = PublisherClient(credentials=credentials.AnonymousCredentials(),) + 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. @@ -2543,7 +2463,6 @@ def test_detach_subscription_field_headers(): 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. @@ -2560,11 +2479,12 @@ def test_detach_subscription_field_headers(): @pytest.mark.asyncio async def test_detach_subscription_field_headers_async(): - client = PublisherAsyncClient(credentials=credentials.AnonymousCredentials(),) + 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. @@ -2574,7 +2494,6 @@ async def test_detach_subscription_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( pubsub.DetachSubscriptionResponse() ) - await client.detach_subscription(request) # Establish that the underlying gRPC stub method was called. @@ -2592,16 +2511,16 @@ async def test_detach_subscription_field_headers_async(): def test_credentials_transport_error(): # It is an error to provide credentials and a transport instance. transport = transports.PublisherGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = PublisherClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # It is an error to provide a credentials file and a transport instance. transport = transports.PublisherGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = PublisherClient( @@ -2611,7 +2530,7 @@ def test_credentials_transport_error(): # It is an error to provide scopes and a transport instance. transport = transports.PublisherGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = PublisherClient( @@ -2622,7 +2541,7 @@ def test_credentials_transport_error(): def test_transport_instance(): # A client may be instantiated with a custom transport instance. transport = transports.PublisherGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) client = PublisherClient(transport=transport) assert client.transport is transport @@ -2631,13 +2550,13 @@ def test_transport_instance(): def test_transport_get_channel(): # A client may be instantiated with a custom transport instance. transport = transports.PublisherGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) channel = transport.grpc_channel assert channel transport = transports.PublisherGrpcAsyncIOTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) channel = transport.grpc_channel assert channel @@ -2649,23 +2568,23 @@ def test_transport_get_channel(): ) def test_transport_adc(transport_class): # Test default credentials are used if not provided. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + 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=credentials.AnonymousCredentials(),) + 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(exceptions.DuplicateCredentialArgs): + with pytest.raises(core_exceptions.DuplicateCredentialArgs): transport = transports.PublisherTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), credentials_file="credentials.json", ) @@ -2677,7 +2596,7 @@ def test_publisher_base_transport(): ) as Transport: Transport.return_value = None transport = transports.PublisherTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Every method on the transport should just blindly @@ -2701,15 +2620,40 @@ def test_publisher_base_transport(): getattr(transport, method)(request=object()) +@requires_google_auth_gte_1_25_0 def test_publisher_base_transport_with_credentials_file(): # Instantiate the base transport with a credentials file with mock.patch.object( - auth, "load_credentials_from_file" + 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", + ) + + +@requires_google_auth_lt_1_25_0 +def test_publisher_base_transport_with_credentials_file_old_google_auth(): + # 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 = (credentials.AnonymousCredentials(), None) + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.PublisherTransport( credentials_file="credentials.json", quota_project_id="octopus", ) @@ -2725,19 +2669,36 @@ def test_publisher_base_transport_with_credentials_file(): def test_publisher_base_transport_with_adc(): # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(auth, "default") as adc, mock.patch( + 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 = (credentials.AnonymousCredentials(), None) + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.PublisherTransport() adc.assert_called_once() +@requires_google_auth_gte_1_25_0 def test_publisher_auth_adc(): # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + 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, + ) + + +@requires_google_auth_lt_1_25_0 +def test_publisher_auth_adc_old_google_auth(): + # 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=( @@ -2748,14 +2709,38 @@ def test_publisher_auth_adc(): ) -def test_publisher_transport_auth_adc(): +@pytest.mark.parametrize( + "transport_class", + [transports.PublisherGrpcTransport, transports.PublisherGrpcAsyncIOTransport,], +) +@requires_google_auth_gte_1_25_0 +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(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) - transports.PublisherGrpcTransport( - host="squid.clam.whelk", quota_project_id="octopus" + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + adc.assert_called_once_with( + scopes=["1", "2"], + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/pubsub", + ), + quota_project_id="octopus", ) + + +@pytest.mark.parametrize( + "transport_class", + [transports.PublisherGrpcTransport, transports.PublisherGrpcAsyncIOTransport,], +) +@requires_google_auth_lt_1_25_0 +def test_publisher_transport_auth_adc_old_google_auth(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") adc.assert_called_once_with( scopes=( "https://www.googleapis.com/auth/cloud-platform", @@ -2765,12 +2750,126 @@ def test_publisher_transport_auth_adc(): ) +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.PublisherGrpcTransport, grpc_helpers), + (transports.PublisherGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_gte_1_26_0 +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), + ("grpc.keepalive_time_ms", 30000), + ], + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.PublisherGrpcTransport, grpc_helpers), + (transports.PublisherGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_publisher_transport_create_channel_old_api_core(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") + + create_channel.assert_called_with( + "pubsub.googleapis.com", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/pubsub", + ), + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ("grpc.keepalive_time_ms", 30000), + ], + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.PublisherGrpcTransport, grpc_helpers), + (transports.PublisherGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_publisher_transport_create_channel_user_scopes(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", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + scopes=["1", "2"], + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ("grpc.keepalive_time_ms", 30000), + ], + ) + + @pytest.mark.parametrize( "transport_class", [transports.PublisherGrpcTransport, transports.PublisherGrpcAsyncIOTransport], ) def test_publisher_grpc_transport_client_cert_source_for_mtls(transport_class): - cred = credentials.AnonymousCredentials() + cred = ga_credentials.AnonymousCredentials() # Check ssl_channel_credentials is used if provided. with mock.patch.object(transport_class, "create_channel") as mock_create_channel: @@ -2813,7 +2912,7 @@ def test_publisher_grpc_transport_client_cert_source_for_mtls(transport_class): def test_publisher_host_no_port(): client = PublisherClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="pubsub.googleapis.com" ), @@ -2823,7 +2922,7 @@ def test_publisher_host_no_port(): def test_publisher_host_with_port(): client = PublisherClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="pubsub.googleapis.com:8000" ), @@ -2874,9 +2973,9 @@ def test_publisher_transport_channel_mtls_with_client_cert_source(transport_clas mock_grpc_channel = mock.Mock() grpc_create_channel.return_value = mock_grpc_channel - cred = credentials.AnonymousCredentials() + cred = ga_credentials.AnonymousCredentials() with pytest.warns(DeprecationWarning): - with mock.patch.object(auth, "default") as adc: + with mock.patch.object(google.auth, "default") as adc: adc.return_value = (cred, None) transport = transport_class( host="squid.clam.whelk", @@ -2958,7 +3057,6 @@ def test_publisher_transport_channel_mtls_with_adc(transport_class): def test_schema_path(): project = "squid" schema = "clam" - expected = "projects/{project}/schemas/{schema}".format( project=project, schema=schema, ) @@ -2981,7 +3079,6 @@ def test_parse_schema_path(): def test_subscription_path(): project = "oyster" subscription = "nudibranch" - expected = "projects/{project}/subscriptions/{subscription}".format( project=project, subscription=subscription, ) @@ -3004,7 +3101,6 @@ def test_parse_subscription_path(): 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 @@ -3024,7 +3120,6 @@ def test_parse_topic_path(): def test_common_billing_account_path(): billing_account = "squid" - expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -3045,7 +3140,6 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): folder = "whelk" - expected = "folders/{folder}".format(folder=folder,) actual = PublisherClient.common_folder_path(folder) assert expected == actual @@ -3064,7 +3158,6 @@ def test_parse_common_folder_path(): def test_common_organization_path(): organization = "oyster" - expected = "organizations/{organization}".format(organization=organization,) actual = PublisherClient.common_organization_path(organization) assert expected == actual @@ -3083,7 +3176,6 @@ def test_parse_common_organization_path(): def test_common_project_path(): project = "cuttlefish" - expected = "projects/{project}".format(project=project,) actual = PublisherClient.common_project_path(project) assert expected == actual @@ -3103,7 +3195,6 @@ def test_parse_common_project_path(): def test_common_location_path(): project = "winkle" location = "nautilus" - expected = "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -3130,7 +3221,7 @@ def test_client_withDEFAULT_CLIENT_INFO(): transports.PublisherTransport, "_prep_wrapped_messages" ) as prep: client = PublisherClient( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) @@ -3139,24 +3230,24 @@ def test_client_withDEFAULT_CLIENT_INFO(): ) as prep: transport_class = PublisherClient.get_transport_class() transport = transport_class( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + 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=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional 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.SetIamPolicyRequest() + 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.Policy(version=774, etag=b"etag_blob",) + call.return_value = policy_pb2.Policy(version=774, etag=b"etag_blob",) response = client.set_iam_policy(request) @@ -3167,7 +3258,7 @@ def test_set_iam_policy(transport: str = "grpc"): assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, policy.Policy) + assert isinstance(response, policy_pb2.Policy) assert response.version == 774 @@ -3177,18 +3268,18 @@ def test_set_iam_policy(transport: str = "grpc"): @pytest.mark.asyncio async def test_set_iam_policy_async(transport: str = "grpc_asyncio"): client = PublisherAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional 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.SetIamPolicyRequest() + 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.Policy(version=774, etag=b"etag_blob",) + policy_pb2.Policy(version=774, etag=b"etag_blob",) ) response = await client.set_iam_policy(request) @@ -3200,7 +3291,7 @@ async def test_set_iam_policy_async(transport: str = "grpc_asyncio"): assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, policy.Policy) + assert isinstance(response, policy_pb2.Policy) assert response.version == 774 @@ -3208,16 +3299,16 @@ async def test_set_iam_policy_async(transport: str = "grpc_asyncio"): def test_set_iam_policy_field_headers(): - client = PublisherClient(credentials=credentials.AnonymousCredentials(),) + 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.SetIamPolicyRequest() + 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.Policy() + call.return_value = policy_pb2.Policy() client.set_iam_policy(request) @@ -3233,16 +3324,16 @@ def test_set_iam_policy_field_headers(): @pytest.mark.asyncio async def test_set_iam_policy_field_headers_async(): - client = PublisherAsyncClient(credentials=credentials.AnonymousCredentials(),) + 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.SetIamPolicyRequest() + 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.Policy()) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) await client.set_iam_policy(request) @@ -3257,16 +3348,16 @@ async def test_set_iam_policy_field_headers_async(): def test_set_iam_policy_from_dict(): - client = PublisherClient(credentials=credentials.AnonymousCredentials(),) + 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.Policy() + call.return_value = policy_pb2.Policy() response = client.set_iam_policy( request={ "resource": "resource_value", - "policy": policy.Policy(version=774), + "policy": policy_pb2.Policy(version=774), } ) call.assert_called() @@ -3274,16 +3365,16 @@ def test_set_iam_policy_from_dict(): @pytest.mark.asyncio async def test_set_iam_policy_from_dict_async(): - client = PublisherAsyncClient(credentials=credentials.AnonymousCredentials(),) + 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.Policy()) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) response = await client.set_iam_policy( request={ "resource": "resource_value", - "policy": policy.Policy(version=774), + "policy": policy_pb2.Policy(version=774), } ) call.assert_called() @@ -3291,17 +3382,17 @@ async def test_set_iam_policy_from_dict_async(): def test_get_iam_policy(transport: str = "grpc"): client = PublisherClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional 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.GetIamPolicyRequest() + 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.Policy(version=774, etag=b"etag_blob",) + call.return_value = policy_pb2.Policy(version=774, etag=b"etag_blob",) response = client.get_iam_policy(request) @@ -3312,7 +3403,7 @@ def test_get_iam_policy(transport: str = "grpc"): assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, policy.Policy) + assert isinstance(response, policy_pb2.Policy) assert response.version == 774 @@ -3322,18 +3413,18 @@ def test_get_iam_policy(transport: str = "grpc"): @pytest.mark.asyncio async def test_get_iam_policy_async(transport: str = "grpc_asyncio"): client = PublisherAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional 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.GetIamPolicyRequest() + 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.Policy(version=774, etag=b"etag_blob",) + policy_pb2.Policy(version=774, etag=b"etag_blob",) ) response = await client.get_iam_policy(request) @@ -3345,7 +3436,7 @@ async def test_get_iam_policy_async(transport: str = "grpc_asyncio"): assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, policy.Policy) + assert isinstance(response, policy_pb2.Policy) assert response.version == 774 @@ -3353,16 +3444,16 @@ async def test_get_iam_policy_async(transport: str = "grpc_asyncio"): def test_get_iam_policy_field_headers(): - client = PublisherClient(credentials=credentials.AnonymousCredentials(),) + 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.GetIamPolicyRequest() + 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.Policy() + call.return_value = policy_pb2.Policy() client.get_iam_policy(request) @@ -3378,16 +3469,16 @@ def test_get_iam_policy_field_headers(): @pytest.mark.asyncio async def test_get_iam_policy_field_headers_async(): - client = PublisherAsyncClient(credentials=credentials.AnonymousCredentials(),) + 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.GetIamPolicyRequest() + 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.Policy()) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) await client.get_iam_policy(request) @@ -3402,16 +3493,16 @@ async def test_get_iam_policy_field_headers_async(): def test_get_iam_policy_from_dict(): - client = PublisherClient(credentials=credentials.AnonymousCredentials(),) + 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.Policy() + call.return_value = policy_pb2.Policy() response = client.get_iam_policy( request={ "resource": "resource_value", - "options": options.GetPolicyOptions(requested_policy_version=2598), + "options": options_pb2.GetPolicyOptions(requested_policy_version=2598), } ) call.assert_called() @@ -3419,16 +3510,16 @@ def test_get_iam_policy_from_dict(): @pytest.mark.asyncio async def test_get_iam_policy_from_dict_async(): - client = PublisherAsyncClient(credentials=credentials.AnonymousCredentials(),) + 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.Policy()) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) response = await client.get_iam_policy( request={ "resource": "resource_value", - "options": options.GetPolicyOptions(requested_policy_version=2598), + "options": options_pb2.GetPolicyOptions(requested_policy_version=2598), } ) call.assert_called() @@ -3436,19 +3527,19 @@ async def test_get_iam_policy_from_dict_async(): def test_test_iam_permissions(transport: str = "grpc"): client = PublisherClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional 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.TestIamPermissionsRequest() + 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.TestIamPermissionsResponse( + call.return_value = iam_policy_pb2.TestIamPermissionsResponse( permissions=["permissions_value"], ) @@ -3461,7 +3552,7 @@ def test_test_iam_permissions(transport: str = "grpc"): assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, iam_policy.TestIamPermissionsResponse) + assert isinstance(response, iam_policy_pb2.TestIamPermissionsResponse) assert response.permissions == ["permissions_value"] @@ -3469,12 +3560,12 @@ def test_test_iam_permissions(transport: str = "grpc"): @pytest.mark.asyncio async def test_test_iam_permissions_async(transport: str = "grpc_asyncio"): client = PublisherAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional 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.TestIamPermissionsRequest() + request = iam_policy_pb2.TestIamPermissionsRequest() # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -3482,7 +3573,9 @@ async def test_test_iam_permissions_async(transport: str = "grpc_asyncio"): ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - iam_policy.TestIamPermissionsResponse(permissions=["permissions_value"],) + iam_policy_pb2.TestIamPermissionsResponse( + permissions=["permissions_value"], + ) ) response = await client.test_iam_permissions(request) @@ -3494,24 +3587,24 @@ async def test_test_iam_permissions_async(transport: str = "grpc_asyncio"): assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, iam_policy.TestIamPermissionsResponse) + assert isinstance(response, iam_policy_pb2.TestIamPermissionsResponse) assert response.permissions == ["permissions_value"] def test_test_iam_permissions_field_headers(): - client = PublisherClient(credentials=credentials.AnonymousCredentials(),) + 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.TestIamPermissionsRequest() + 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.TestIamPermissionsResponse() + call.return_value = iam_policy_pb2.TestIamPermissionsResponse() client.test_iam_permissions(request) @@ -3527,11 +3620,11 @@ def test_test_iam_permissions_field_headers(): @pytest.mark.asyncio async def test_test_iam_permissions_field_headers_async(): - client = PublisherAsyncClient(credentials=credentials.AnonymousCredentials(),) + 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.TestIamPermissionsRequest() + request = iam_policy_pb2.TestIamPermissionsRequest() request.resource = "resource/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -3539,7 +3632,7 @@ async def test_test_iam_permissions_field_headers_async(): type(client.transport.test_iam_permissions), "__call__" ) as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - iam_policy.TestIamPermissionsResponse() + iam_policy_pb2.TestIamPermissionsResponse() ) await client.test_iam_permissions(request) @@ -3555,13 +3648,13 @@ async def test_test_iam_permissions_field_headers_async(): def test_test_iam_permissions_from_dict(): - client = PublisherClient(credentials=credentials.AnonymousCredentials(),) + 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.TestIamPermissionsResponse() + call.return_value = iam_policy_pb2.TestIamPermissionsResponse() response = client.test_iam_permissions( request={ @@ -3574,14 +3667,14 @@ def test_test_iam_permissions_from_dict(): @pytest.mark.asyncio async def test_test_iam_permissions_from_dict_async(): - client = PublisherAsyncClient(credentials=credentials.AnonymousCredentials(),) + 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.TestIamPermissionsResponse() + iam_policy_pb2.TestIamPermissionsResponse() ) response = await client.test_iam_permissions( diff --git a/tests/unit/gapic/pubsub_v1/test_schema_service.py b/tests/unit/gapic/pubsub_v1/test_schema_service.py index 62a3aa730..ab0f64f47 100644 --- a/tests/unit/gapic/pubsub_v1/test_schema_service.py +++ b/tests/unit/gapic/pubsub_v1/test_schema_service.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,9 +13,9 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import os import mock +import packaging.version import grpc from grpc.experimental import aio @@ -24,24 +23,52 @@ import pytest from proto.marshal.rules.dates import DurationRule, TimestampRule -from google import auth + from google.api_core import client_options -from google.api_core import exceptions +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.auth import credentials +from google.auth import credentials as ga_credentials from google.auth.exceptions import MutualTLSChannelError -from google.iam.v1 import iam_policy_pb2 as iam_policy # type: ignore -from google.iam.v1 import options_pb2 as options # type: ignore -from google.iam.v1 import policy_pb2 as policy # type: ignore +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.services.schema_service.transports.base import _API_CORE_VERSION +from google.pubsub_v1.services.schema_service.transports.base import ( + _GOOGLE_AUTH_VERSION, +) from google.pubsub_v1.types import schema from google.pubsub_v1.types import schema as gp_schema +import google.auth + + +# TODO(busunkim): Once google-api-core >= 1.26.0 is required: +# - Delete all the api-core and auth "less than" test cases +# - Delete these pytest markers (Make the "greater than or equal to" tests the default). +requires_google_auth_lt_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), + reason="This test requires google-auth < 1.25.0", +) +requires_google_auth_gte_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) < packaging.version.parse("1.25.0"), + reason="This test requires google-auth >= 1.25.0", +) + +requires_api_core_lt_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) >= packaging.version.parse("1.26.0"), + reason="This test requires google-api-core < 1.26.0", +) + +requires_api_core_gte_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) < packaging.version.parse("1.26.0"), + reason="This test requires google-api-core >= 1.26.0", +) def client_cert_source_callback(): @@ -92,7 +119,7 @@ def test__get_default_mtls_endpoint(): "client_class", [SchemaServiceClient, SchemaServiceAsyncClient,] ) def test_schema_service_client_from_service_account_info(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_info" ) as factory: @@ -109,7 +136,7 @@ def test_schema_service_client_from_service_account_info(client_class): "client_class", [SchemaServiceClient, SchemaServiceAsyncClient,] ) def test_schema_service_client_from_service_account_file(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_file" ) as factory: @@ -162,7 +189,7 @@ def test_schema_service_client_client_options( ): # 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=credentials.AnonymousCredentials()) + transport = transport_class(credentials=ga_credentials.AnonymousCredentials()) client = client_class(transport=transport) gtc.assert_not_called() @@ -450,7 +477,7 @@ def test_create_schema( transport: str = "grpc", request_type=gp_schema.CreateSchemaRequest ): client = SchemaServiceClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -465,23 +492,17 @@ def test_create_schema( 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" @@ -493,7 +514,7 @@ 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=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -501,7 +522,6 @@ def test_create_schema_empty_call(): client.create_schema() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == gp_schema.CreateSchemaRequest() @@ -510,7 +530,7 @@ async def test_create_schema_async( transport: str = "grpc_asyncio", request_type=gp_schema.CreateSchemaRequest ): client = SchemaServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -527,22 +547,17 @@ async def test_create_schema_async( 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" @@ -552,17 +567,17 @@ async def test_create_schema_async_from_dict(): def test_create_schema_field_headers(): - client = SchemaServiceClient(credentials=credentials.AnonymousCredentials(),) + 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. @@ -577,17 +592,19 @@ def test_create_schema_field_headers(): @pytest.mark.asyncio async def test_create_schema_field_headers_async(): - client = SchemaServiceAsyncClient(credentials=credentials.AnonymousCredentials(),) + 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. @@ -601,13 +618,12 @@ async def test_create_schema_field_headers_async(): def test_create_schema_flattened(): - client = SchemaServiceClient(credentials=credentials.AnonymousCredentials(),) + 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( @@ -620,16 +636,13 @@ def test_create_schema_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" - assert args[0].schema == gp_schema.Schema(name="name_value") - assert args[0].schema_id == "schema_id_value" def test_create_schema_flattened_error(): - client = SchemaServiceClient(credentials=credentials.AnonymousCredentials(),) + client = SchemaServiceClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -644,7 +657,9 @@ def test_create_schema_flattened_error(): @pytest.mark.asyncio async def test_create_schema_flattened_async(): - client = SchemaServiceAsyncClient(credentials=credentials.AnonymousCredentials(),) + 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: @@ -664,17 +679,16 @@ async def test_create_schema_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" - assert args[0].schema == gp_schema.Schema(name="name_value") - assert args[0].schema_id == "schema_id_value" @pytest.mark.asyncio async def test_create_schema_flattened_error_async(): - client = SchemaServiceAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = SchemaServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -689,7 +703,7 @@ async def test_create_schema_flattened_error_async(): def test_get_schema(transport: str = "grpc", request_type=schema.GetSchemaRequest): client = SchemaServiceClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -704,23 +718,17 @@ def test_get_schema(transport: str = "grpc", request_type=schema.GetSchemaReques 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" @@ -732,7 +740,7 @@ 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=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -740,7 +748,6 @@ def test_get_schema_empty_call(): client.get_schema() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == schema.GetSchemaRequest() @@ -749,7 +756,7 @@ async def test_get_schema_async( transport: str = "grpc_asyncio", request_type=schema.GetSchemaRequest ): client = SchemaServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -766,22 +773,17 @@ async def test_get_schema_async( 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" @@ -791,17 +793,17 @@ async def test_get_schema_async_from_dict(): def test_get_schema_field_headers(): - client = SchemaServiceClient(credentials=credentials.AnonymousCredentials(),) + 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. @@ -816,17 +818,19 @@ def test_get_schema_field_headers(): @pytest.mark.asyncio async def test_get_schema_field_headers_async(): - client = SchemaServiceAsyncClient(credentials=credentials.AnonymousCredentials(),) + 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. @@ -840,13 +844,12 @@ async def test_get_schema_field_headers_async(): def test_get_schema_flattened(): - client = SchemaServiceClient(credentials=credentials.AnonymousCredentials(),) + 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",) @@ -855,12 +858,11 @@ def test_get_schema_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" def test_get_schema_flattened_error(): - client = SchemaServiceClient(credentials=credentials.AnonymousCredentials(),) + client = SchemaServiceClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -872,7 +874,9 @@ def test_get_schema_flattened_error(): @pytest.mark.asyncio async def test_get_schema_flattened_async(): - client = SchemaServiceAsyncClient(credentials=credentials.AnonymousCredentials(),) + 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: @@ -888,13 +892,14 @@ async def test_get_schema_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" @pytest.mark.asyncio async def test_get_schema_flattened_error_async(): - client = SchemaServiceAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = SchemaServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -906,7 +911,7 @@ async def test_get_schema_flattened_error_async(): def test_list_schemas(transport: str = "grpc", request_type=schema.ListSchemasRequest): client = SchemaServiceClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -919,19 +924,15 @@ def test_list_schemas(transport: str = "grpc", request_type=schema.ListSchemasRe 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" @@ -943,7 +944,7 @@ 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=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -951,7 +952,6 @@ def test_list_schemas_empty_call(): client.list_schemas() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == schema.ListSchemasRequest() @@ -960,7 +960,7 @@ async def test_list_schemas_async( transport: str = "grpc_asyncio", request_type=schema.ListSchemasRequest ): client = SchemaServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -973,18 +973,15 @@ async def test_list_schemas_async( 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" @@ -994,17 +991,17 @@ async def test_list_schemas_async_from_dict(): def test_list_schemas_field_headers(): - client = SchemaServiceClient(credentials=credentials.AnonymousCredentials(),) + 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. @@ -1019,11 +1016,14 @@ def test_list_schemas_field_headers(): @pytest.mark.asyncio async def test_list_schemas_field_headers_async(): - client = SchemaServiceAsyncClient(credentials=credentials.AnonymousCredentials(),) + 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. @@ -1031,7 +1031,6 @@ async def test_list_schemas_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( schema.ListSchemasResponse() ) - await client.list_schemas(request) # Establish that the underlying gRPC stub method was called. @@ -1045,13 +1044,12 @@ async def test_list_schemas_field_headers_async(): def test_list_schemas_flattened(): - client = SchemaServiceClient(credentials=credentials.AnonymousCredentials(),) + 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",) @@ -1060,12 +1058,11 @@ def test_list_schemas_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" def test_list_schemas_flattened_error(): - client = SchemaServiceClient(credentials=credentials.AnonymousCredentials(),) + client = SchemaServiceClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1077,7 +1074,9 @@ def test_list_schemas_flattened_error(): @pytest.mark.asyncio async def test_list_schemas_flattened_async(): - client = SchemaServiceAsyncClient(credentials=credentials.AnonymousCredentials(),) + 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: @@ -1095,13 +1094,14 @@ async def test_list_schemas_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" @pytest.mark.asyncio async def test_list_schemas_flattened_error_async(): - client = SchemaServiceAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = SchemaServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1112,7 +1112,7 @@ async def test_list_schemas_flattened_error_async(): def test_list_schemas_pager(): - client = SchemaServiceClient(credentials=credentials.AnonymousCredentials,) + 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: @@ -1144,7 +1144,7 @@ def test_list_schemas_pager(): def test_list_schemas_pages(): - client = SchemaServiceClient(credentials=credentials.AnonymousCredentials,) + 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: @@ -1168,7 +1168,7 @@ def test_list_schemas_pages(): @pytest.mark.asyncio async def test_list_schemas_async_pager(): - client = SchemaServiceAsyncClient(credentials=credentials.AnonymousCredentials,) + client = SchemaServiceAsyncClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1199,7 +1199,7 @@ async def test_list_schemas_async_pager(): @pytest.mark.asyncio async def test_list_schemas_async_pages(): - client = SchemaServiceAsyncClient(credentials=credentials.AnonymousCredentials,) + client = SchemaServiceAsyncClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1229,7 +1229,7 @@ def test_delete_schema( transport: str = "grpc", request_type=schema.DeleteSchemaRequest ): client = SchemaServiceClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1240,13 +1240,11 @@ def test_delete_schema( 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. @@ -1261,7 +1259,7 @@ 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=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1269,7 +1267,6 @@ def test_delete_schema_empty_call(): client.delete_schema() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == schema.DeleteSchemaRequest() @@ -1278,7 +1275,7 @@ async def test_delete_schema_async( transport: str = "grpc_asyncio", request_type=schema.DeleteSchemaRequest ): client = SchemaServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1289,13 +1286,11 @@ async def test_delete_schema_async( 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. @@ -1308,17 +1303,17 @@ async def test_delete_schema_async_from_dict(): def test_delete_schema_field_headers(): - client = SchemaServiceClient(credentials=credentials.AnonymousCredentials(),) + 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. @@ -1333,17 +1328,19 @@ def test_delete_schema_field_headers(): @pytest.mark.asyncio async def test_delete_schema_field_headers_async(): - client = SchemaServiceAsyncClient(credentials=credentials.AnonymousCredentials(),) + 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. @@ -1357,13 +1354,12 @@ async def test_delete_schema_field_headers_async(): def test_delete_schema_flattened(): - client = SchemaServiceClient(credentials=credentials.AnonymousCredentials(),) + 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",) @@ -1372,12 +1368,11 @@ def test_delete_schema_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" def test_delete_schema_flattened_error(): - client = SchemaServiceClient(credentials=credentials.AnonymousCredentials(),) + client = SchemaServiceClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1389,7 +1384,9 @@ def test_delete_schema_flattened_error(): @pytest.mark.asyncio async def test_delete_schema_flattened_async(): - client = SchemaServiceAsyncClient(credentials=credentials.AnonymousCredentials(),) + 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: @@ -1405,13 +1402,14 @@ async def test_delete_schema_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" @pytest.mark.asyncio async def test_delete_schema_flattened_error_async(): - client = SchemaServiceAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = SchemaServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1425,7 +1423,7 @@ def test_validate_schema( transport: str = "grpc", request_type=gp_schema.ValidateSchemaRequest ): client = SchemaServiceClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1436,17 +1434,14 @@ def test_validate_schema( 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) @@ -1458,7 +1453,7 @@ 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=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1466,7 +1461,6 @@ def test_validate_schema_empty_call(): client.validate_schema() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == gp_schema.ValidateSchemaRequest() @@ -1475,7 +1469,7 @@ async def test_validate_schema_async( transport: str = "grpc_asyncio", request_type=gp_schema.ValidateSchemaRequest ): client = SchemaServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1488,13 +1482,11 @@ async def test_validate_schema_async( 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. @@ -1507,17 +1499,17 @@ async def test_validate_schema_async_from_dict(): def test_validate_schema_field_headers(): - client = SchemaServiceClient(credentials=credentials.AnonymousCredentials(),) + 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. @@ -1532,11 +1524,14 @@ def test_validate_schema_field_headers(): @pytest.mark.asyncio async def test_validate_schema_field_headers_async(): - client = SchemaServiceAsyncClient(credentials=credentials.AnonymousCredentials(),) + 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. @@ -1544,7 +1539,6 @@ async def test_validate_schema_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( gp_schema.ValidateSchemaResponse() ) - await client.validate_schema(request) # Establish that the underlying gRPC stub method was called. @@ -1558,13 +1552,12 @@ async def test_validate_schema_field_headers_async(): def test_validate_schema_flattened(): - client = SchemaServiceClient(credentials=credentials.AnonymousCredentials(),) + 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( @@ -1575,14 +1568,12 @@ def test_validate_schema_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" - assert args[0].schema == gp_schema.Schema(name="name_value") def test_validate_schema_flattened_error(): - client = SchemaServiceClient(credentials=credentials.AnonymousCredentials(),) + client = SchemaServiceClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1596,7 +1587,9 @@ def test_validate_schema_flattened_error(): @pytest.mark.asyncio async def test_validate_schema_flattened_async(): - client = SchemaServiceAsyncClient(credentials=credentials.AnonymousCredentials(),) + 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: @@ -1616,15 +1609,15 @@ async def test_validate_schema_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" - assert args[0].schema == gp_schema.Schema(name="name_value") @pytest.mark.asyncio async def test_validate_schema_flattened_error_async(): - client = SchemaServiceAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = SchemaServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1640,7 +1633,7 @@ def test_validate_message( transport: str = "grpc", request_type=schema.ValidateMessageRequest ): client = SchemaServiceClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1651,17 +1644,14 @@ def test_validate_message( 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) @@ -1673,7 +1663,7 @@ 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=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1681,7 +1671,6 @@ def test_validate_message_empty_call(): client.validate_message() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == schema.ValidateMessageRequest() @@ -1690,7 +1679,7 @@ async def test_validate_message_async( transport: str = "grpc_asyncio", request_type=schema.ValidateMessageRequest ): client = SchemaServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1703,13 +1692,11 @@ async def test_validate_message_async( 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. @@ -1722,17 +1709,17 @@ async def test_validate_message_async_from_dict(): def test_validate_message_field_headers(): - client = SchemaServiceClient(credentials=credentials.AnonymousCredentials(),) + 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. @@ -1747,11 +1734,14 @@ def test_validate_message_field_headers(): @pytest.mark.asyncio async def test_validate_message_field_headers_async(): - client = SchemaServiceAsyncClient(credentials=credentials.AnonymousCredentials(),) + 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. @@ -1759,7 +1749,6 @@ async def test_validate_message_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( schema.ValidateMessageResponse() ) - await client.validate_message(request) # Establish that the underlying gRPC stub method was called. @@ -1775,16 +1764,16 @@ async def test_validate_message_field_headers_async(): def test_credentials_transport_error(): # It is an error to provide credentials and a transport instance. transport = transports.SchemaServiceGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = SchemaServiceClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # It is an error to provide a credentials file and a transport instance. transport = transports.SchemaServiceGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = SchemaServiceClient( @@ -1794,7 +1783,7 @@ def test_credentials_transport_error(): # It is an error to provide scopes and a transport instance. transport = transports.SchemaServiceGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = SchemaServiceClient( @@ -1805,7 +1794,7 @@ def test_credentials_transport_error(): def test_transport_instance(): # A client may be instantiated with a custom transport instance. transport = transports.SchemaServiceGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) client = SchemaServiceClient(transport=transport) assert client.transport is transport @@ -1814,13 +1803,13 @@ def test_transport_instance(): def test_transport_get_channel(): # A client may be instantiated with a custom transport instance. transport = transports.SchemaServiceGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) channel = transport.grpc_channel assert channel transport = transports.SchemaServiceGrpcAsyncIOTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) channel = transport.grpc_channel assert channel @@ -1835,23 +1824,23 @@ def test_transport_get_channel(): ) def test_transport_adc(transport_class): # Test default credentials are used if not provided. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + 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=credentials.AnonymousCredentials(),) + 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(exceptions.DuplicateCredentialArgs): + with pytest.raises(core_exceptions.DuplicateCredentialArgs): transport = transports.SchemaServiceTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), credentials_file="credentials.json", ) @@ -1863,7 +1852,7 @@ def test_schema_service_base_transport(): ) as Transport: Transport.return_value = None transport = transports.SchemaServiceTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Every method on the transport should just blindly @@ -1884,15 +1873,40 @@ def test_schema_service_base_transport(): getattr(transport, method)(request=object()) +@requires_google_auth_gte_1_25_0 def test_schema_service_base_transport_with_credentials_file(): # Instantiate the base transport with a credentials file with mock.patch.object( - auth, "load_credentials_from_file" + 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", + ) + + +@requires_google_auth_lt_1_25_0 +def test_schema_service_base_transport_with_credentials_file_old_google_auth(): + # 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 = (credentials.AnonymousCredentials(), None) + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.SchemaServiceTransport( credentials_file="credentials.json", quota_project_id="octopus", ) @@ -1908,19 +1922,36 @@ def test_schema_service_base_transport_with_credentials_file(): 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(auth, "default") as adc, mock.patch( + 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 = (credentials.AnonymousCredentials(), None) + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.SchemaServiceTransport() adc.assert_called_once() +@requires_google_auth_gte_1_25_0 def test_schema_service_auth_adc(): # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + 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, + ) + + +@requires_google_auth_lt_1_25_0 +def test_schema_service_auth_adc_old_google_auth(): + # 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=( @@ -1931,14 +1962,44 @@ def test_schema_service_auth_adc(): ) -def test_schema_service_transport_auth_adc(): +@pytest.mark.parametrize( + "transport_class", + [ + transports.SchemaServiceGrpcTransport, + transports.SchemaServiceGrpcAsyncIOTransport, + ], +) +@requires_google_auth_gte_1_25_0 +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(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) - transports.SchemaServiceGrpcTransport( - host="squid.clam.whelk", quota_project_id="octopus" + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + adc.assert_called_once_with( + scopes=["1", "2"], + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/pubsub", + ), + quota_project_id="octopus", ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.SchemaServiceGrpcTransport, + transports.SchemaServiceGrpcAsyncIOTransport, + ], +) +@requires_google_auth_lt_1_25_0 +def test_schema_service_transport_auth_adc_old_google_auth(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") adc.assert_called_once_with( scopes=( "https://www.googleapis.com/auth/cloud-platform", @@ -1948,6 +2009,124 @@ def test_schema_service_transport_auth_adc(): ) +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.SchemaServiceGrpcTransport, grpc_helpers), + (transports.SchemaServiceGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_gte_1_26_0 +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), + ("grpc.keepalive_time_ms", 30000), + ], + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.SchemaServiceGrpcTransport, grpc_helpers), + (transports.SchemaServiceGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_schema_service_transport_create_channel_old_api_core( + 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") + + create_channel.assert_called_with( + "pubsub.googleapis.com", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/pubsub", + ), + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ("grpc.keepalive_time_ms", 30000), + ], + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.SchemaServiceGrpcTransport, grpc_helpers), + (transports.SchemaServiceGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_schema_service_transport_create_channel_user_scopes( + 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", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + scopes=["1", "2"], + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ("grpc.keepalive_time_ms", 30000), + ], + ) + + @pytest.mark.parametrize( "transport_class", [ @@ -1956,7 +2135,7 @@ def test_schema_service_transport_auth_adc(): ], ) def test_schema_service_grpc_transport_client_cert_source_for_mtls(transport_class): - cred = credentials.AnonymousCredentials() + cred = ga_credentials.AnonymousCredentials() # Check ssl_channel_credentials is used if provided. with mock.patch.object(transport_class, "create_channel") as mock_create_channel: @@ -1999,7 +2178,7 @@ def test_schema_service_grpc_transport_client_cert_source_for_mtls(transport_cla def test_schema_service_host_no_port(): client = SchemaServiceClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="pubsub.googleapis.com" ), @@ -2009,7 +2188,7 @@ def test_schema_service_host_no_port(): def test_schema_service_host_with_port(): client = SchemaServiceClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="pubsub.googleapis.com:8000" ), @@ -2063,9 +2242,9 @@ def test_schema_service_transport_channel_mtls_with_client_cert_source(transport mock_grpc_channel = mock.Mock() grpc_create_channel.return_value = mock_grpc_channel - cred = credentials.AnonymousCredentials() + cred = ga_credentials.AnonymousCredentials() with pytest.warns(DeprecationWarning): - with mock.patch.object(auth, "default") as adc: + with mock.patch.object(google.auth, "default") as adc: adc.return_value = (cred, None) transport = transport_class( host="squid.clam.whelk", @@ -2150,7 +2329,6 @@ def test_schema_service_transport_channel_mtls_with_adc(transport_class): def test_schema_path(): project = "squid" schema = "clam" - expected = "projects/{project}/schemas/{schema}".format( project=project, schema=schema, ) @@ -2172,7 +2350,6 @@ def test_parse_schema_path(): def test_common_billing_account_path(): billing_account = "oyster" - expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -2193,7 +2370,6 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): folder = "cuttlefish" - expected = "folders/{folder}".format(folder=folder,) actual = SchemaServiceClient.common_folder_path(folder) assert expected == actual @@ -2212,7 +2388,6 @@ def test_parse_common_folder_path(): def test_common_organization_path(): organization = "winkle" - expected = "organizations/{organization}".format(organization=organization,) actual = SchemaServiceClient.common_organization_path(organization) assert expected == actual @@ -2231,7 +2406,6 @@ def test_parse_common_organization_path(): def test_common_project_path(): project = "scallop" - expected = "projects/{project}".format(project=project,) actual = SchemaServiceClient.common_project_path(project) assert expected == actual @@ -2251,7 +2425,6 @@ def test_parse_common_project_path(): def test_common_location_path(): project = "squid" location = "clam" - expected = "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -2278,7 +2451,7 @@ def test_client_withDEFAULT_CLIENT_INFO(): transports.SchemaServiceTransport, "_prep_wrapped_messages" ) as prep: client = SchemaServiceClient( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) @@ -2287,24 +2460,24 @@ def test_client_withDEFAULT_CLIENT_INFO(): ) as prep: transport_class = SchemaServiceClient.get_transport_class() transport = transport_class( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + 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=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional 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.SetIamPolicyRequest() + 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.Policy(version=774, etag=b"etag_blob",) + call.return_value = policy_pb2.Policy(version=774, etag=b"etag_blob",) response = client.set_iam_policy(request) @@ -2315,7 +2488,7 @@ def test_set_iam_policy(transport: str = "grpc"): assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, policy.Policy) + assert isinstance(response, policy_pb2.Policy) assert response.version == 774 @@ -2325,18 +2498,18 @@ def test_set_iam_policy(transport: str = "grpc"): @pytest.mark.asyncio async def test_set_iam_policy_async(transport: str = "grpc_asyncio"): client = SchemaServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional 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.SetIamPolicyRequest() + 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.Policy(version=774, etag=b"etag_blob",) + policy_pb2.Policy(version=774, etag=b"etag_blob",) ) response = await client.set_iam_policy(request) @@ -2348,7 +2521,7 @@ async def test_set_iam_policy_async(transport: str = "grpc_asyncio"): assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, policy.Policy) + assert isinstance(response, policy_pb2.Policy) assert response.version == 774 @@ -2356,16 +2529,16 @@ async def test_set_iam_policy_async(transport: str = "grpc_asyncio"): def test_set_iam_policy_field_headers(): - client = SchemaServiceClient(credentials=credentials.AnonymousCredentials(),) + 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.SetIamPolicyRequest() + 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.Policy() + call.return_value = policy_pb2.Policy() client.set_iam_policy(request) @@ -2381,16 +2554,18 @@ def test_set_iam_policy_field_headers(): @pytest.mark.asyncio async def test_set_iam_policy_field_headers_async(): - client = SchemaServiceAsyncClient(credentials=credentials.AnonymousCredentials(),) + 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.SetIamPolicyRequest() + 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.Policy()) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) await client.set_iam_policy(request) @@ -2405,16 +2580,16 @@ async def test_set_iam_policy_field_headers_async(): def test_set_iam_policy_from_dict(): - client = SchemaServiceClient(credentials=credentials.AnonymousCredentials(),) + 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.Policy() + call.return_value = policy_pb2.Policy() response = client.set_iam_policy( request={ "resource": "resource_value", - "policy": policy.Policy(version=774), + "policy": policy_pb2.Policy(version=774), } ) call.assert_called() @@ -2422,16 +2597,18 @@ def test_set_iam_policy_from_dict(): @pytest.mark.asyncio async def test_set_iam_policy_from_dict_async(): - client = SchemaServiceAsyncClient(credentials=credentials.AnonymousCredentials(),) + 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.Policy()) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) response = await client.set_iam_policy( request={ "resource": "resource_value", - "policy": policy.Policy(version=774), + "policy": policy_pb2.Policy(version=774), } ) call.assert_called() @@ -2439,17 +2616,17 @@ async def test_set_iam_policy_from_dict_async(): def test_get_iam_policy(transport: str = "grpc"): client = SchemaServiceClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional 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.GetIamPolicyRequest() + 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.Policy(version=774, etag=b"etag_blob",) + call.return_value = policy_pb2.Policy(version=774, etag=b"etag_blob",) response = client.get_iam_policy(request) @@ -2460,7 +2637,7 @@ def test_get_iam_policy(transport: str = "grpc"): assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, policy.Policy) + assert isinstance(response, policy_pb2.Policy) assert response.version == 774 @@ -2470,18 +2647,18 @@ def test_get_iam_policy(transport: str = "grpc"): @pytest.mark.asyncio async def test_get_iam_policy_async(transport: str = "grpc_asyncio"): client = SchemaServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional 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.GetIamPolicyRequest() + 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.Policy(version=774, etag=b"etag_blob",) + policy_pb2.Policy(version=774, etag=b"etag_blob",) ) response = await client.get_iam_policy(request) @@ -2493,7 +2670,7 @@ async def test_get_iam_policy_async(transport: str = "grpc_asyncio"): assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, policy.Policy) + assert isinstance(response, policy_pb2.Policy) assert response.version == 774 @@ -2501,16 +2678,16 @@ async def test_get_iam_policy_async(transport: str = "grpc_asyncio"): def test_get_iam_policy_field_headers(): - client = SchemaServiceClient(credentials=credentials.AnonymousCredentials(),) + 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.GetIamPolicyRequest() + 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.Policy() + call.return_value = policy_pb2.Policy() client.get_iam_policy(request) @@ -2526,16 +2703,18 @@ def test_get_iam_policy_field_headers(): @pytest.mark.asyncio async def test_get_iam_policy_field_headers_async(): - client = SchemaServiceAsyncClient(credentials=credentials.AnonymousCredentials(),) + 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.GetIamPolicyRequest() + 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.Policy()) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) await client.get_iam_policy(request) @@ -2550,16 +2729,16 @@ async def test_get_iam_policy_field_headers_async(): def test_get_iam_policy_from_dict(): - client = SchemaServiceClient(credentials=credentials.AnonymousCredentials(),) + 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.Policy() + call.return_value = policy_pb2.Policy() response = client.get_iam_policy( request={ "resource": "resource_value", - "options": options.GetPolicyOptions(requested_policy_version=2598), + "options": options_pb2.GetPolicyOptions(requested_policy_version=2598), } ) call.assert_called() @@ -2567,16 +2746,18 @@ def test_get_iam_policy_from_dict(): @pytest.mark.asyncio async def test_get_iam_policy_from_dict_async(): - client = SchemaServiceAsyncClient(credentials=credentials.AnonymousCredentials(),) + 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.Policy()) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) response = await client.get_iam_policy( request={ "resource": "resource_value", - "options": options.GetPolicyOptions(requested_policy_version=2598), + "options": options_pb2.GetPolicyOptions(requested_policy_version=2598), } ) call.assert_called() @@ -2584,19 +2765,19 @@ async def test_get_iam_policy_from_dict_async(): def test_test_iam_permissions(transport: str = "grpc"): client = SchemaServiceClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional 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.TestIamPermissionsRequest() + 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.TestIamPermissionsResponse( + call.return_value = iam_policy_pb2.TestIamPermissionsResponse( permissions=["permissions_value"], ) @@ -2609,7 +2790,7 @@ def test_test_iam_permissions(transport: str = "grpc"): assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, iam_policy.TestIamPermissionsResponse) + assert isinstance(response, iam_policy_pb2.TestIamPermissionsResponse) assert response.permissions == ["permissions_value"] @@ -2617,12 +2798,12 @@ def test_test_iam_permissions(transport: str = "grpc"): @pytest.mark.asyncio async def test_test_iam_permissions_async(transport: str = "grpc_asyncio"): client = SchemaServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional 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.TestIamPermissionsRequest() + request = iam_policy_pb2.TestIamPermissionsRequest() # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -2630,7 +2811,9 @@ async def test_test_iam_permissions_async(transport: str = "grpc_asyncio"): ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - iam_policy.TestIamPermissionsResponse(permissions=["permissions_value"],) + iam_policy_pb2.TestIamPermissionsResponse( + permissions=["permissions_value"], + ) ) response = await client.test_iam_permissions(request) @@ -2642,24 +2825,24 @@ async def test_test_iam_permissions_async(transport: str = "grpc_asyncio"): assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, iam_policy.TestIamPermissionsResponse) + assert isinstance(response, iam_policy_pb2.TestIamPermissionsResponse) assert response.permissions == ["permissions_value"] def test_test_iam_permissions_field_headers(): - client = SchemaServiceClient(credentials=credentials.AnonymousCredentials(),) + 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.TestIamPermissionsRequest() + 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.TestIamPermissionsResponse() + call.return_value = iam_policy_pb2.TestIamPermissionsResponse() client.test_iam_permissions(request) @@ -2675,11 +2858,13 @@ def test_test_iam_permissions_field_headers(): @pytest.mark.asyncio async def test_test_iam_permissions_field_headers_async(): - client = SchemaServiceAsyncClient(credentials=credentials.AnonymousCredentials(),) + 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.TestIamPermissionsRequest() + request = iam_policy_pb2.TestIamPermissionsRequest() request.resource = "resource/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -2687,7 +2872,7 @@ async def test_test_iam_permissions_field_headers_async(): type(client.transport.test_iam_permissions), "__call__" ) as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - iam_policy.TestIamPermissionsResponse() + iam_policy_pb2.TestIamPermissionsResponse() ) await client.test_iam_permissions(request) @@ -2703,13 +2888,13 @@ async def test_test_iam_permissions_field_headers_async(): def test_test_iam_permissions_from_dict(): - client = SchemaServiceClient(credentials=credentials.AnonymousCredentials(),) + 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.TestIamPermissionsResponse() + call.return_value = iam_policy_pb2.TestIamPermissionsResponse() response = client.test_iam_permissions( request={ @@ -2722,14 +2907,16 @@ def test_test_iam_permissions_from_dict(): @pytest.mark.asyncio async def test_test_iam_permissions_from_dict_async(): - client = SchemaServiceAsyncClient(credentials=credentials.AnonymousCredentials(),) + 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.TestIamPermissionsResponse() + iam_policy_pb2.TestIamPermissionsResponse() ) response = await client.test_iam_permissions( diff --git a/tests/unit/gapic/pubsub_v1/test_subscriber.py b/tests/unit/gapic/pubsub_v1/test_subscriber.py index 96f03eb15..eff436cae 100644 --- a/tests/unit/gapic/pubsub_v1/test_subscriber.py +++ b/tests/unit/gapic/pubsub_v1/test_subscriber.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,10 +13,10 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import os import mock import warnings +import packaging.version import grpc from grpc.experimental import aio @@ -25,26 +24,52 @@ import pytest from proto.marshal.rules.dates import DurationRule, TimestampRule -from google import auth + from google.api_core import client_options -from google.api_core import exceptions +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.auth import credentials +from google.auth import credentials as ga_credentials from google.auth.exceptions import MutualTLSChannelError -from google.iam.v1 import iam_policy_pb2 as iam_policy # type: ignore -from google.iam.v1 import options_pb2 as options # type: ignore -from google.iam.v1 import policy_pb2 as policy # type: ignore +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 as duration # type: ignore -from google.protobuf import field_mask_pb2 as field_mask # type: ignore -from google.protobuf import timestamp_pb2 as timestamp # type: ignore +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore from google.pubsub_v1.services.subscriber import 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.services.subscriber.transports.base import _API_CORE_VERSION +from google.pubsub_v1.services.subscriber.transports.base import _GOOGLE_AUTH_VERSION from google.pubsub_v1.types import pubsub +import google.auth + + +# TODO(busunkim): Once google-api-core >= 1.26.0 is required: +# - Delete all the api-core and auth "less than" test cases +# - Delete these pytest markers (Make the "greater than or equal to" tests the default). +requires_google_auth_lt_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), + reason="This test requires google-auth < 1.25.0", +) +requires_google_auth_gte_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) < packaging.version.parse("1.25.0"), + reason="This test requires google-auth >= 1.25.0", +) + +requires_api_core_lt_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) >= packaging.version.parse("1.26.0"), + reason="This test requires google-api-core < 1.26.0", +) + +requires_api_core_gte_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) < packaging.version.parse("1.26.0"), + reason="This test requires google-api-core >= 1.26.0", +) def client_cert_source_callback(): @@ -90,7 +115,7 @@ def test__get_default_mtls_endpoint(): @pytest.mark.parametrize("client_class", [SubscriberClient, SubscriberAsyncClient,]) def test_subscriber_client_from_service_account_info(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_info" ) as factory: @@ -105,7 +130,7 @@ def test_subscriber_client_from_service_account_info(client_class): @pytest.mark.parametrize("client_class", [SubscriberClient, SubscriberAsyncClient,]) def test_subscriber_client_from_service_account_file(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_file" ) as factory: @@ -156,7 +181,7 @@ def test_subscriber_client_client_options( ): # 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=credentials.AnonymousCredentials()) + transport = transport_class(credentials=ga_credentials.AnonymousCredentials()) client = client_class(transport=transport) gtc.assert_not_called() @@ -438,7 +463,7 @@ def test_subscriber_client_client_options_from_dict(): def test_create_subscription(transport: str = "grpc", request_type=pubsub.Subscription): client = SubscriberClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -459,31 +484,21 @@ def test_create_subscription(transport: str = "grpc", request_type=pubsub.Subscr filter="filter_value", detached=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 @@ -495,7 +510,7 @@ 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=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -505,7 +520,6 @@ def test_create_subscription_empty_call(): client.create_subscription() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == pubsub.Subscription() @@ -514,7 +528,7 @@ async def test_create_subscription_async( transport: str = "grpc_asyncio", request_type=pubsub.Subscription ): client = SubscriberAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -537,30 +551,21 @@ async def test_create_subscription_async( detached=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 @@ -570,11 +575,12 @@ async def test_create_subscription_async_from_dict(): def test_create_subscription_field_headers(): - client = SubscriberClient(credentials=credentials.AnonymousCredentials(),) + 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. @@ -582,7 +588,6 @@ def test_create_subscription_field_headers(): 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. @@ -597,11 +602,12 @@ def test_create_subscription_field_headers(): @pytest.mark.asyncio async def test_create_subscription_field_headers_async(): - client = SubscriberAsyncClient(credentials=credentials.AnonymousCredentials(),) + 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. @@ -609,7 +615,6 @@ async def test_create_subscription_field_headers_async(): 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. @@ -623,7 +628,7 @@ async def test_create_subscription_field_headers_async(): def test_create_subscription_flattened(): - client = SubscriberClient(credentials=credentials.AnonymousCredentials(),) + client = SubscriberClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -631,7 +636,6 @@ def test_create_subscription_flattened(): ) 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( @@ -645,20 +649,16 @@ def test_create_subscription_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" - assert args[0].topic == "topic_value" - assert args[0].push_config == pubsub.PushConfig( push_endpoint="push_endpoint_value" ) - assert args[0].ack_deadline_seconds == 2066 def test_create_subscription_flattened_error(): - client = SubscriberClient(credentials=credentials.AnonymousCredentials(),) + client = SubscriberClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -674,7 +674,7 @@ def test_create_subscription_flattened_error(): @pytest.mark.asyncio async def test_create_subscription_flattened_async(): - client = SubscriberAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = SubscriberAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -697,21 +697,17 @@ async def test_create_subscription_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" - assert args[0].topic == "topic_value" - assert args[0].push_config == pubsub.PushConfig( push_endpoint="push_endpoint_value" ) - assert args[0].ack_deadline_seconds == 2066 @pytest.mark.asyncio async def test_create_subscription_flattened_error_async(): - client = SubscriberAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = SubscriberAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -729,7 +725,7 @@ def test_get_subscription( transport: str = "grpc", request_type=pubsub.GetSubscriptionRequest ): client = SubscriberClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -748,31 +744,21 @@ def test_get_subscription( filter="filter_value", detached=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 @@ -784,7 +770,7 @@ 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=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -792,7 +778,6 @@ def test_get_subscription_empty_call(): client.get_subscription() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == pubsub.GetSubscriptionRequest() @@ -801,7 +786,7 @@ async def test_get_subscription_async( transport: str = "grpc_asyncio", request_type=pubsub.GetSubscriptionRequest ): client = SubscriberAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -822,30 +807,21 @@ async def test_get_subscription_async( detached=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 @@ -855,17 +831,17 @@ async def test_get_subscription_async_from_dict(): def test_get_subscription_field_headers(): - client = SubscriberClient(credentials=credentials.AnonymousCredentials(),) + 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. @@ -882,17 +858,17 @@ def test_get_subscription_field_headers(): @pytest.mark.asyncio async def test_get_subscription_field_headers_async(): - client = SubscriberAsyncClient(credentials=credentials.AnonymousCredentials(),) + 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. @@ -908,13 +884,12 @@ async def test_get_subscription_field_headers_async(): def test_get_subscription_flattened(): - client = SubscriberClient(credentials=credentials.AnonymousCredentials(),) + 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",) @@ -923,12 +898,11 @@ def test_get_subscription_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].subscription == "subscription_value" def test_get_subscription_flattened_error(): - client = SubscriberClient(credentials=credentials.AnonymousCredentials(),) + client = SubscriberClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -940,7 +914,7 @@ def test_get_subscription_flattened_error(): @pytest.mark.asyncio async def test_get_subscription_flattened_async(): - client = SubscriberAsyncClient(credentials=credentials.AnonymousCredentials(),) + 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: @@ -956,13 +930,12 @@ async def test_get_subscription_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].subscription == "subscription_value" @pytest.mark.asyncio async def test_get_subscription_flattened_error_async(): - client = SubscriberAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = SubscriberAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -976,7 +949,7 @@ def test_update_subscription( transport: str = "grpc", request_type=pubsub.UpdateSubscriptionRequest ): client = SubscriberClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -997,31 +970,21 @@ def test_update_subscription( filter="filter_value", detached=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 @@ -1033,7 +996,7 @@ 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=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1043,7 +1006,6 @@ def test_update_subscription_empty_call(): client.update_subscription() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == pubsub.UpdateSubscriptionRequest() @@ -1052,7 +1014,7 @@ async def test_update_subscription_async( transport: str = "grpc_asyncio", request_type=pubsub.UpdateSubscriptionRequest ): client = SubscriberAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1075,30 +1037,21 @@ async def test_update_subscription_async( detached=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 @@ -1108,11 +1061,12 @@ async def test_update_subscription_async_from_dict(): def test_update_subscription_field_headers(): - client = SubscriberClient(credentials=credentials.AnonymousCredentials(),) + 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. @@ -1120,7 +1074,6 @@ def test_update_subscription_field_headers(): 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. @@ -1138,11 +1091,12 @@ def test_update_subscription_field_headers(): @pytest.mark.asyncio async def test_update_subscription_field_headers_async(): - client = SubscriberAsyncClient(credentials=credentials.AnonymousCredentials(),) + 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. @@ -1150,7 +1104,6 @@ async def test_update_subscription_field_headers_async(): 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. @@ -1170,7 +1123,7 @@ def test_list_subscriptions( transport: str = "grpc", request_type=pubsub.ListSubscriptionsRequest ): client = SubscriberClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1185,19 +1138,15 @@ def test_list_subscriptions( 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" @@ -1209,7 +1158,7 @@ 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=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1219,7 +1168,6 @@ def test_list_subscriptions_empty_call(): client.list_subscriptions() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == pubsub.ListSubscriptionsRequest() @@ -1228,7 +1176,7 @@ async def test_list_subscriptions_async( transport: str = "grpc_asyncio", request_type=pubsub.ListSubscriptionsRequest ): client = SubscriberAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1243,18 +1191,15 @@ async def test_list_subscriptions_async( 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" @@ -1264,11 +1209,12 @@ async def test_list_subscriptions_async_from_dict(): def test_list_subscriptions_field_headers(): - client = SubscriberClient(credentials=credentials.AnonymousCredentials(),) + 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. @@ -1276,7 +1222,6 @@ def test_list_subscriptions_field_headers(): 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. @@ -1291,11 +1236,12 @@ def test_list_subscriptions_field_headers(): @pytest.mark.asyncio async def test_list_subscriptions_field_headers_async(): - client = SubscriberAsyncClient(credentials=credentials.AnonymousCredentials(),) + 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. @@ -1305,7 +1251,6 @@ async def test_list_subscriptions_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( pubsub.ListSubscriptionsResponse() ) - await client.list_subscriptions(request) # Establish that the underlying gRPC stub method was called. @@ -1319,7 +1264,7 @@ async def test_list_subscriptions_field_headers_async(): def test_list_subscriptions_flattened(): - client = SubscriberClient(credentials=credentials.AnonymousCredentials(),) + client = SubscriberClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1327,7 +1272,6 @@ def test_list_subscriptions_flattened(): ) 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",) @@ -1336,12 +1280,11 @@ def test_list_subscriptions_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].project == "project_value" def test_list_subscriptions_flattened_error(): - client = SubscriberClient(credentials=credentials.AnonymousCredentials(),) + client = SubscriberClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1353,7 +1296,7 @@ def test_list_subscriptions_flattened_error(): @pytest.mark.asyncio async def test_list_subscriptions_flattened_async(): - client = SubscriberAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = SubscriberAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1373,13 +1316,12 @@ async def test_list_subscriptions_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].project == "project_value" @pytest.mark.asyncio async def test_list_subscriptions_flattened_error_async(): - client = SubscriberAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = SubscriberAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1390,7 +1332,7 @@ async def test_list_subscriptions_flattened_error_async(): def test_list_subscriptions_pager(): - client = SubscriberClient(credentials=credentials.AnonymousCredentials,) + client = SubscriberClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1430,7 +1372,7 @@ def test_list_subscriptions_pager(): def test_list_subscriptions_pages(): - client = SubscriberClient(credentials=credentials.AnonymousCredentials,) + client = SubscriberClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1462,7 +1404,7 @@ def test_list_subscriptions_pages(): @pytest.mark.asyncio async def test_list_subscriptions_async_pager(): - client = SubscriberAsyncClient(credentials=credentials.AnonymousCredentials,) + client = SubscriberAsyncClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1501,7 +1443,7 @@ async def test_list_subscriptions_async_pager(): @pytest.mark.asyncio async def test_list_subscriptions_async_pages(): - client = SubscriberAsyncClient(credentials=credentials.AnonymousCredentials,) + client = SubscriberAsyncClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1539,7 +1481,7 @@ def test_delete_subscription( transport: str = "grpc", request_type=pubsub.DeleteSubscriptionRequest ): client = SubscriberClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1552,13 +1494,11 @@ def test_delete_subscription( ) 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. @@ -1573,7 +1513,7 @@ 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=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1583,7 +1523,6 @@ def test_delete_subscription_empty_call(): client.delete_subscription() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == pubsub.DeleteSubscriptionRequest() @@ -1592,7 +1531,7 @@ async def test_delete_subscription_async( transport: str = "grpc_asyncio", request_type=pubsub.DeleteSubscriptionRequest ): client = SubscriberAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1605,13 +1544,11 @@ async def test_delete_subscription_async( ) 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. @@ -1624,11 +1561,12 @@ async def test_delete_subscription_async_from_dict(): def test_delete_subscription_field_headers(): - client = SubscriberClient(credentials=credentials.AnonymousCredentials(),) + 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. @@ -1636,7 +1574,6 @@ def test_delete_subscription_field_headers(): 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. @@ -1653,11 +1590,12 @@ def test_delete_subscription_field_headers(): @pytest.mark.asyncio async def test_delete_subscription_field_headers_async(): - client = SubscriberAsyncClient(credentials=credentials.AnonymousCredentials(),) + 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. @@ -1665,7 +1603,6 @@ async def test_delete_subscription_field_headers_async(): 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. @@ -1681,7 +1618,7 @@ async def test_delete_subscription_field_headers_async(): def test_delete_subscription_flattened(): - client = SubscriberClient(credentials=credentials.AnonymousCredentials(),) + client = SubscriberClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1689,7 +1626,6 @@ def test_delete_subscription_flattened(): ) 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",) @@ -1698,12 +1634,11 @@ def test_delete_subscription_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].subscription == "subscription_value" def test_delete_subscription_flattened_error(): - client = SubscriberClient(credentials=credentials.AnonymousCredentials(),) + client = SubscriberClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1715,7 +1650,7 @@ def test_delete_subscription_flattened_error(): @pytest.mark.asyncio async def test_delete_subscription_flattened_async(): - client = SubscriberAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = SubscriberAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1733,13 +1668,12 @@ async def test_delete_subscription_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].subscription == "subscription_value" @pytest.mark.asyncio async def test_delete_subscription_flattened_error_async(): - client = SubscriberAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = SubscriberAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1753,7 +1687,7 @@ def test_modify_ack_deadline( transport: str = "grpc", request_type=pubsub.ModifyAckDeadlineRequest ): client = SubscriberClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1766,13 +1700,11 @@ def test_modify_ack_deadline( ) 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. @@ -1787,7 +1719,7 @@ 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=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1797,7 +1729,6 @@ def test_modify_ack_deadline_empty_call(): client.modify_ack_deadline() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == pubsub.ModifyAckDeadlineRequest() @@ -1806,7 +1737,7 @@ async def test_modify_ack_deadline_async( transport: str = "grpc_asyncio", request_type=pubsub.ModifyAckDeadlineRequest ): client = SubscriberAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1819,13 +1750,11 @@ async def test_modify_ack_deadline_async( ) 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. @@ -1838,11 +1767,12 @@ async def test_modify_ack_deadline_async_from_dict(): def test_modify_ack_deadline_field_headers(): - client = SubscriberClient(credentials=credentials.AnonymousCredentials(),) + 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. @@ -1850,7 +1780,6 @@ def test_modify_ack_deadline_field_headers(): 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. @@ -1867,11 +1796,12 @@ def test_modify_ack_deadline_field_headers(): @pytest.mark.asyncio async def test_modify_ack_deadline_field_headers_async(): - client = SubscriberAsyncClient(credentials=credentials.AnonymousCredentials(),) + 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. @@ -1879,7 +1809,6 @@ async def test_modify_ack_deadline_field_headers_async(): 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. @@ -1895,7 +1824,7 @@ async def test_modify_ack_deadline_field_headers_async(): def test_modify_ack_deadline_flattened(): - client = SubscriberClient(credentials=credentials.AnonymousCredentials(),) + client = SubscriberClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1903,7 +1832,6 @@ def test_modify_ack_deadline_flattened(): ) 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( @@ -1916,16 +1844,13 @@ def test_modify_ack_deadline_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].subscription == "subscription_value" - assert args[0].ack_ids == ["ack_ids_value"] - assert args[0].ack_deadline_seconds == 2066 def test_modify_ack_deadline_flattened_error(): - client = SubscriberClient(credentials=credentials.AnonymousCredentials(),) + client = SubscriberClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1940,7 +1865,7 @@ def test_modify_ack_deadline_flattened_error(): @pytest.mark.asyncio async def test_modify_ack_deadline_flattened_async(): - client = SubscriberAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = SubscriberAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1962,17 +1887,14 @@ async def test_modify_ack_deadline_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].subscription == "subscription_value" - assert args[0].ack_ids == ["ack_ids_value"] - assert args[0].ack_deadline_seconds == 2066 @pytest.mark.asyncio async def test_modify_ack_deadline_flattened_error_async(): - client = SubscriberAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = SubscriberAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1987,7 +1909,7 @@ async def test_modify_ack_deadline_flattened_error_async(): def test_acknowledge(transport: str = "grpc", request_type=pubsub.AcknowledgeRequest): client = SubscriberClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1998,13 +1920,11 @@ def test_acknowledge(transport: str = "grpc", request_type=pubsub.AcknowledgeReq 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. @@ -2019,7 +1939,7 @@ 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=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2027,7 +1947,6 @@ def test_acknowledge_empty_call(): client.acknowledge() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == pubsub.AcknowledgeRequest() @@ -2036,7 +1955,7 @@ async def test_acknowledge_async( transport: str = "grpc_asyncio", request_type=pubsub.AcknowledgeRequest ): client = SubscriberAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -2047,13 +1966,11 @@ async def test_acknowledge_async( 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. @@ -2066,17 +1983,17 @@ async def test_acknowledge_async_from_dict(): def test_acknowledge_field_headers(): - client = SubscriberClient(credentials=credentials.AnonymousCredentials(),) + 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. @@ -2093,17 +2010,17 @@ def test_acknowledge_field_headers(): @pytest.mark.asyncio async def test_acknowledge_field_headers_async(): - client = SubscriberAsyncClient(credentials=credentials.AnonymousCredentials(),) + 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. @@ -2119,13 +2036,12 @@ async def test_acknowledge_field_headers_async(): def test_acknowledge_flattened(): - client = SubscriberClient(credentials=credentials.AnonymousCredentials(),) + 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( @@ -2136,14 +2052,12 @@ def test_acknowledge_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].subscription == "subscription_value" - assert args[0].ack_ids == ["ack_ids_value"] def test_acknowledge_flattened_error(): - client = SubscriberClient(credentials=credentials.AnonymousCredentials(),) + client = SubscriberClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -2157,7 +2071,7 @@ def test_acknowledge_flattened_error(): @pytest.mark.asyncio async def test_acknowledge_flattened_async(): - client = SubscriberAsyncClient(credentials=credentials.AnonymousCredentials(),) + 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: @@ -2175,15 +2089,13 @@ async def test_acknowledge_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].subscription == "subscription_value" - assert args[0].ack_ids == ["ack_ids_value"] @pytest.mark.asyncio async def test_acknowledge_flattened_error_async(): - client = SubscriberAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = SubscriberAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -2197,7 +2109,7 @@ async def test_acknowledge_flattened_error_async(): def test_pull(transport: str = "grpc", request_type=pubsub.PullRequest): client = SubscriberClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -2208,17 +2120,14 @@ def test_pull(transport: str = "grpc", request_type=pubsub.PullRequest): 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) @@ -2230,7 +2139,7 @@ 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=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2238,7 +2147,6 @@ def test_pull_empty_call(): client.pull() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == pubsub.PullRequest() @@ -2247,7 +2155,7 @@ async def test_pull_async( transport: str = "grpc_asyncio", request_type=pubsub.PullRequest ): client = SubscriberAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -2258,13 +2166,11 @@ async def test_pull_async( 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. @@ -2277,17 +2183,17 @@ async def test_pull_async_from_dict(): def test_pull_field_headers(): - client = SubscriberClient(credentials=credentials.AnonymousCredentials(),) + 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. @@ -2304,17 +2210,17 @@ def test_pull_field_headers(): @pytest.mark.asyncio async def test_pull_field_headers_async(): - client = SubscriberAsyncClient(credentials=credentials.AnonymousCredentials(),) + 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. @@ -2330,13 +2236,12 @@ async def test_pull_field_headers_async(): def test_pull_flattened(): - client = SubscriberClient(credentials=credentials.AnonymousCredentials(),) + 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. with warnings.catch_warnings(): @@ -2351,16 +2256,13 @@ def test_pull_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].subscription == "subscription_value" - assert args[0].return_immediately == True - assert args[0].max_messages == 1277 def test_pull_flattened_error(): - client = SubscriberClient(credentials=credentials.AnonymousCredentials(),) + client = SubscriberClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -2375,7 +2277,7 @@ def test_pull_flattened_error(): @pytest.mark.asyncio async def test_pull_flattened_async(): - client = SubscriberAsyncClient(credentials=credentials.AnonymousCredentials(),) + 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: @@ -2397,17 +2299,14 @@ async def test_pull_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].subscription == "subscription_value" - assert args[0].return_immediately == True - assert args[0].max_messages == 1277 @pytest.mark.asyncio async def test_pull_flattened_error_async(): - client = SubscriberAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = SubscriberAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -2424,26 +2323,23 @@ def test_streaming_pull( transport: str = "grpc", request_type=pubsub.StreamingPullRequest ): client = SubscriberClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 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. @@ -2460,13 +2356,12 @@ async def test_streaming_pull_async( transport: str = "grpc_asyncio", request_type=pubsub.StreamingPullRequest ): client = SubscriberAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 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. @@ -2476,13 +2371,11 @@ async def test_streaming_pull_async( 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. @@ -2499,7 +2392,7 @@ def test_modify_push_config( transport: str = "grpc", request_type=pubsub.ModifyPushConfigRequest ): client = SubscriberClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -2512,13 +2405,11 @@ def test_modify_push_config( ) 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. @@ -2533,7 +2424,7 @@ 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=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2543,7 +2434,6 @@ def test_modify_push_config_empty_call(): client.modify_push_config() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == pubsub.ModifyPushConfigRequest() @@ -2552,7 +2442,7 @@ async def test_modify_push_config_async( transport: str = "grpc_asyncio", request_type=pubsub.ModifyPushConfigRequest ): client = SubscriberAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -2565,13 +2455,11 @@ async def test_modify_push_config_async( ) 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. @@ -2584,11 +2472,12 @@ async def test_modify_push_config_async_from_dict(): def test_modify_push_config_field_headers(): - client = SubscriberClient(credentials=credentials.AnonymousCredentials(),) + 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. @@ -2596,7 +2485,6 @@ def test_modify_push_config_field_headers(): 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. @@ -2613,11 +2501,12 @@ def test_modify_push_config_field_headers(): @pytest.mark.asyncio async def test_modify_push_config_field_headers_async(): - client = SubscriberAsyncClient(credentials=credentials.AnonymousCredentials(),) + 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. @@ -2625,7 +2514,6 @@ async def test_modify_push_config_field_headers_async(): 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. @@ -2641,7 +2529,7 @@ async def test_modify_push_config_field_headers_async(): def test_modify_push_config_flattened(): - client = SubscriberClient(credentials=credentials.AnonymousCredentials(),) + client = SubscriberClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -2649,7 +2537,6 @@ def test_modify_push_config_flattened(): ) 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( @@ -2661,16 +2548,14 @@ def test_modify_push_config_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].subscription == "subscription_value" - assert args[0].push_config == pubsub.PushConfig( push_endpoint="push_endpoint_value" ) def test_modify_push_config_flattened_error(): - client = SubscriberClient(credentials=credentials.AnonymousCredentials(),) + client = SubscriberClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -2684,7 +2569,7 @@ def test_modify_push_config_flattened_error(): @pytest.mark.asyncio async def test_modify_push_config_flattened_async(): - client = SubscriberAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = SubscriberAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -2705,9 +2590,7 @@ async def test_modify_push_config_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].subscription == "subscription_value" - assert args[0].push_config == pubsub.PushConfig( push_endpoint="push_endpoint_value" ) @@ -2715,7 +2598,7 @@ async def test_modify_push_config_flattened_async(): @pytest.mark.asyncio async def test_modify_push_config_flattened_error_async(): - client = SubscriberAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = SubscriberAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -2729,7 +2612,7 @@ async def test_modify_push_config_flattened_error_async(): def test_get_snapshot(transport: str = "grpc", request_type=pubsub.GetSnapshotRequest): client = SubscriberClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -2740,21 +2623,16 @@ def test_get_snapshot(transport: str = "grpc", request_type=pubsub.GetSnapshotRe 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" @@ -2766,7 +2644,7 @@ 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=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2774,7 +2652,6 @@ def test_get_snapshot_empty_call(): client.get_snapshot() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == pubsub.GetSnapshotRequest() @@ -2783,7 +2660,7 @@ async def test_get_snapshot_async( transport: str = "grpc_asyncio", request_type=pubsub.GetSnapshotRequest ): client = SubscriberAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -2796,20 +2673,16 @@ async def test_get_snapshot_async( 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" @@ -2819,17 +2692,17 @@ async def test_get_snapshot_async_from_dict(): def test_get_snapshot_field_headers(): - client = SubscriberClient(credentials=credentials.AnonymousCredentials(),) + 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. @@ -2844,17 +2717,17 @@ def test_get_snapshot_field_headers(): @pytest.mark.asyncio async def test_get_snapshot_field_headers_async(): - client = SubscriberAsyncClient(credentials=credentials.AnonymousCredentials(),) + 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. @@ -2868,13 +2741,12 @@ async def test_get_snapshot_field_headers_async(): def test_get_snapshot_flattened(): - client = SubscriberClient(credentials=credentials.AnonymousCredentials(),) + 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",) @@ -2883,12 +2755,11 @@ def test_get_snapshot_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].snapshot == "snapshot_value" def test_get_snapshot_flattened_error(): - client = SubscriberClient(credentials=credentials.AnonymousCredentials(),) + client = SubscriberClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -2900,7 +2771,7 @@ def test_get_snapshot_flattened_error(): @pytest.mark.asyncio async def test_get_snapshot_flattened_async(): - client = SubscriberAsyncClient(credentials=credentials.AnonymousCredentials(),) + 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: @@ -2916,13 +2787,12 @@ async def test_get_snapshot_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].snapshot == "snapshot_value" @pytest.mark.asyncio async def test_get_snapshot_flattened_error_async(): - client = SubscriberAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = SubscriberAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -2936,7 +2806,7 @@ def test_list_snapshots( transport: str = "grpc", request_type=pubsub.ListSnapshotsRequest ): client = SubscriberClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -2949,19 +2819,15 @@ def test_list_snapshots( 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" @@ -2973,7 +2839,7 @@ 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=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2981,7 +2847,6 @@ def test_list_snapshots_empty_call(): client.list_snapshots() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == pubsub.ListSnapshotsRequest() @@ -2990,7 +2855,7 @@ async def test_list_snapshots_async( transport: str = "grpc_asyncio", request_type=pubsub.ListSnapshotsRequest ): client = SubscriberAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -3003,18 +2868,15 @@ async def test_list_snapshots_async( 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" @@ -3024,17 +2886,17 @@ async def test_list_snapshots_async_from_dict(): def test_list_snapshots_field_headers(): - client = SubscriberClient(credentials=credentials.AnonymousCredentials(),) + 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. @@ -3049,11 +2911,12 @@ def test_list_snapshots_field_headers(): @pytest.mark.asyncio async def test_list_snapshots_field_headers_async(): - client = SubscriberAsyncClient(credentials=credentials.AnonymousCredentials(),) + 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. @@ -3061,7 +2924,6 @@ async def test_list_snapshots_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( pubsub.ListSnapshotsResponse() ) - await client.list_snapshots(request) # Establish that the underlying gRPC stub method was called. @@ -3075,13 +2937,12 @@ async def test_list_snapshots_field_headers_async(): def test_list_snapshots_flattened(): - client = SubscriberClient(credentials=credentials.AnonymousCredentials(),) + 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",) @@ -3090,12 +2951,11 @@ def test_list_snapshots_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].project == "project_value" def test_list_snapshots_flattened_error(): - client = SubscriberClient(credentials=credentials.AnonymousCredentials(),) + client = SubscriberClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -3107,7 +2967,7 @@ def test_list_snapshots_flattened_error(): @pytest.mark.asyncio async def test_list_snapshots_flattened_async(): - client = SubscriberAsyncClient(credentials=credentials.AnonymousCredentials(),) + 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: @@ -3125,13 +2985,12 @@ async def test_list_snapshots_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].project == "project_value" @pytest.mark.asyncio async def test_list_snapshots_flattened_error_async(): - client = SubscriberAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = SubscriberAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -3142,7 +3001,7 @@ async def test_list_snapshots_flattened_error_async(): def test_list_snapshots_pager(): - client = SubscriberClient(credentials=credentials.AnonymousCredentials,) + 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: @@ -3176,7 +3035,7 @@ def test_list_snapshots_pager(): def test_list_snapshots_pages(): - client = SubscriberClient(credentials=credentials.AnonymousCredentials,) + 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: @@ -3202,7 +3061,7 @@ def test_list_snapshots_pages(): @pytest.mark.asyncio async def test_list_snapshots_async_pager(): - client = SubscriberAsyncClient(credentials=credentials.AnonymousCredentials,) + client = SubscriberAsyncClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -3235,7 +3094,7 @@ async def test_list_snapshots_async_pager(): @pytest.mark.asyncio async def test_list_snapshots_async_pages(): - client = SubscriberAsyncClient(credentials=credentials.AnonymousCredentials,) + client = SubscriberAsyncClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -3267,7 +3126,7 @@ def test_create_snapshot( transport: str = "grpc", request_type=pubsub.CreateSnapshotRequest ): client = SubscriberClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -3278,21 +3137,16 @@ def test_create_snapshot( 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" @@ -3304,7 +3158,7 @@ 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=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -3312,7 +3166,6 @@ def test_create_snapshot_empty_call(): client.create_snapshot() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == pubsub.CreateSnapshotRequest() @@ -3321,7 +3174,7 @@ async def test_create_snapshot_async( transport: str = "grpc_asyncio", request_type=pubsub.CreateSnapshotRequest ): client = SubscriberAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -3334,20 +3187,16 @@ async def test_create_snapshot_async( 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" @@ -3357,17 +3206,17 @@ async def test_create_snapshot_async_from_dict(): def test_create_snapshot_field_headers(): - client = SubscriberClient(credentials=credentials.AnonymousCredentials(),) + 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. @@ -3382,17 +3231,17 @@ def test_create_snapshot_field_headers(): @pytest.mark.asyncio async def test_create_snapshot_field_headers_async(): - client = SubscriberAsyncClient(credentials=credentials.AnonymousCredentials(),) + 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. @@ -3406,13 +3255,12 @@ async def test_create_snapshot_field_headers_async(): def test_create_snapshot_flattened(): - client = SubscriberClient(credentials=credentials.AnonymousCredentials(),) + 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( @@ -3423,14 +3271,12 @@ def test_create_snapshot_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" - assert args[0].subscription == "subscription_value" def test_create_snapshot_flattened_error(): - client = SubscriberClient(credentials=credentials.AnonymousCredentials(),) + client = SubscriberClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -3444,7 +3290,7 @@ def test_create_snapshot_flattened_error(): @pytest.mark.asyncio async def test_create_snapshot_flattened_async(): - client = SubscriberAsyncClient(credentials=credentials.AnonymousCredentials(),) + 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: @@ -3462,15 +3308,13 @@ async def test_create_snapshot_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" - assert args[0].subscription == "subscription_value" @pytest.mark.asyncio async def test_create_snapshot_flattened_error_async(): - client = SubscriberAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = SubscriberAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -3486,7 +3330,7 @@ def test_update_snapshot( transport: str = "grpc", request_type=pubsub.UpdateSnapshotRequest ): client = SubscriberClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -3497,21 +3341,16 @@ def test_update_snapshot( 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" @@ -3523,7 +3362,7 @@ 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=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -3531,7 +3370,6 @@ def test_update_snapshot_empty_call(): client.update_snapshot() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == pubsub.UpdateSnapshotRequest() @@ -3540,7 +3378,7 @@ async def test_update_snapshot_async( transport: str = "grpc_asyncio", request_type=pubsub.UpdateSnapshotRequest ): client = SubscriberAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -3553,20 +3391,16 @@ async def test_update_snapshot_async( 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" @@ -3576,17 +3410,17 @@ async def test_update_snapshot_async_from_dict(): def test_update_snapshot_field_headers(): - client = SubscriberClient(credentials=credentials.AnonymousCredentials(),) + 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. @@ -3603,17 +3437,17 @@ def test_update_snapshot_field_headers(): @pytest.mark.asyncio async def test_update_snapshot_field_headers_async(): - client = SubscriberAsyncClient(credentials=credentials.AnonymousCredentials(),) + 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. @@ -3632,7 +3466,7 @@ def test_delete_snapshot( transport: str = "grpc", request_type=pubsub.DeleteSnapshotRequest ): client = SubscriberClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -3643,13 +3477,11 @@ def test_delete_snapshot( 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. @@ -3664,7 +3496,7 @@ 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=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -3672,7 +3504,6 @@ def test_delete_snapshot_empty_call(): client.delete_snapshot() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == pubsub.DeleteSnapshotRequest() @@ -3681,7 +3512,7 @@ async def test_delete_snapshot_async( transport: str = "grpc_asyncio", request_type=pubsub.DeleteSnapshotRequest ): client = SubscriberAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -3692,13 +3523,11 @@ async def test_delete_snapshot_async( 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. @@ -3711,17 +3540,17 @@ async def test_delete_snapshot_async_from_dict(): def test_delete_snapshot_field_headers(): - client = SubscriberClient(credentials=credentials.AnonymousCredentials(),) + 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. @@ -3736,17 +3565,17 @@ def test_delete_snapshot_field_headers(): @pytest.mark.asyncio async def test_delete_snapshot_field_headers_async(): - client = SubscriberAsyncClient(credentials=credentials.AnonymousCredentials(),) + 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. @@ -3760,13 +3589,12 @@ async def test_delete_snapshot_field_headers_async(): def test_delete_snapshot_flattened(): - client = SubscriberClient(credentials=credentials.AnonymousCredentials(),) + 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",) @@ -3775,12 +3603,11 @@ def test_delete_snapshot_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].snapshot == "snapshot_value" def test_delete_snapshot_flattened_error(): - client = SubscriberClient(credentials=credentials.AnonymousCredentials(),) + client = SubscriberClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -3792,7 +3619,7 @@ def test_delete_snapshot_flattened_error(): @pytest.mark.asyncio async def test_delete_snapshot_flattened_async(): - client = SubscriberAsyncClient(credentials=credentials.AnonymousCredentials(),) + 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: @@ -3808,13 +3635,12 @@ async def test_delete_snapshot_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].snapshot == "snapshot_value" @pytest.mark.asyncio async def test_delete_snapshot_flattened_error_async(): - client = SubscriberAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = SubscriberAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -3826,7 +3652,7 @@ async def test_delete_snapshot_flattened_error_async(): def test_seek(transport: str = "grpc", request_type=pubsub.SeekRequest): client = SubscriberClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -3837,17 +3663,14 @@ def test_seek(transport: str = "grpc", request_type=pubsub.SeekRequest): 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) @@ -3859,7 +3682,7 @@ 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=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -3867,7 +3690,6 @@ def test_seek_empty_call(): client.seek() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == pubsub.SeekRequest() @@ -3876,7 +3698,7 @@ async def test_seek_async( transport: str = "grpc_asyncio", request_type=pubsub.SeekRequest ): client = SubscriberAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -3887,13 +3709,11 @@ async def test_seek_async( 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. @@ -3906,17 +3726,17 @@ async def test_seek_async_from_dict(): def test_seek_field_headers(): - client = SubscriberClient(credentials=credentials.AnonymousCredentials(),) + 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. @@ -3933,17 +3753,17 @@ def test_seek_field_headers(): @pytest.mark.asyncio async def test_seek_field_headers_async(): - client = SubscriberAsyncClient(credentials=credentials.AnonymousCredentials(),) + 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. @@ -3961,16 +3781,16 @@ async def test_seek_field_headers_async(): def test_credentials_transport_error(): # It is an error to provide credentials and a transport instance. transport = transports.SubscriberGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = SubscriberClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # It is an error to provide a credentials file and a transport instance. transport = transports.SubscriberGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = SubscriberClient( @@ -3980,7 +3800,7 @@ def test_credentials_transport_error(): # It is an error to provide scopes and a transport instance. transport = transports.SubscriberGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = SubscriberClient( @@ -3991,7 +3811,7 @@ def test_credentials_transport_error(): def test_transport_instance(): # A client may be instantiated with a custom transport instance. transport = transports.SubscriberGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) client = SubscriberClient(transport=transport) assert client.transport is transport @@ -4000,13 +3820,13 @@ def test_transport_instance(): def test_transport_get_channel(): # A client may be instantiated with a custom transport instance. transport = transports.SubscriberGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) channel = transport.grpc_channel assert channel transport = transports.SubscriberGrpcAsyncIOTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) channel = transport.grpc_channel assert channel @@ -4018,23 +3838,23 @@ def test_transport_get_channel(): ) def test_transport_adc(transport_class): # Test default credentials are used if not provided. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + 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=credentials.AnonymousCredentials(),) + 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(exceptions.DuplicateCredentialArgs): + with pytest.raises(core_exceptions.DuplicateCredentialArgs): transport = transports.SubscriberTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), credentials_file="credentials.json", ) @@ -4046,7 +3866,7 @@ def test_subscriber_base_transport(): ) as Transport: Transport.return_value = None transport = transports.SubscriberTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Every method on the transport should just blindly @@ -4077,15 +3897,40 @@ def test_subscriber_base_transport(): getattr(transport, method)(request=object()) +@requires_google_auth_gte_1_25_0 def test_subscriber_base_transport_with_credentials_file(): # Instantiate the base transport with a credentials file with mock.patch.object( - auth, "load_credentials_from_file" + 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", + ) + + +@requires_google_auth_lt_1_25_0 +def test_subscriber_base_transport_with_credentials_file_old_google_auth(): + # 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 = (credentials.AnonymousCredentials(), None) + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.SubscriberTransport( credentials_file="credentials.json", quota_project_id="octopus", ) @@ -4101,19 +3946,36 @@ def test_subscriber_base_transport_with_credentials_file(): def test_subscriber_base_transport_with_adc(): # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(auth, "default") as adc, mock.patch( + 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 = (credentials.AnonymousCredentials(), None) + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.SubscriberTransport() adc.assert_called_once() +@requires_google_auth_gte_1_25_0 def test_subscriber_auth_adc(): # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + 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, + ) + + +@requires_google_auth_lt_1_25_0 +def test_subscriber_auth_adc_old_google_auth(): + # 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=( @@ -4124,14 +3986,38 @@ def test_subscriber_auth_adc(): ) -def test_subscriber_transport_auth_adc(): +@pytest.mark.parametrize( + "transport_class", + [transports.SubscriberGrpcTransport, transports.SubscriberGrpcAsyncIOTransport,], +) +@requires_google_auth_gte_1_25_0 +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(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) - transports.SubscriberGrpcTransport( - host="squid.clam.whelk", quota_project_id="octopus" + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + adc.assert_called_once_with( + scopes=["1", "2"], + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/pubsub", + ), + quota_project_id="octopus", ) + + +@pytest.mark.parametrize( + "transport_class", + [transports.SubscriberGrpcTransport, transports.SubscriberGrpcAsyncIOTransport,], +) +@requires_google_auth_lt_1_25_0 +def test_subscriber_transport_auth_adc_old_google_auth(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") adc.assert_called_once_with( scopes=( "https://www.googleapis.com/auth/cloud-platform", @@ -4141,12 +4027,128 @@ def test_subscriber_transport_auth_adc(): ) +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.SubscriberGrpcTransport, grpc_helpers), + (transports.SubscriberGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_gte_1_26_0 +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), + ("grpc.keepalive_time_ms", 30000), + ], + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.SubscriberGrpcTransport, grpc_helpers), + (transports.SubscriberGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_subscriber_transport_create_channel_old_api_core( + 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") + + create_channel.assert_called_with( + "pubsub.googleapis.com", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/pubsub", + ), + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ("grpc.keepalive_time_ms", 30000), + ], + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.SubscriberGrpcTransport, grpc_helpers), + (transports.SubscriberGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_subscriber_transport_create_channel_user_scopes(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", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + scopes=["1", "2"], + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ("grpc.keepalive_time_ms", 30000), + ], + ) + + @pytest.mark.parametrize( "transport_class", [transports.SubscriberGrpcTransport, transports.SubscriberGrpcAsyncIOTransport], ) def test_subscriber_grpc_transport_client_cert_source_for_mtls(transport_class): - cred = credentials.AnonymousCredentials() + cred = ga_credentials.AnonymousCredentials() # Check ssl_channel_credentials is used if provided. with mock.patch.object(transport_class, "create_channel") as mock_create_channel: @@ -4189,7 +4191,7 @@ def test_subscriber_grpc_transport_client_cert_source_for_mtls(transport_class): def test_subscriber_host_no_port(): client = SubscriberClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="pubsub.googleapis.com" ), @@ -4199,7 +4201,7 @@ def test_subscriber_host_no_port(): def test_subscriber_host_with_port(): client = SubscriberClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="pubsub.googleapis.com:8000" ), @@ -4250,9 +4252,9 @@ def test_subscriber_transport_channel_mtls_with_client_cert_source(transport_cla mock_grpc_channel = mock.Mock() grpc_create_channel.return_value = mock_grpc_channel - cred = credentials.AnonymousCredentials() + cred = ga_credentials.AnonymousCredentials() with pytest.warns(DeprecationWarning): - with mock.patch.object(auth, "default") as adc: + with mock.patch.object(google.auth, "default") as adc: adc.return_value = (cred, None) transport = transport_class( host="squid.clam.whelk", @@ -4334,7 +4336,6 @@ def test_subscriber_transport_channel_mtls_with_adc(transport_class): def test_snapshot_path(): project = "squid" snapshot = "clam" - expected = "projects/{project}/snapshots/{snapshot}".format( project=project, snapshot=snapshot, ) @@ -4357,7 +4358,6 @@ def test_parse_snapshot_path(): def test_subscription_path(): project = "oyster" subscription = "nudibranch" - expected = "projects/{project}/subscriptions/{subscription}".format( project=project, subscription=subscription, ) @@ -4380,7 +4380,6 @@ def test_parse_subscription_path(): 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 @@ -4400,7 +4399,6 @@ def test_parse_topic_path(): def test_common_billing_account_path(): billing_account = "squid" - expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -4421,7 +4419,6 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): folder = "whelk" - expected = "folders/{folder}".format(folder=folder,) actual = SubscriberClient.common_folder_path(folder) assert expected == actual @@ -4440,7 +4437,6 @@ def test_parse_common_folder_path(): def test_common_organization_path(): organization = "oyster" - expected = "organizations/{organization}".format(organization=organization,) actual = SubscriberClient.common_organization_path(organization) assert expected == actual @@ -4459,7 +4455,6 @@ def test_parse_common_organization_path(): def test_common_project_path(): project = "cuttlefish" - expected = "projects/{project}".format(project=project,) actual = SubscriberClient.common_project_path(project) assert expected == actual @@ -4479,7 +4474,6 @@ def test_parse_common_project_path(): def test_common_location_path(): project = "winkle" location = "nautilus" - expected = "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -4506,7 +4500,7 @@ def test_client_withDEFAULT_CLIENT_INFO(): transports.SubscriberTransport, "_prep_wrapped_messages" ) as prep: client = SubscriberClient( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) @@ -4515,24 +4509,24 @@ def test_client_withDEFAULT_CLIENT_INFO(): ) as prep: transport_class = SubscriberClient.get_transport_class() transport = transport_class( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + 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=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional 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.SetIamPolicyRequest() + 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.Policy(version=774, etag=b"etag_blob",) + call.return_value = policy_pb2.Policy(version=774, etag=b"etag_blob",) response = client.set_iam_policy(request) @@ -4543,7 +4537,7 @@ def test_set_iam_policy(transport: str = "grpc"): assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, policy.Policy) + assert isinstance(response, policy_pb2.Policy) assert response.version == 774 @@ -4553,18 +4547,18 @@ def test_set_iam_policy(transport: str = "grpc"): @pytest.mark.asyncio async def test_set_iam_policy_async(transport: str = "grpc_asyncio"): client = SubscriberAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional 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.SetIamPolicyRequest() + 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.Policy(version=774, etag=b"etag_blob",) + policy_pb2.Policy(version=774, etag=b"etag_blob",) ) response = await client.set_iam_policy(request) @@ -4576,7 +4570,7 @@ async def test_set_iam_policy_async(transport: str = "grpc_asyncio"): assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, policy.Policy) + assert isinstance(response, policy_pb2.Policy) assert response.version == 774 @@ -4584,16 +4578,16 @@ async def test_set_iam_policy_async(transport: str = "grpc_asyncio"): def test_set_iam_policy_field_headers(): - client = SubscriberClient(credentials=credentials.AnonymousCredentials(),) + 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.SetIamPolicyRequest() + 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.Policy() + call.return_value = policy_pb2.Policy() client.set_iam_policy(request) @@ -4609,16 +4603,16 @@ def test_set_iam_policy_field_headers(): @pytest.mark.asyncio async def test_set_iam_policy_field_headers_async(): - client = SubscriberAsyncClient(credentials=credentials.AnonymousCredentials(),) + 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.SetIamPolicyRequest() + 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.Policy()) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) await client.set_iam_policy(request) @@ -4633,16 +4627,16 @@ async def test_set_iam_policy_field_headers_async(): def test_set_iam_policy_from_dict(): - client = SubscriberClient(credentials=credentials.AnonymousCredentials(),) + 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.Policy() + call.return_value = policy_pb2.Policy() response = client.set_iam_policy( request={ "resource": "resource_value", - "policy": policy.Policy(version=774), + "policy": policy_pb2.Policy(version=774), } ) call.assert_called() @@ -4650,16 +4644,16 @@ def test_set_iam_policy_from_dict(): @pytest.mark.asyncio async def test_set_iam_policy_from_dict_async(): - client = SubscriberAsyncClient(credentials=credentials.AnonymousCredentials(),) + 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.Policy()) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) response = await client.set_iam_policy( request={ "resource": "resource_value", - "policy": policy.Policy(version=774), + "policy": policy_pb2.Policy(version=774), } ) call.assert_called() @@ -4667,17 +4661,17 @@ async def test_set_iam_policy_from_dict_async(): def test_get_iam_policy(transport: str = "grpc"): client = SubscriberClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional 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.GetIamPolicyRequest() + 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.Policy(version=774, etag=b"etag_blob",) + call.return_value = policy_pb2.Policy(version=774, etag=b"etag_blob",) response = client.get_iam_policy(request) @@ -4688,7 +4682,7 @@ def test_get_iam_policy(transport: str = "grpc"): assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, policy.Policy) + assert isinstance(response, policy_pb2.Policy) assert response.version == 774 @@ -4698,18 +4692,18 @@ def test_get_iam_policy(transport: str = "grpc"): @pytest.mark.asyncio async def test_get_iam_policy_async(transport: str = "grpc_asyncio"): client = SubscriberAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional 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.GetIamPolicyRequest() + 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.Policy(version=774, etag=b"etag_blob",) + policy_pb2.Policy(version=774, etag=b"etag_blob",) ) response = await client.get_iam_policy(request) @@ -4721,7 +4715,7 @@ async def test_get_iam_policy_async(transport: str = "grpc_asyncio"): assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, policy.Policy) + assert isinstance(response, policy_pb2.Policy) assert response.version == 774 @@ -4729,16 +4723,16 @@ async def test_get_iam_policy_async(transport: str = "grpc_asyncio"): def test_get_iam_policy_field_headers(): - client = SubscriberClient(credentials=credentials.AnonymousCredentials(),) + 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.GetIamPolicyRequest() + 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.Policy() + call.return_value = policy_pb2.Policy() client.get_iam_policy(request) @@ -4754,16 +4748,16 @@ def test_get_iam_policy_field_headers(): @pytest.mark.asyncio async def test_get_iam_policy_field_headers_async(): - client = SubscriberAsyncClient(credentials=credentials.AnonymousCredentials(),) + 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.GetIamPolicyRequest() + 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.Policy()) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) await client.get_iam_policy(request) @@ -4778,16 +4772,16 @@ async def test_get_iam_policy_field_headers_async(): def test_get_iam_policy_from_dict(): - client = SubscriberClient(credentials=credentials.AnonymousCredentials(),) + 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.Policy() + call.return_value = policy_pb2.Policy() response = client.get_iam_policy( request={ "resource": "resource_value", - "options": options.GetPolicyOptions(requested_policy_version=2598), + "options": options_pb2.GetPolicyOptions(requested_policy_version=2598), } ) call.assert_called() @@ -4795,16 +4789,16 @@ def test_get_iam_policy_from_dict(): @pytest.mark.asyncio async def test_get_iam_policy_from_dict_async(): - client = SubscriberAsyncClient(credentials=credentials.AnonymousCredentials(),) + 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.Policy()) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) response = await client.get_iam_policy( request={ "resource": "resource_value", - "options": options.GetPolicyOptions(requested_policy_version=2598), + "options": options_pb2.GetPolicyOptions(requested_policy_version=2598), } ) call.assert_called() @@ -4812,19 +4806,19 @@ async def test_get_iam_policy_from_dict_async(): def test_test_iam_permissions(transport: str = "grpc"): client = SubscriberClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional 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.TestIamPermissionsRequest() + 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.TestIamPermissionsResponse( + call.return_value = iam_policy_pb2.TestIamPermissionsResponse( permissions=["permissions_value"], ) @@ -4837,7 +4831,7 @@ def test_test_iam_permissions(transport: str = "grpc"): assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, iam_policy.TestIamPermissionsResponse) + assert isinstance(response, iam_policy_pb2.TestIamPermissionsResponse) assert response.permissions == ["permissions_value"] @@ -4845,12 +4839,12 @@ def test_test_iam_permissions(transport: str = "grpc"): @pytest.mark.asyncio async def test_test_iam_permissions_async(transport: str = "grpc_asyncio"): client = SubscriberAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional 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.TestIamPermissionsRequest() + request = iam_policy_pb2.TestIamPermissionsRequest() # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -4858,7 +4852,9 @@ async def test_test_iam_permissions_async(transport: str = "grpc_asyncio"): ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - iam_policy.TestIamPermissionsResponse(permissions=["permissions_value"],) + iam_policy_pb2.TestIamPermissionsResponse( + permissions=["permissions_value"], + ) ) response = await client.test_iam_permissions(request) @@ -4870,24 +4866,24 @@ async def test_test_iam_permissions_async(transport: str = "grpc_asyncio"): assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, iam_policy.TestIamPermissionsResponse) + assert isinstance(response, iam_policy_pb2.TestIamPermissionsResponse) assert response.permissions == ["permissions_value"] def test_test_iam_permissions_field_headers(): - client = SubscriberClient(credentials=credentials.AnonymousCredentials(),) + 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.TestIamPermissionsRequest() + 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.TestIamPermissionsResponse() + call.return_value = iam_policy_pb2.TestIamPermissionsResponse() client.test_iam_permissions(request) @@ -4903,11 +4899,11 @@ def test_test_iam_permissions_field_headers(): @pytest.mark.asyncio async def test_test_iam_permissions_field_headers_async(): - client = SubscriberAsyncClient(credentials=credentials.AnonymousCredentials(),) + 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.TestIamPermissionsRequest() + request = iam_policy_pb2.TestIamPermissionsRequest() request.resource = "resource/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -4915,7 +4911,7 @@ async def test_test_iam_permissions_field_headers_async(): type(client.transport.test_iam_permissions), "__call__" ) as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - iam_policy.TestIamPermissionsResponse() + iam_policy_pb2.TestIamPermissionsResponse() ) await client.test_iam_permissions(request) @@ -4931,13 +4927,13 @@ async def test_test_iam_permissions_field_headers_async(): def test_test_iam_permissions_from_dict(): - client = SubscriberClient(credentials=credentials.AnonymousCredentials(),) + 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.TestIamPermissionsResponse() + call.return_value = iam_policy_pb2.TestIamPermissionsResponse() response = client.test_iam_permissions( request={ @@ -4950,14 +4946,14 @@ def test_test_iam_permissions_from_dict(): @pytest.mark.asyncio async def test_test_iam_permissions_from_dict_async(): - client = SubscriberAsyncClient(credentials=credentials.AnonymousCredentials(),) + 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.TestIamPermissionsResponse() + iam_policy_pb2.TestIamPermissionsResponse() ) response = await client.test_iam_permissions( From 3388c76c474a6b5c538fe9b951c76b4d421c0440 Mon Sep 17 00:00:00 2001 From: yoshi-automation Date: Sun, 18 Jul 2021 04:55:00 +0000 Subject: [PATCH 07/18] chore: upgrade gapic-generator-python to 0.46.1 PiperOrigin-RevId: 373400747 Source-Author: Google APIs Source-Date: Wed May 12 10:34:35 2021 -0700 Source-Repo: googleapis/googleapis Source-Sha: 162641cfe5573c648df679a6dd30385650a08704 Source-Link: https://github.com/googleapis/googleapis/commit/162641cfe5573c648df679a6dd30385650a08704 --- examples/feature_fragments | 14 -------------- google/pubsub_v1/__init__.py | 3 +++ synth.metadata | 5 ++--- 3 files changed, 5 insertions(+), 17 deletions(-) delete mode 100644 examples/feature_fragments diff --git a/examples/feature_fragments b/examples/feature_fragments deleted file mode 100644 index 7d1b62477..000000000 --- a/examples/feature_fragments +++ /dev/null @@ -1,14 +0,0 @@ - - - - - - - - - - - - - -} diff --git a/google/pubsub_v1/__init__.py b/google/pubsub_v1/__init__.py index 500c756b8..bc78db26f 100644 --- a/google/pubsub_v1/__init__.py +++ b/google/pubsub_v1/__init__.py @@ -79,6 +79,9 @@ from .types.schema import SchemaView __all__ = ( + "PublisherAsyncClient", + "SchemaServiceAsyncClient", + "SubscriberAsyncClient", "AcknowledgeRequest", "CreateSchemaRequest", "CreateSnapshotRequest", diff --git a/synth.metadata b/synth.metadata index 14ace7289..fc397d680 100644 --- a/synth.metadata +++ b/synth.metadata @@ -11,8 +11,8 @@ "git": { "name": "googleapis", "remote": "https://github.com/googleapis/googleapis.git", - "sha": "83a7e1c8c2f7421ded45ed323eb1fda99ef5ea46", - "internalRef": "372197450" + "sha": "162641cfe5573c648df679a6dd30385650a08704", + "internalRef": "373400747" } } ], @@ -93,7 +93,6 @@ "docs/_templates/layout.html", "docs/conf.py", "docs/multiprocessing.rst", - "examples/feature_fragments", "google/cloud/pubsub_v1/proto/pubsub.proto", "google/cloud/pubsub_v1/proto/schema.proto", "google/pubsub/__init__.py", From 686667277fc0d1c21909cfd9c9bd439b7e803f4b Mon Sep 17 00:00:00 2001 From: yoshi-automation Date: Sun, 18 Jul 2021 04:57:27 +0000 Subject: [PATCH 08/18] chore: upgrade gapic-generator-python to 0.46.3 PiperOrigin-RevId: 373649163 Source-Author: Google APIs Source-Date: Thu May 13 13:40:36 2021 -0700 Source-Repo: googleapis/googleapis Source-Sha: 7e1b14e6c7a9ab96d2db7e4a131981f162446d34 Source-Link: https://github.com/googleapis/googleapis/commit/7e1b14e6c7a9ab96d2db7e4a131981f162446d34 --- .../services/publisher/async_client.py | 76 ++++++++----- google/pubsub_v1/services/publisher/client.py | 99 ++++++++-------- google/pubsub_v1/services/publisher/pagers.py | 6 +- .../services/schema_service/async_client.py | 22 ++-- .../services/schema_service/client.py | 81 +++++++------ .../services/schema_service/pagers.py | 2 +- .../services/subscriber/async_client.py | 106 +++++++++++------- .../pubsub_v1/services/subscriber/client.py | 99 ++++++++-------- .../pubsub_v1/services/subscriber/pagers.py | 4 +- synth.metadata | 4 +- tests/unit/gapic/pubsub_v1/test_publisher.py | 4 +- .../gapic/pubsub_v1/test_schema_service.py | 4 +- tests/unit/gapic/pubsub_v1/test_subscriber.py | 4 +- 13 files changed, 289 insertions(+), 222 deletions(-) diff --git a/google/pubsub_v1/services/publisher/async_client.py b/google/pubsub_v1/services/publisher/async_client.py index 53fa90fb2..09e4b0e55 100644 --- a/google/pubsub_v1/services/publisher/async_client.py +++ b/google/pubsub_v1/services/publisher/async_client.py @@ -74,7 +74,8 @@ class PublisherAsyncClient: @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials info. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -89,7 +90,7 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials - file. + file. Args: filename (str): The path to the service account private key json @@ -106,7 +107,7 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> PublisherTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: PublisherTransport: The transport used by the client instance. @@ -125,7 +126,7 @@ def __init__( client_options: ClientOptions = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: - """Instantiate the publisher client. + """Instantiates the publisher client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -229,7 +230,9 @@ async def create_topic( initial=0.1, maximum=60.0, multiplier=1.3, - predicate=retries.if_exception_type(exceptions.ServiceUnavailable,), + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), deadline=60.0, ), default_timeout=60.0, @@ -284,7 +287,9 @@ async def update_topic( initial=0.1, maximum=60.0, multiplier=1.3, - predicate=retries.if_exception_type(exceptions.ServiceUnavailable,), + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), deadline=60.0, ), default_timeout=60.0, @@ -373,13 +378,13 @@ async def publish( maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.Aborted, - exceptions.Cancelled, - exceptions.DeadlineExceeded, - exceptions.InternalServerError, - exceptions.ResourceExhausted, - exceptions.ServiceUnavailable, - exceptions.Unknown, + core_exceptions.Aborted, + core_exceptions.Cancelled, + core_exceptions.DeadlineExceeded, + core_exceptions.InternalServerError, + core_exceptions.ResourceExhausted, + core_exceptions.ServiceUnavailable, + core_exceptions.Unknown, ), deadline=60.0, ), @@ -457,9 +462,9 @@ async def get_topic( maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.Aborted, - exceptions.ServiceUnavailable, - exceptions.Unknown, + core_exceptions.Aborted, + core_exceptions.ServiceUnavailable, + core_exceptions.Unknown, ), deadline=60.0, ), @@ -541,9 +546,9 @@ async def list_topics( maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.Aborted, - exceptions.ServiceUnavailable, - exceptions.Unknown, + core_exceptions.Aborted, + core_exceptions.ServiceUnavailable, + core_exceptions.Unknown, ), deadline=60.0, ), @@ -634,9 +639,9 @@ async def list_topic_subscriptions( maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.Aborted, - exceptions.ServiceUnavailable, - exceptions.Unknown, + core_exceptions.Aborted, + core_exceptions.ServiceUnavailable, + core_exceptions.Unknown, ), deadline=60.0, ), @@ -731,9 +736,9 @@ async def list_topic_snapshots( maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.Aborted, - exceptions.ServiceUnavailable, - exceptions.Unknown, + core_exceptions.Aborted, + core_exceptions.ServiceUnavailable, + core_exceptions.Unknown, ), deadline=60.0, ), @@ -818,7 +823,9 @@ async def delete_topic( initial=0.1, maximum=60.0, multiplier=1.3, - predicate=retries.if_exception_type(exceptions.ServiceUnavailable,), + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), deadline=60.0, ), default_timeout=60.0, @@ -878,7 +885,9 @@ async def detach_subscription( initial=0.1, maximum=60.0, multiplier=1.3, - predicate=retries.if_exception_type(exceptions.ServiceUnavailable,), + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), deadline=60.0, ), default_timeout=60.0, @@ -907,8 +916,10 @@ async def set_iam_policy( timeout: TimeoutType = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> policy_pb2.Policy: - r"""Sets the IAM access control policy on the specified - function. Replaces any existing policy. + 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` @@ -1015,8 +1026,10 @@ async def get_iam_policy( 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` @@ -1123,8 +1136,11 @@ async def test_iam_permissions( 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 + 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 diff --git a/google/pubsub_v1/services/publisher/client.py b/google/pubsub_v1/services/publisher/client.py index 2e63a1d58..321d9efe3 100644 --- a/google/pubsub_v1/services/publisher/client.py +++ b/google/pubsub_v1/services/publisher/client.py @@ -57,7 +57,7 @@ class PublisherClientMeta(type): _transport_registry["grpc_asyncio"] = PublisherGrpcAsyncIOTransport def get_transport_class(cls, label: str = None,) -> Type[PublisherTransport]: - """Return an appropriate transport class. + """Returns an appropriate transport class. Args: @@ -83,7 +83,8 @@ class PublisherClient(metaclass=PublisherClientMeta): @staticmethod def _get_default_mtls_endpoint(api_endpoint): - """Convert api endpoint to mTLS endpoint. + """Converts api endpoint to mTLS endpoint. + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. @@ -111,16 +112,6 @@ def _get_default_mtls_endpoint(api_endpoint): return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") - # The scopes needed to make gRPC calls to all of the methods defined in - # this service - _DEFAULT_SCOPES = ( - "https://www.googleapis.com/auth/cloud-platform", - "https://www.googleapis.com/auth/pubsub", - ) - - SERVICE_ADDRESS = "pubsub.googleapis.com:443" - """The default address of the service.""" - DEFAULT_ENDPOINT = "pubsub.googleapis.com" DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore DEFAULT_ENDPOINT @@ -128,7 +119,8 @@ def _get_default_mtls_endpoint(api_endpoint): @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials info. + """Creates an instance of this client using the provided credentials + info. Args: @@ -146,7 +138,7 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials - file. + file. Args: @@ -166,36 +158,37 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> PublisherTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: - PublisherTransport: The transport used by the client instance. + PublisherTransport: The transport used by the client + instance. """ return self._transport @staticmethod def schema_path(project: str, schema: str,) -> str: - """Return a fully-qualified schema string.""" + """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]: - """Parse a schema path into its component segments.""" + """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: - """Return a fully-qualified subscription string.""" + """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]: - """Parse a subscription path into its component segments.""" + """Parses a subscription path into its component segments.""" m = re.match( r"^projects/(?P.+?)/subscriptions/(?P.+?)$", path ) @@ -203,18 +196,18 @@ def parse_subscription_path(path: str) -> Dict[str, str]: @staticmethod def topic_path(project: str, topic: str,) -> str: - """Return a fully-qualified topic string.""" + """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]: - """Parse a topic path into its component segments.""" + """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: - """Return a fully-qualified billing_account string.""" + """Returns a fully-qualified billing_account string.""" return "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -227,7 +220,7 @@ def parse_common_billing_account_path(path: str) -> Dict[str, str]: @staticmethod def common_folder_path(folder: str,) -> str: - """Return a fully-qualified folder string.""" + """Returns a fully-qualified folder string.""" return "folders/{folder}".format(folder=folder,) @staticmethod @@ -238,7 +231,7 @@ def parse_common_folder_path(path: str) -> Dict[str, str]: @staticmethod def common_organization_path(organization: str,) -> str: - """Return a fully-qualified organization string.""" + """Returns a fully-qualified organization string.""" return "organizations/{organization}".format(organization=organization,) @staticmethod @@ -249,7 +242,7 @@ def parse_common_organization_path(path: str) -> Dict[str, str]: @staticmethod def common_project_path(project: str,) -> str: - """Return a fully-qualified project string.""" + """Returns a fully-qualified project string.""" return "projects/{project}".format(project=project,) @staticmethod @@ -260,7 +253,7 @@ def parse_common_project_path(path: str) -> Dict[str, str]: @staticmethod def common_location_path(project: str, location: str,) -> str: - """Return a fully-qualified location string.""" + """Returns a fully-qualified location string.""" return "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -279,7 +272,7 @@ def __init__( client_options: Optional[client_options_lib.ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: - """Instantiate the publisher client. + """Instantiates the publisher client. Args: @@ -335,9 +328,10 @@ def __init__( client_cert_source_func = client_options.client_cert_source else: is_mtls = mtls.has_default_client_cert_source() - client_cert_source_func = ( - mtls.default_client_cert_source() if is_mtls else None - ) + if is_mtls: + client_cert_source_func = mtls.default_client_cert_source() + else: + client_cert_source_func = None # Figure out which api endpoint to use. if client_options.api_endpoint is not None: @@ -349,12 +343,14 @@ def __init__( elif use_mtls_env == "always": api_endpoint = self.DEFAULT_MTLS_ENDPOINT elif use_mtls_env == "auto": - api_endpoint = ( - self.DEFAULT_MTLS_ENDPOINT if is_mtls else self.DEFAULT_ENDPOINT - ) + if is_mtls: + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = self.DEFAULT_ENDPOINT else: raise MutualTLSChannelError( - "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted values: never, auto, always" + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " + "values: never, auto, always" ) # Save or instantiate the transport. @@ -369,8 +365,8 @@ def __init__( ) if client_options.scopes: raise ValueError( - "When providing a transport instance, " - "provide its scopes directly." + "When providing a transport instance, provide its scopes " + "directly." ) self._transport = transport else: @@ -1061,8 +1057,10 @@ def set_iam_policy( timeout: TimeoutType = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> policy_pb2.Policy: - r"""Sets the IAM access control policy on the specified - function. Replaces any existing policy. + r"""Sets the IAM access control policy on the specified function. + + Replaces any existing policy. + Args: request (:class:`~.iam_policy_pb2.SetIamPolicyRequest`): @@ -1173,15 +1171,17 @@ def get_iam_policy( 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. + + 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. + retry (google.api_core.retry.Retry): Designation of what errors, if + any, should be retried. timeout (TimeoutType): The timeout for this request. metadata (Sequence[Tuple[str, str]]): Strings which should be @@ -1284,16 +1284,19 @@ def test_iam_permissions( timeout: TimeoutType = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> iam_policy_pb2.TestIamPermissionsResponse: - r"""Tests the specified permissions against the IAM access control - policy for a function. If the function does not exist, this will - return an empty set of permissions, not a NOT_FOUND error. + 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. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. timeout (TimeoutType): The timeout for this request. metadata (Sequence[Tuple[str, str]]): Strings which should be diff --git a/google/pubsub_v1/services/publisher/pagers.py b/google/pubsub_v1/services/publisher/pagers.py index 592e3d507..1a826de78 100644 --- a/google/pubsub_v1/services/publisher/pagers.py +++ b/google/pubsub_v1/services/publisher/pagers.py @@ -115,7 +115,7 @@ def __init__( *, metadata: Sequence[Tuple[str, str]] = () ): - """Instantiate the pager. + """Instantiates the pager. Args: method (Callable): The method that was originally called, and @@ -243,7 +243,7 @@ def __init__( *, metadata: Sequence[Tuple[str, str]] = () ): - """Instantiate the pager. + """Instantiates the pager. Args: method (Callable): The method that was originally called, and @@ -371,7 +371,7 @@ def __init__( *, metadata: Sequence[Tuple[str, str]] = () ): - """Instantiate the pager. + """Instantiates the pager. Args: method (Callable): The method that was originally called, and diff --git a/google/pubsub_v1/services/schema_service/async_client.py b/google/pubsub_v1/services/schema_service/async_client.py index c2d6e9c7b..6ec1fe667 100644 --- a/google/pubsub_v1/services/schema_service/async_client.py +++ b/google/pubsub_v1/services/schema_service/async_client.py @@ -73,7 +73,8 @@ class SchemaServiceAsyncClient: @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials info. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -88,7 +89,7 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials - file. + file. Args: filename (str): The path to the service account private key json @@ -105,7 +106,7 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> SchemaServiceTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: SchemaServiceTransport: The transport used by the client instance. @@ -124,7 +125,7 @@ def __init__( client_options: ClientOptions = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: - """Instantiate the schema service client. + """Instantiates the schema service client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -603,8 +604,10 @@ async def set_iam_policy( 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. + 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` @@ -710,8 +713,10 @@ async def get_iam_policy( 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` @@ -817,8 +822,11 @@ async def test_iam_permissions( 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 + 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 diff --git a/google/pubsub_v1/services/schema_service/client.py b/google/pubsub_v1/services/schema_service/client.py index 3fe5f64ff..106afa850 100644 --- a/google/pubsub_v1/services/schema_service/client.py +++ b/google/pubsub_v1/services/schema_service/client.py @@ -53,7 +53,7 @@ class SchemaServiceClientMeta(type): _transport_registry["grpc_asyncio"] = SchemaServiceGrpcAsyncIOTransport def get_transport_class(cls, label: str = None,) -> Type[SchemaServiceTransport]: - """Return an appropriate transport class. + """Returns an appropriate transport class. Args: label: The name of the desired transport. If none is @@ -76,7 +76,8 @@ class SchemaServiceClient(metaclass=SchemaServiceClientMeta): @staticmethod def _get_default_mtls_endpoint(api_endpoint): - """Convert api endpoint to mTLS 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: @@ -110,7 +111,8 @@ def _get_default_mtls_endpoint(api_endpoint): @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials info. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -127,7 +129,7 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials - file. + file. Args: filename (str): The path to the service account private key json @@ -146,29 +148,30 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> SchemaServiceTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: - SchemaServiceTransport: The transport used by the client instance. + SchemaServiceTransport: The transport used by the client + instance. """ return self._transport @staticmethod def schema_path(project: str, schema: str,) -> str: - """Return a fully-qualified schema string.""" + """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]: - """Parse a schema path into its component segments.""" + """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: - """Return a fully-qualified billing_account string.""" + """Returns a fully-qualified billing_account string.""" return "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -181,7 +184,7 @@ def parse_common_billing_account_path(path: str) -> Dict[str, str]: @staticmethod def common_folder_path(folder: str,) -> str: - """Return a fully-qualified folder string.""" + """Returns a fully-qualified folder string.""" return "folders/{folder}".format(folder=folder,) @staticmethod @@ -192,7 +195,7 @@ def parse_common_folder_path(path: str) -> Dict[str, str]: @staticmethod def common_organization_path(organization: str,) -> str: - """Return a fully-qualified organization string.""" + """Returns a fully-qualified organization string.""" return "organizations/{organization}".format(organization=organization,) @staticmethod @@ -203,7 +206,7 @@ def parse_common_organization_path(path: str) -> Dict[str, str]: @staticmethod def common_project_path(project: str,) -> str: - """Return a fully-qualified project string.""" + """Returns a fully-qualified project string.""" return "projects/{project}".format(project=project,) @staticmethod @@ -214,7 +217,7 @@ def parse_common_project_path(path: str) -> Dict[str, str]: @staticmethod def common_location_path(project: str, location: str,) -> str: - """Return a fully-qualified location string.""" + """Returns a fully-qualified location string.""" return "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -233,7 +236,7 @@ def __init__( client_options: Optional[client_options_lib.ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: - """Instantiate the schema service client. + """Instantiates the schema service client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -288,9 +291,10 @@ def __init__( client_cert_source_func = client_options.client_cert_source else: is_mtls = mtls.has_default_client_cert_source() - client_cert_source_func = ( - mtls.default_client_cert_source() if is_mtls else None - ) + if is_mtls: + client_cert_source_func = mtls.default_client_cert_source() + else: + client_cert_source_func = None # Figure out which api endpoint to use. if client_options.api_endpoint is not None: @@ -302,12 +306,14 @@ def __init__( elif use_mtls_env == "always": api_endpoint = self.DEFAULT_MTLS_ENDPOINT elif use_mtls_env == "auto": - api_endpoint = ( - self.DEFAULT_MTLS_ENDPOINT if is_mtls else self.DEFAULT_ENDPOINT - ) + if is_mtls: + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = self.DEFAULT_ENDPOINT else: raise MutualTLSChannelError( - "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted values: never, auto, always" + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " + "values: never, auto, always" ) # Save or instantiate the transport. @@ -322,8 +328,8 @@ def __init__( ) if client_options.scopes: raise ValueError( - "When providing a transport instance, " - "provide its scopes directly." + "When providing a transport instance, provide its scopes " + "directly." ) self._transport = transport else: @@ -779,8 +785,10 @@ def set_iam_policy( 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. + 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` @@ -886,14 +894,16 @@ def get_iam_policy( 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. + + 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. + retry (google.api_core.retry.Retry): Designation of what errors, if + any, should be retried. timeout (float): The timeout for this request. metadata (Sequence[Tuple[str, str]]): Strings which should be sent along with the request as metadata. @@ -992,15 +1002,18 @@ def test_iam_permissions( 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. + 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. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. timeout (float): The timeout for this request. metadata (Sequence[Tuple[str, str]]): Strings which should be sent along with the request as metadata. diff --git a/google/pubsub_v1/services/schema_service/pagers.py b/google/pubsub_v1/services/schema_service/pagers.py index a6bf1ccc0..f0248bf5e 100644 --- a/google/pubsub_v1/services/schema_service/pagers.py +++ b/google/pubsub_v1/services/schema_service/pagers.py @@ -115,7 +115,7 @@ def __init__( *, metadata: Sequence[Tuple[str, str]] = () ): - """Instantiate the pager. + """Instantiates the pager. Args: method (Callable): The method that was originally called, and diff --git a/google/pubsub_v1/services/subscriber/async_client.py b/google/pubsub_v1/services/subscriber/async_client.py index 589fc090a..502f6f158 100644 --- a/google/pubsub_v1/services/subscriber/async_client.py +++ b/google/pubsub_v1/services/subscriber/async_client.py @@ -86,7 +86,8 @@ class SubscriberAsyncClient: @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials info. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -101,7 +102,7 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials - file. + file. Args: filename (str): The path to the service account private key json @@ -118,7 +119,7 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> SubscriberTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: SubscriberTransport: The transport used by the client instance. @@ -137,7 +138,7 @@ def __init__( client_options: ClientOptions = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: - """Instantiate the subscriber client. + """Instantiates the subscriber client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -309,9 +310,9 @@ async def create_subscription( maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.Aborted, - exceptions.ServiceUnavailable, - exceptions.Unknown, + core_exceptions.Aborted, + core_exceptions.ServiceUnavailable, + core_exceptions.Unknown, ), deadline=60.0, ), @@ -389,9 +390,9 @@ async def get_subscription( maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.Aborted, - exceptions.ServiceUnavailable, - exceptions.Unknown, + core_exceptions.Aborted, + core_exceptions.ServiceUnavailable, + core_exceptions.Unknown, ), deadline=60.0, ), @@ -450,7 +451,9 @@ async def update_subscription( initial=0.1, maximum=60.0, multiplier=1.3, - predicate=retries.if_exception_type(exceptions.ServiceUnavailable,), + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), deadline=60.0, ), default_timeout=60.0, @@ -533,9 +536,9 @@ async def list_subscriptions( maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.Aborted, - exceptions.ServiceUnavailable, - exceptions.Unknown, + core_exceptions.Aborted, + core_exceptions.ServiceUnavailable, + core_exceptions.Unknown, ), deadline=60.0, ), @@ -619,7 +622,9 @@ async def delete_subscription( initial=0.1, maximum=60.0, multiplier=1.3, - predicate=retries.if_exception_type(exceptions.ServiceUnavailable,), + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), deadline=60.0, ), default_timeout=60.0, @@ -724,7 +729,9 @@ async def modify_ack_deadline( initial=0.1, maximum=60.0, multiplier=1.3, - predicate=retries.if_exception_type(exceptions.ServiceUnavailable,), + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), deadline=60.0, ), default_timeout=60.0, @@ -815,7 +822,9 @@ async def acknowledge( initial=0.1, maximum=60.0, multiplier=1.3, - predicate=retries.if_exception_type(exceptions.ServiceUnavailable,), + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), deadline=60.0, ), default_timeout=60.0, @@ -931,9 +940,9 @@ async def pull( maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.Aborted, - exceptions.ServiceUnavailable, - exceptions.Unknown, + core_exceptions.Aborted, + core_exceptions.ServiceUnavailable, + core_exceptions.Unknown, ), deadline=60.0, ), @@ -1001,11 +1010,11 @@ def streaming_pull( maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.Aborted, - exceptions.DeadlineExceeded, - exceptions.InternalServerError, - exceptions.ResourceExhausted, - exceptions.ServiceUnavailable, + core_exceptions.Aborted, + core_exceptions.DeadlineExceeded, + core_exceptions.InternalServerError, + core_exceptions.ResourceExhausted, + core_exceptions.ServiceUnavailable, ), deadline=900.0, ), @@ -1093,7 +1102,9 @@ async def modify_push_config( initial=0.1, maximum=60.0, multiplier=1.3, - predicate=retries.if_exception_type(exceptions.ServiceUnavailable,), + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), deadline=60.0, ), default_timeout=60.0, @@ -1182,9 +1193,9 @@ async def get_snapshot( maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.Aborted, - exceptions.ServiceUnavailable, - exceptions.Unknown, + core_exceptions.Aborted, + core_exceptions.ServiceUnavailable, + core_exceptions.Unknown, ), deadline=60.0, ), @@ -1270,9 +1281,9 @@ async def list_snapshots( maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.Aborted, - exceptions.ServiceUnavailable, - exceptions.Unknown, + core_exceptions.Aborted, + core_exceptions.ServiceUnavailable, + core_exceptions.Unknown, ), deadline=60.0, ), @@ -1402,7 +1413,9 @@ async def create_snapshot( initial=0.1, maximum=60.0, multiplier=1.3, - predicate=retries.if_exception_type(exceptions.ServiceUnavailable,), + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), deadline=60.0, ), default_timeout=60.0, @@ -1468,7 +1481,9 @@ async def update_snapshot( initial=0.1, maximum=60.0, multiplier=1.3, - predicate=retries.if_exception_type(exceptions.ServiceUnavailable,), + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), deadline=60.0, ), default_timeout=60.0, @@ -1551,7 +1566,9 @@ async def delete_snapshot( initial=0.1, maximum=60.0, multiplier=1.3, - predicate=retries.if_exception_type(exceptions.ServiceUnavailable,), + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), deadline=60.0, ), default_timeout=60.0, @@ -1612,9 +1629,9 @@ async def seek( maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.Aborted, - exceptions.ServiceUnavailable, - exceptions.Unknown, + core_exceptions.Aborted, + core_exceptions.ServiceUnavailable, + core_exceptions.Unknown, ), deadline=60.0, ), @@ -1644,8 +1661,10 @@ async def set_iam_policy( 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. + 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` @@ -1751,8 +1770,10 @@ async def get_iam_policy( 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` @@ -1858,8 +1879,11 @@ async def test_iam_permissions( 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 + 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 diff --git a/google/pubsub_v1/services/subscriber/client.py b/google/pubsub_v1/services/subscriber/client.py index 1c69f3b41..4c307f462 100644 --- a/google/pubsub_v1/services/subscriber/client.py +++ b/google/pubsub_v1/services/subscriber/client.py @@ -68,7 +68,7 @@ class SubscriberClientMeta(type): _transport_registry["grpc_asyncio"] = SubscriberGrpcAsyncIOTransport def get_transport_class(cls, label: str = None,) -> Type[SubscriberTransport]: - """Return an appropriate transport class. + """Returns an appropriate transport class. Args: @@ -96,7 +96,8 @@ class SubscriberClient(metaclass=SubscriberClientMeta): @staticmethod def _get_default_mtls_endpoint(api_endpoint): - """Convert api endpoint to mTLS endpoint. + """Converts api endpoint to mTLS endpoint. + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. @@ -124,16 +125,6 @@ def _get_default_mtls_endpoint(api_endpoint): return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") - # The scopes needed to make gRPC calls to all of the methods defined in - # this service - _DEFAULT_SCOPES = ( - "https://www.googleapis.com/auth/cloud-platform", - "https://www.googleapis.com/auth/pubsub", - ) - - SERVICE_ADDRESS = "pubsub.googleapis.com:443" - """The default address of the service.""" - DEFAULT_ENDPOINT = "pubsub.googleapis.com" DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore DEFAULT_ENDPOINT @@ -141,7 +132,8 @@ def _get_default_mtls_endpoint(api_endpoint): @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials info. + """Creates an instance of this client using the provided credentials + info. Args: @@ -159,7 +151,7 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials - file. + file. Args: @@ -179,36 +171,37 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> SubscriberTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: - SubscriberTransport: The transport used by the client instance. + SubscriberTransport: The transport used by the client + instance. """ return self._transport @staticmethod def snapshot_path(project: str, snapshot: str,) -> str: - """Return a fully-qualified snapshot string.""" + """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]: - """Parse a snapshot path into its component segments.""" + """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: - """Return a fully-qualified subscription string.""" + """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]: - """Parse a subscription path into its component segments.""" + """Parses a subscription path into its component segments.""" m = re.match( r"^projects/(?P.+?)/subscriptions/(?P.+?)$", path ) @@ -216,18 +209,18 @@ def parse_subscription_path(path: str) -> Dict[str, str]: @staticmethod def topic_path(project: str, topic: str,) -> str: - """Return a fully-qualified topic string.""" + """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]: - """Parse a topic path into its component segments.""" + """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: - """Return a fully-qualified billing_account string.""" + """Returns a fully-qualified billing_account string.""" return "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -240,7 +233,7 @@ def parse_common_billing_account_path(path: str) -> Dict[str, str]: @staticmethod def common_folder_path(folder: str,) -> str: - """Return a fully-qualified folder string.""" + """Returns a fully-qualified folder string.""" return "folders/{folder}".format(folder=folder,) @staticmethod @@ -251,7 +244,7 @@ def parse_common_folder_path(path: str) -> Dict[str, str]: @staticmethod def common_organization_path(organization: str,) -> str: - """Return a fully-qualified organization string.""" + """Returns a fully-qualified organization string.""" return "organizations/{organization}".format(organization=organization,) @staticmethod @@ -262,7 +255,7 @@ def parse_common_organization_path(path: str) -> Dict[str, str]: @staticmethod def common_project_path(project: str,) -> str: - """Return a fully-qualified project string.""" + """Returns a fully-qualified project string.""" return "projects/{project}".format(project=project,) @staticmethod @@ -273,7 +266,7 @@ def parse_common_project_path(path: str) -> Dict[str, str]: @staticmethod def common_location_path(project: str, location: str,) -> str: - """Return a fully-qualified location string.""" + """Returns a fully-qualified location string.""" return "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -292,7 +285,7 @@ def __init__( client_options: Optional[client_options_lib.ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: - """Instantiate the subscriber client. + """Instantiates the subscriber client. Args: @@ -348,9 +341,10 @@ def __init__( client_cert_source_func = client_options.client_cert_source else: is_mtls = mtls.has_default_client_cert_source() - client_cert_source_func = ( - mtls.default_client_cert_source() if is_mtls else None - ) + if is_mtls: + client_cert_source_func = mtls.default_client_cert_source() + else: + client_cert_source_func = None # Figure out which api endpoint to use. if client_options.api_endpoint is not None: @@ -362,12 +356,14 @@ def __init__( elif use_mtls_env == "always": api_endpoint = self.DEFAULT_MTLS_ENDPOINT elif use_mtls_env == "auto": - api_endpoint = ( - self.DEFAULT_MTLS_ENDPOINT if is_mtls else self.DEFAULT_ENDPOINT - ) + if is_mtls: + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = self.DEFAULT_ENDPOINT else: raise MutualTLSChannelError( - "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted values: never, auto, always" + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " + "values: never, auto, always" ) # Save or instantiate the transport. @@ -382,8 +378,8 @@ def __init__( ) if client_options.scopes: raise ValueError( - "When providing a transport instance, " - "provide its scopes directly." + "When providing a transport instance, provide its scopes " + "directly." ) self._transport = transport else: @@ -1749,8 +1745,10 @@ def set_iam_policy( 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. + r"""Sets the IAM access control policy on the specified function. + + Replaces any existing policy. + Args: request (:class:`~.iam_policy_pb2.SetIamPolicyRequest`): @@ -1860,15 +1858,17 @@ def get_iam_policy( 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. + + 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. + retry (google.api_core.retry.Retry): Designation of what errors, if + any, should be retried. timeout (float): The timeout for this request. metadata (Sequence[Tuple[str, str]]): Strings which should be sent along with the request as metadata. @@ -1970,16 +1970,19 @@ def test_iam_permissions( 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. + 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. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. timeout (float): The timeout for this request. metadata (Sequence[Tuple[str, str]]): Strings which should be sent along with the request as metadata. diff --git a/google/pubsub_v1/services/subscriber/pagers.py b/google/pubsub_v1/services/subscriber/pagers.py index 3e0de8ddc..495688522 100644 --- a/google/pubsub_v1/services/subscriber/pagers.py +++ b/google/pubsub_v1/services/subscriber/pagers.py @@ -115,7 +115,7 @@ def __init__( *, metadata: Sequence[Tuple[str, str]] = () ): - """Instantiate the pager. + """Instantiates the pager. Args: method (Callable): The method that was originally called, and @@ -243,7 +243,7 @@ def __init__( *, metadata: Sequence[Tuple[str, str]] = () ): - """Instantiate the pager. + """Instantiates the pager. Args: method (Callable): The method that was originally called, and diff --git a/synth.metadata b/synth.metadata index fc397d680..fc00473b5 100644 --- a/synth.metadata +++ b/synth.metadata @@ -11,8 +11,8 @@ "git": { "name": "googleapis", "remote": "https://github.com/googleapis/googleapis.git", - "sha": "162641cfe5573c648df679a6dd30385650a08704", - "internalRef": "373400747" + "sha": "7e1b14e6c7a9ab96d2db7e4a131981f162446d34", + "internalRef": "373649163" } } ], diff --git a/tests/unit/gapic/pubsub_v1/test_publisher.py b/tests/unit/gapic/pubsub_v1/test_publisher.py index 61af19cc7..048d47ce0 100644 --- a/tests/unit/gapic/pubsub_v1/test_publisher.py +++ b/tests/unit/gapic/pubsub_v1/test_publisher.py @@ -2811,7 +2811,7 @@ def test_publisher_transport_create_channel_old_api_core(transport_class, grpc_h transport_class(quota_project_id="octopus") create_channel.assert_called_with( - "pubsub.googleapis.com", + "pubsub.googleapis.com:443", credentials=creds, credentials_file=None, quota_project_id="octopus", @@ -2850,7 +2850,7 @@ def test_publisher_transport_create_channel_user_scopes(transport_class, grpc_he transport_class(quota_project_id="octopus", scopes=["1", "2"]) create_channel.assert_called_with( - "pubsub.googleapis.com", + "pubsub.googleapis.com:443", credentials=creds, credentials_file=None, quota_project_id="octopus", diff --git a/tests/unit/gapic/pubsub_v1/test_schema_service.py b/tests/unit/gapic/pubsub_v1/test_schema_service.py index ab0f64f47..5f8c44ad2 100644 --- a/tests/unit/gapic/pubsub_v1/test_schema_service.py +++ b/tests/unit/gapic/pubsub_v1/test_schema_service.py @@ -2072,7 +2072,7 @@ def test_schema_service_transport_create_channel_old_api_core( transport_class(quota_project_id="octopus") create_channel.assert_called_with( - "pubsub.googleapis.com", + "pubsub.googleapis.com:443", credentials=creds, credentials_file=None, quota_project_id="octopus", @@ -2113,7 +2113,7 @@ def test_schema_service_transport_create_channel_user_scopes( transport_class(quota_project_id="octopus", scopes=["1", "2"]) create_channel.assert_called_with( - "pubsub.googleapis.com", + "pubsub.googleapis.com:443", credentials=creds, credentials_file=None, quota_project_id="octopus", diff --git a/tests/unit/gapic/pubsub_v1/test_subscriber.py b/tests/unit/gapic/pubsub_v1/test_subscriber.py index eff436cae..447d5b9ba 100644 --- a/tests/unit/gapic/pubsub_v1/test_subscriber.py +++ b/tests/unit/gapic/pubsub_v1/test_subscriber.py @@ -4090,7 +4090,7 @@ def test_subscriber_transport_create_channel_old_api_core( transport_class(quota_project_id="octopus") create_channel.assert_called_with( - "pubsub.googleapis.com", + "pubsub.googleapis.com:443", credentials=creds, credentials_file=None, quota_project_id="octopus", @@ -4129,7 +4129,7 @@ def test_subscriber_transport_create_channel_user_scopes(transport_class, grpc_h transport_class(quota_project_id="octopus", scopes=["1", "2"]) create_channel.assert_called_with( - "pubsub.googleapis.com", + "pubsub.googleapis.com:443", credentials=creds, credentials_file=None, quota_project_id="octopus", From 5bef0ca90875f40c6bfb62122d5675f109f1b9f0 Mon Sep 17 00:00:00 2001 From: yoshi-automation Date: Sun, 18 Jul 2021 05:01:23 +0000 Subject: [PATCH 09/18] chore: remove all monolith Bazel deps chore: release gapic-generator-csharp v1.3.7 chore: release gapic-generator-go 0.20.5 chore: release gapic-generator-java 1.0.14 chore: release gapic-generator-php 1.0.1 chore: release gapic-generator-python 0.50.0 chore: update gapic-generator-ruby to the latest commit chore: release gapic-generator-typescript 1.5.0 Committer: @miraleung PiperOrigin-RevId: 380641501 Source-Author: Google APIs Source-Date: Mon Jun 21 12:42:31 2021 -0700 Source-Repo: googleapis/googleapis Source-Sha: 076f7e9f0b258bdb54338895d7251b202e8f0de3 Source-Link: https://github.com/googleapis/googleapis/commit/076f7e9f0b258bdb54338895d7251b202e8f0de3 --- .../services/publisher/transports/base.py | 40 +++---- .../services/publisher/transports/grpc.py | 7 +- .../publisher/transports/grpc_asyncio.py | 7 +- .../schema_service/transports/base.py | 40 +++---- .../schema_service/transports/grpc.py | 7 +- .../schema_service/transports/grpc_asyncio.py | 7 +- .../services/subscriber/transports/base.py | 40 +++---- .../services/subscriber/transports/grpc.py | 7 +- .../subscriber/transports/grpc_asyncio.py | 7 +- synth.metadata | 4 +- tests/unit/gapic/pubsub_v1/test_publisher.py | 101 +++-------------- .../gapic/pubsub_v1/test_schema_service.py | 107 +++--------------- tests/unit/gapic/pubsub_v1/test_subscriber.py | 103 +++-------------- 13 files changed, 109 insertions(+), 368 deletions(-) diff --git a/google/pubsub_v1/services/publisher/transports/base.py b/google/pubsub_v1/services/publisher/transports/base.py index 77edf35a9..5c61715b8 100644 --- a/google/pubsub_v1/services/publisher/transports/base.py +++ b/google/pubsub_v1/services/publisher/transports/base.py @@ -24,6 +24,7 @@ from google.api_core import gapic_v1 # type: ignore from google.api_core import retry as retries # type: ignore 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 @@ -48,8 +49,6 @@ except pkg_resources.DistributionNotFound: # pragma: NO COVER _GOOGLE_AUTH_VERSION = None -_API_CORE_VERSION = google.api_core.__version__ - class PublisherTransport(abc.ABC): """Abstract transport class for Publisher.""" @@ -70,6 +69,7 @@ def __init__( 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. @@ -93,6 +93,8 @@ def __init__( 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: @@ -121,13 +123,20 @@ def __init__( **scopes_kwargs, quota_project_id=quota_project_id ) + # If the credentials is 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 - # TODO(busunkim): These two class methods are in the base transport + # TODO(busunkim): This method is in the base transport # to avoid duplicating code across the transport classes. These functions - # should be deleted once the minimum required versions of google-api-core - # and google-auth are increased. + # should be deleted once the minimum required versions of google-auth is increased. # TODO: Remove this function once google-auth >= 1.25.0 is required @classmethod @@ -148,27 +157,6 @@ def _get_scopes_kwargs( return scopes_kwargs - # TODO: Remove this function once google-api-core >= 1.26.0 is required - @classmethod - def _get_self_signed_jwt_kwargs( - cls, host: str, scopes: Optional[Sequence[str]] - ) -> Dict[str, Union[Optional[Sequence[str]], str]]: - """Returns kwargs to pass to grpc_helpers.create_channel depending on the google-api-core version""" - - self_signed_jwt_kwargs: Dict[str, Union[Optional[Sequence[str]], str]] = {} - - if _API_CORE_VERSION and ( - packaging.version.parse(_API_CORE_VERSION) - >= packaging.version.parse("1.26.0") - ): - self_signed_jwt_kwargs["default_scopes"] = cls.AUTH_SCOPES - self_signed_jwt_kwargs["scopes"] = scopes - self_signed_jwt_kwargs["default_host"] = cls.DEFAULT_HOST - else: - self_signed_jwt_kwargs["scopes"] = scopes or cls.AUTH_SCOPES - - return self_signed_jwt_kwargs - def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. self._wrapped_methods = { diff --git a/google/pubsub_v1/services/publisher/transports/grpc.py b/google/pubsub_v1/services/publisher/transports/grpc.py index 55c1c5e83..0b30ccb64 100644 --- a/google/pubsub_v1/services/publisher/transports/grpc.py +++ b/google/pubsub_v1/services/publisher/transports/grpc.py @@ -153,6 +153,7 @@ def __init__( scopes=scopes, quota_project_id=quota_project_id, client_info=client_info, + always_use_jwt_access=True, ) if not self._grpc_channel: @@ -209,14 +210,14 @@ def create_channel( and ``credentials_file`` are passed. """ - self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) - return grpc_helpers.create_channel( host, credentials=credentials, credentials_file=credentials_file, quota_project_id=quota_project_id, - **self_signed_jwt_kwargs, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, **kwargs, ) diff --git a/google/pubsub_v1/services/publisher/transports/grpc_asyncio.py b/google/pubsub_v1/services/publisher/transports/grpc_asyncio.py index bc633fc21..e762307ce 100644 --- a/google/pubsub_v1/services/publisher/transports/grpc_asyncio.py +++ b/google/pubsub_v1/services/publisher/transports/grpc_asyncio.py @@ -82,14 +82,14 @@ def create_channel( aio.Channel: A gRPC AsyncIO channel object. """ - self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) - return grpc_helpers_async.create_channel( host, credentials=credentials, credentials_file=credentials_file, quota_project_id=quota_project_id, - **self_signed_jwt_kwargs, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, **kwargs, ) @@ -199,6 +199,7 @@ def __init__( scopes=scopes, quota_project_id=quota_project_id, client_info=client_info, + always_use_jwt_access=True, ) if not self._grpc_channel: diff --git a/google/pubsub_v1/services/schema_service/transports/base.py b/google/pubsub_v1/services/schema_service/transports/base.py index 1b00274b6..65912698b 100644 --- a/google/pubsub_v1/services/schema_service/transports/base.py +++ b/google/pubsub_v1/services/schema_service/transports/base.py @@ -24,6 +24,7 @@ from google.api_core import gapic_v1 # type: ignore from google.api_core import retry as retries # type: ignore 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 @@ -49,8 +50,6 @@ except pkg_resources.DistributionNotFound: # pragma: NO COVER _GOOGLE_AUTH_VERSION = None -_API_CORE_VERSION = google.api_core.__version__ - class SchemaServiceTransport(abc.ABC): """Abstract transport class for SchemaService.""" @@ -71,6 +70,7 @@ def __init__( 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. @@ -94,6 +94,8 @@ def __init__( 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: @@ -122,13 +124,20 @@ def __init__( **scopes_kwargs, quota_project_id=quota_project_id ) + # If the credentials is 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 - # TODO(busunkim): These two class methods are in the base transport + # TODO(busunkim): This method is in the base transport # to avoid duplicating code across the transport classes. These functions - # should be deleted once the minimum required versions of google-api-core - # and google-auth are increased. + # should be deleted once the minimum required versions of google-auth is increased. # TODO: Remove this function once google-auth >= 1.25.0 is required @classmethod @@ -149,27 +158,6 @@ def _get_scopes_kwargs( return scopes_kwargs - # TODO: Remove this function once google-api-core >= 1.26.0 is required - @classmethod - def _get_self_signed_jwt_kwargs( - cls, host: str, scopes: Optional[Sequence[str]] - ) -> Dict[str, Union[Optional[Sequence[str]], str]]: - """Returns kwargs to pass to grpc_helpers.create_channel depending on the google-api-core version""" - - self_signed_jwt_kwargs: Dict[str, Union[Optional[Sequence[str]], str]] = {} - - if _API_CORE_VERSION and ( - packaging.version.parse(_API_CORE_VERSION) - >= packaging.version.parse("1.26.0") - ): - self_signed_jwt_kwargs["default_scopes"] = cls.AUTH_SCOPES - self_signed_jwt_kwargs["scopes"] = scopes - self_signed_jwt_kwargs["default_host"] = cls.DEFAULT_HOST - else: - self_signed_jwt_kwargs["scopes"] = scopes or cls.AUTH_SCOPES - - return self_signed_jwt_kwargs - def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. self._wrapped_methods = { diff --git a/google/pubsub_v1/services/schema_service/transports/grpc.py b/google/pubsub_v1/services/schema_service/transports/grpc.py index ebf4d6e9f..6c6ddcdcd 100644 --- a/google/pubsub_v1/services/schema_service/transports/grpc.py +++ b/google/pubsub_v1/services/schema_service/transports/grpc.py @@ -153,6 +153,7 @@ def __init__( scopes=scopes, quota_project_id=quota_project_id, client_info=client_info, + always_use_jwt_access=True, ) if not self._grpc_channel: @@ -209,14 +210,14 @@ def create_channel( and ``credentials_file`` are passed. """ - self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) - return grpc_helpers.create_channel( host, credentials=credentials, credentials_file=credentials_file, quota_project_id=quota_project_id, - **self_signed_jwt_kwargs, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, **kwargs, ) diff --git a/google/pubsub_v1/services/schema_service/transports/grpc_asyncio.py b/google/pubsub_v1/services/schema_service/transports/grpc_asyncio.py index 9adebdf9f..bb423f47d 100644 --- a/google/pubsub_v1/services/schema_service/transports/grpc_asyncio.py +++ b/google/pubsub_v1/services/schema_service/transports/grpc_asyncio.py @@ -82,14 +82,14 @@ def create_channel( aio.Channel: A gRPC AsyncIO channel object. """ - self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) - return grpc_helpers_async.create_channel( host, credentials=credentials, credentials_file=credentials_file, quota_project_id=quota_project_id, - **self_signed_jwt_kwargs, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, **kwargs, ) @@ -199,6 +199,7 @@ def __init__( scopes=scopes, quota_project_id=quota_project_id, client_info=client_info, + always_use_jwt_access=True, ) if not self._grpc_channel: diff --git a/google/pubsub_v1/services/subscriber/transports/base.py b/google/pubsub_v1/services/subscriber/transports/base.py index 51189d8bf..2d111b6ff 100644 --- a/google/pubsub_v1/services/subscriber/transports/base.py +++ b/google/pubsub_v1/services/subscriber/transports/base.py @@ -24,6 +24,7 @@ from google.api_core import gapic_v1 # type: ignore from google.api_core import retry as retries # type: ignore 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 @@ -48,8 +49,6 @@ except pkg_resources.DistributionNotFound: # pragma: NO COVER _GOOGLE_AUTH_VERSION = None -_API_CORE_VERSION = google.api_core.__version__ - class SubscriberTransport(abc.ABC): """Abstract transport class for Subscriber.""" @@ -70,6 +69,7 @@ def __init__( 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. @@ -93,6 +93,8 @@ def __init__( 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: @@ -121,13 +123,20 @@ def __init__( **scopes_kwargs, quota_project_id=quota_project_id ) + # If the credentials is 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 - # TODO(busunkim): These two class methods are in the base transport + # TODO(busunkim): This method is in the base transport # to avoid duplicating code across the transport classes. These functions - # should be deleted once the minimum required versions of google-api-core - # and google-auth are increased. + # should be deleted once the minimum required versions of google-auth is increased. # TODO: Remove this function once google-auth >= 1.25.0 is required @classmethod @@ -148,27 +157,6 @@ def _get_scopes_kwargs( return scopes_kwargs - # TODO: Remove this function once google-api-core >= 1.26.0 is required - @classmethod - def _get_self_signed_jwt_kwargs( - cls, host: str, scopes: Optional[Sequence[str]] - ) -> Dict[str, Union[Optional[Sequence[str]], str]]: - """Returns kwargs to pass to grpc_helpers.create_channel depending on the google-api-core version""" - - self_signed_jwt_kwargs: Dict[str, Union[Optional[Sequence[str]], str]] = {} - - if _API_CORE_VERSION and ( - packaging.version.parse(_API_CORE_VERSION) - >= packaging.version.parse("1.26.0") - ): - self_signed_jwt_kwargs["default_scopes"] = cls.AUTH_SCOPES - self_signed_jwt_kwargs["scopes"] = scopes - self_signed_jwt_kwargs["default_host"] = cls.DEFAULT_HOST - else: - self_signed_jwt_kwargs["scopes"] = scopes or cls.AUTH_SCOPES - - return self_signed_jwt_kwargs - def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. self._wrapped_methods = { diff --git a/google/pubsub_v1/services/subscriber/transports/grpc.py b/google/pubsub_v1/services/subscriber/transports/grpc.py index 7668b02e7..1489ead2a 100644 --- a/google/pubsub_v1/services/subscriber/transports/grpc.py +++ b/google/pubsub_v1/services/subscriber/transports/grpc.py @@ -155,6 +155,7 @@ def __init__( scopes=scopes, quota_project_id=quota_project_id, client_info=client_info, + always_use_jwt_access=True, ) if not self._grpc_channel: @@ -211,14 +212,14 @@ def create_channel( and ``credentials_file`` are passed. """ - self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) - return grpc_helpers.create_channel( host, credentials=credentials, credentials_file=credentials_file, quota_project_id=quota_project_id, - **self_signed_jwt_kwargs, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, **kwargs, ) diff --git a/google/pubsub_v1/services/subscriber/transports/grpc_asyncio.py b/google/pubsub_v1/services/subscriber/transports/grpc_asyncio.py index 6ebf0746a..50cea83ca 100644 --- a/google/pubsub_v1/services/subscriber/transports/grpc_asyncio.py +++ b/google/pubsub_v1/services/subscriber/transports/grpc_asyncio.py @@ -84,14 +84,14 @@ def create_channel( aio.Channel: A gRPC AsyncIO channel object. """ - self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) - return grpc_helpers_async.create_channel( host, credentials=credentials, credentials_file=credentials_file, quota_project_id=quota_project_id, - **self_signed_jwt_kwargs, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, **kwargs, ) @@ -201,6 +201,7 @@ def __init__( scopes=scopes, quota_project_id=quota_project_id, client_info=client_info, + always_use_jwt_access=True, ) if not self._grpc_channel: diff --git a/synth.metadata b/synth.metadata index fc00473b5..bb94ff6bf 100644 --- a/synth.metadata +++ b/synth.metadata @@ -11,8 +11,8 @@ "git": { "name": "googleapis", "remote": "https://github.com/googleapis/googleapis.git", - "sha": "7e1b14e6c7a9ab96d2db7e4a131981f162446d34", - "internalRef": "373649163" + "sha": "076f7e9f0b258bdb54338895d7251b202e8f0de3", + "internalRef": "380641501" } } ], diff --git a/tests/unit/gapic/pubsub_v1/test_publisher.py b/tests/unit/gapic/pubsub_v1/test_publisher.py index 048d47ce0..782a6eb28 100644 --- a/tests/unit/gapic/pubsub_v1/test_publisher.py +++ b/tests/unit/gapic/pubsub_v1/test_publisher.py @@ -41,15 +41,15 @@ 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.services.publisher.transports.base import _API_CORE_VERSION from google.pubsub_v1.services.publisher.transports.base import _GOOGLE_AUTH_VERSION from google.pubsub_v1.types import pubsub from google.pubsub_v1.types import schema import google.auth -# TODO(busunkim): Once google-api-core >= 1.26.0 is required: -# - Delete all the api-core and auth "less than" test cases +# TODO(busunkim): Once google-auth >= 1.25.0 is required transitively +# through google-api-core: +# - Delete the auth "less than" test cases # - Delete these pytest markers (Make the "greater than or equal to" tests the default). requires_google_auth_lt_1_25_0 = pytest.mark.skipif( packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), @@ -60,16 +60,6 @@ reason="This test requires google-auth >= 1.25.0", ) -requires_api_core_lt_1_26_0 = pytest.mark.skipif( - packaging.version.parse(_API_CORE_VERSION) >= packaging.version.parse("1.26.0"), - reason="This test requires google-api-core < 1.26.0", -) - -requires_api_core_gte_1_26_0 = pytest.mark.skipif( - packaging.version.parse(_API_CORE_VERSION) < packaging.version.parse("1.26.0"), - reason="This test requires google-api-core >= 1.26.0", -) - def client_cert_source_callback(): return b"cert bytes", b"key bytes" @@ -125,6 +115,16 @@ def test_publisher_client_from_service_account_info(client_class): assert client.transport._host == "pubsub.googleapis.com:443" +@pytest.mark.parametrize("client_class", [PublisherClient, PublisherAsyncClient,]) +def test_publisher_client_service_account_always_use_jwt(client_class): + with mock.patch.object( + service_account.Credentials, "with_always_use_jwt_access", create=True + ) as use_jwt: + creds = service_account.Credentials(None, None, None) + client = client_class(credentials=creds) + use_jwt.assert_called_with(True) + + @pytest.mark.parametrize("client_class", [PublisherClient, PublisherAsyncClient,]) def test_publisher_client_from_service_account_file(client_class): creds = ga_credentials.AnonymousCredentials() @@ -2757,7 +2757,6 @@ def test_publisher_transport_auth_adc_old_google_auth(transport_class): (transports.PublisherGrpcAsyncIOTransport, grpc_helpers_async), ], ) -@requires_api_core_gte_1_26_0 def test_publisher_transport_create_channel(transport_class, grpc_helpers): # If credentials and host are not provided, the transport class should use # ADC credentials. @@ -2790,80 +2789,6 @@ def test_publisher_transport_create_channel(transport_class, grpc_helpers): ) -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.PublisherGrpcTransport, grpc_helpers), - (transports.PublisherGrpcAsyncIOTransport, grpc_helpers_async), - ], -) -@requires_api_core_lt_1_26_0 -def test_publisher_transport_create_channel_old_api_core(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") - - create_channel.assert_called_with( - "pubsub.googleapis.com:443", - credentials=creds, - credentials_file=None, - quota_project_id="octopus", - scopes=( - "https://www.googleapis.com/auth/cloud-platform", - "https://www.googleapis.com/auth/pubsub", - ), - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ("grpc.keepalive_time_ms", 30000), - ], - ) - - -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.PublisherGrpcTransport, grpc_helpers), - (transports.PublisherGrpcAsyncIOTransport, grpc_helpers_async), - ], -) -@requires_api_core_lt_1_26_0 -def test_publisher_transport_create_channel_user_scopes(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", - scopes=["1", "2"], - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ("grpc.keepalive_time_ms", 30000), - ], - ) - - @pytest.mark.parametrize( "transport_class", [transports.PublisherGrpcTransport, transports.PublisherGrpcAsyncIOTransport], diff --git a/tests/unit/gapic/pubsub_v1/test_schema_service.py b/tests/unit/gapic/pubsub_v1/test_schema_service.py index 5f8c44ad2..061d0bf00 100644 --- a/tests/unit/gapic/pubsub_v1/test_schema_service.py +++ b/tests/unit/gapic/pubsub_v1/test_schema_service.py @@ -39,7 +39,6 @@ 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.services.schema_service.transports.base import _API_CORE_VERSION from google.pubsub_v1.services.schema_service.transports.base import ( _GOOGLE_AUTH_VERSION, ) @@ -48,8 +47,9 @@ import google.auth -# TODO(busunkim): Once google-api-core >= 1.26.0 is required: -# - Delete all the api-core and auth "less than" test cases +# TODO(busunkim): Once google-auth >= 1.25.0 is required transitively +# through google-api-core: +# - Delete the auth "less than" test cases # - Delete these pytest markers (Make the "greater than or equal to" tests the default). requires_google_auth_lt_1_25_0 = pytest.mark.skipif( packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), @@ -60,16 +60,6 @@ reason="This test requires google-auth >= 1.25.0", ) -requires_api_core_lt_1_26_0 = pytest.mark.skipif( - packaging.version.parse(_API_CORE_VERSION) >= packaging.version.parse("1.26.0"), - reason="This test requires google-api-core < 1.26.0", -) - -requires_api_core_gte_1_26_0 = pytest.mark.skipif( - packaging.version.parse(_API_CORE_VERSION) < packaging.version.parse("1.26.0"), - reason="This test requires google-api-core >= 1.26.0", -) - def client_cert_source_callback(): return b"cert bytes", b"key bytes" @@ -132,6 +122,18 @@ def test_schema_service_client_from_service_account_info(client_class): assert client.transport._host == "pubsub.googleapis.com:443" +@pytest.mark.parametrize( + "client_class", [SchemaServiceClient, SchemaServiceAsyncClient,] +) +def test_schema_service_client_service_account_always_use_jwt(client_class): + with mock.patch.object( + service_account.Credentials, "with_always_use_jwt_access", create=True + ) as use_jwt: + creds = service_account.Credentials(None, None, None) + client = client_class(credentials=creds) + use_jwt.assert_called_with(True) + + @pytest.mark.parametrize( "client_class", [SchemaServiceClient, SchemaServiceAsyncClient,] ) @@ -2016,7 +2018,6 @@ def test_schema_service_transport_auth_adc_old_google_auth(transport_class): (transports.SchemaServiceGrpcAsyncIOTransport, grpc_helpers_async), ], ) -@requires_api_core_gte_1_26_0 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. @@ -2049,84 +2050,6 @@ def test_schema_service_transport_create_channel(transport_class, grpc_helpers): ) -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.SchemaServiceGrpcTransport, grpc_helpers), - (transports.SchemaServiceGrpcAsyncIOTransport, grpc_helpers_async), - ], -) -@requires_api_core_lt_1_26_0 -def test_schema_service_transport_create_channel_old_api_core( - 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") - - create_channel.assert_called_with( - "pubsub.googleapis.com:443", - credentials=creds, - credentials_file=None, - quota_project_id="octopus", - scopes=( - "https://www.googleapis.com/auth/cloud-platform", - "https://www.googleapis.com/auth/pubsub", - ), - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ("grpc.keepalive_time_ms", 30000), - ], - ) - - -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.SchemaServiceGrpcTransport, grpc_helpers), - (transports.SchemaServiceGrpcAsyncIOTransport, grpc_helpers_async), - ], -) -@requires_api_core_lt_1_26_0 -def test_schema_service_transport_create_channel_user_scopes( - 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", - scopes=["1", "2"], - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ("grpc.keepalive_time_ms", 30000), - ], - ) - - @pytest.mark.parametrize( "transport_class", [ diff --git a/tests/unit/gapic/pubsub_v1/test_subscriber.py b/tests/unit/gapic/pubsub_v1/test_subscriber.py index 447d5b9ba..2f279b3e1 100644 --- a/tests/unit/gapic/pubsub_v1/test_subscriber.py +++ b/tests/unit/gapic/pubsub_v1/test_subscriber.py @@ -43,14 +43,14 @@ 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.services.subscriber.transports.base import _API_CORE_VERSION from google.pubsub_v1.services.subscriber.transports.base import _GOOGLE_AUTH_VERSION from google.pubsub_v1.types import pubsub import google.auth -# TODO(busunkim): Once google-api-core >= 1.26.0 is required: -# - Delete all the api-core and auth "less than" test cases +# TODO(busunkim): Once google-auth >= 1.25.0 is required transitively +# through google-api-core: +# - Delete the auth "less than" test cases # - Delete these pytest markers (Make the "greater than or equal to" tests the default). requires_google_auth_lt_1_25_0 = pytest.mark.skipif( packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), @@ -61,16 +61,6 @@ reason="This test requires google-auth >= 1.25.0", ) -requires_api_core_lt_1_26_0 = pytest.mark.skipif( - packaging.version.parse(_API_CORE_VERSION) >= packaging.version.parse("1.26.0"), - reason="This test requires google-api-core < 1.26.0", -) - -requires_api_core_gte_1_26_0 = pytest.mark.skipif( - packaging.version.parse(_API_CORE_VERSION) < packaging.version.parse("1.26.0"), - reason="This test requires google-api-core >= 1.26.0", -) - def client_cert_source_callback(): return b"cert bytes", b"key bytes" @@ -128,6 +118,16 @@ def test_subscriber_client_from_service_account_info(client_class): assert client.transport._host == "pubsub.googleapis.com:443" +@pytest.mark.parametrize("client_class", [SubscriberClient, SubscriberAsyncClient,]) +def test_subscriber_client_service_account_always_use_jwt(client_class): + with mock.patch.object( + service_account.Credentials, "with_always_use_jwt_access", create=True + ) as use_jwt: + creds = service_account.Credentials(None, None, None) + client = client_class(credentials=creds) + use_jwt.assert_called_with(True) + + @pytest.mark.parametrize("client_class", [SubscriberClient, SubscriberAsyncClient,]) def test_subscriber_client_from_service_account_file(client_class): creds = ga_credentials.AnonymousCredentials() @@ -4034,7 +4034,6 @@ def test_subscriber_transport_auth_adc_old_google_auth(transport_class): (transports.SubscriberGrpcAsyncIOTransport, grpc_helpers_async), ], ) -@requires_api_core_gte_1_26_0 def test_subscriber_transport_create_channel(transport_class, grpc_helpers): # If credentials and host are not provided, the transport class should use # ADC credentials. @@ -4067,82 +4066,6 @@ def test_subscriber_transport_create_channel(transport_class, grpc_helpers): ) -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.SubscriberGrpcTransport, grpc_helpers), - (transports.SubscriberGrpcAsyncIOTransport, grpc_helpers_async), - ], -) -@requires_api_core_lt_1_26_0 -def test_subscriber_transport_create_channel_old_api_core( - 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") - - create_channel.assert_called_with( - "pubsub.googleapis.com:443", - credentials=creds, - credentials_file=None, - quota_project_id="octopus", - scopes=( - "https://www.googleapis.com/auth/cloud-platform", - "https://www.googleapis.com/auth/pubsub", - ), - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ("grpc.keepalive_time_ms", 30000), - ], - ) - - -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.SubscriberGrpcTransport, grpc_helpers), - (transports.SubscriberGrpcAsyncIOTransport, grpc_helpers_async), - ], -) -@requires_api_core_lt_1_26_0 -def test_subscriber_transport_create_channel_user_scopes(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", - scopes=["1", "2"], - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ("grpc.keepalive_time_ms", 30000), - ], - ) - - @pytest.mark.parametrize( "transport_class", [transports.SubscriberGrpcTransport, transports.SubscriberGrpcAsyncIOTransport], From e84fc7a0ff30aea65c0cc950efb56f960814ef6a Mon Sep 17 00:00:00 2001 From: yoshi-automation Date: Sun, 18 Jul 2021 05:03:24 +0000 Subject: [PATCH 10/18] chore: update python microgenerator to v0.50.2 PiperOrigin-RevId: 381898347 Source-Author: Google APIs Source-Date: Mon Jun 28 10:44:56 2021 -0700 Source-Repo: googleapis/googleapis Source-Sha: 2bf1e2a6711b228debfadbe639973920671a01ef Source-Link: https://github.com/googleapis/googleapis/commit/2bf1e2a6711b228debfadbe639973920671a01ef --- .../services/publisher/transports/base.py | 2 +- .../services/schema_service/transports/base.py | 2 +- .../services/subscriber/transports/base.py | 2 +- synth.metadata | 4 ++-- tests/unit/gapic/pubsub_v1/test_publisher.py | 15 +++------------ tests/unit/gapic/pubsub_v1/test_schema_service.py | 15 +++------------ tests/unit/gapic/pubsub_v1/test_subscriber.py | 15 +++------------ 7 files changed, 14 insertions(+), 41 deletions(-) diff --git a/google/pubsub_v1/services/publisher/transports/base.py b/google/pubsub_v1/services/publisher/transports/base.py index 5c61715b8..6e9f8cea8 100644 --- a/google/pubsub_v1/services/publisher/transports/base.py +++ b/google/pubsub_v1/services/publisher/transports/base.py @@ -104,7 +104,7 @@ def __init__( scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) # Save the scopes. - self._scopes = scopes or self.AUTH_SCOPES + self._scopes = scopes # If no credentials are provided, then determine the appropriate # defaults. diff --git a/google/pubsub_v1/services/schema_service/transports/base.py b/google/pubsub_v1/services/schema_service/transports/base.py index 65912698b..1044166cc 100644 --- a/google/pubsub_v1/services/schema_service/transports/base.py +++ b/google/pubsub_v1/services/schema_service/transports/base.py @@ -105,7 +105,7 @@ def __init__( scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) # Save the scopes. - self._scopes = scopes or self.AUTH_SCOPES + self._scopes = scopes # If no credentials are provided, then determine the appropriate # defaults. diff --git a/google/pubsub_v1/services/subscriber/transports/base.py b/google/pubsub_v1/services/subscriber/transports/base.py index 2d111b6ff..7100e5849 100644 --- a/google/pubsub_v1/services/subscriber/transports/base.py +++ b/google/pubsub_v1/services/subscriber/transports/base.py @@ -104,7 +104,7 @@ def __init__( scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) # Save the scopes. - self._scopes = scopes or self.AUTH_SCOPES + self._scopes = scopes # If no credentials are provided, then determine the appropriate # defaults. diff --git a/synth.metadata b/synth.metadata index bb94ff6bf..bb138259b 100644 --- a/synth.metadata +++ b/synth.metadata @@ -11,8 +11,8 @@ "git": { "name": "googleapis", "remote": "https://github.com/googleapis/googleapis.git", - "sha": "076f7e9f0b258bdb54338895d7251b202e8f0de3", - "internalRef": "380641501" + "sha": "2bf1e2a6711b228debfadbe639973920671a01ef", + "internalRef": "381898347" } } ], diff --git a/tests/unit/gapic/pubsub_v1/test_publisher.py b/tests/unit/gapic/pubsub_v1/test_publisher.py index 782a6eb28..c5bdb3184 100644 --- a/tests/unit/gapic/pubsub_v1/test_publisher.py +++ b/tests/unit/gapic/pubsub_v1/test_publisher.py @@ -2808,10 +2808,7 @@ def test_publisher_grpc_transport_client_cert_source_for_mtls(transport_class): "squid.clam.whelk:443", credentials=cred, credentials_file=None, - scopes=( - "https://www.googleapis.com/auth/cloud-platform", - "https://www.googleapis.com/auth/pubsub", - ), + scopes=None, ssl_credentials=mock_ssl_channel_creds, quota_project_id=None, options=[ @@ -2916,10 +2913,7 @@ def test_publisher_transport_channel_mtls_with_client_cert_source(transport_clas "mtls.squid.clam.whelk:443", credentials=cred, credentials_file=None, - scopes=( - "https://www.googleapis.com/auth/cloud-platform", - "https://www.googleapis.com/auth/pubsub", - ), + scopes=None, ssl_credentials=mock_ssl_cred, quota_project_id=None, options=[ @@ -2964,10 +2958,7 @@ def test_publisher_transport_channel_mtls_with_adc(transport_class): "mtls.squid.clam.whelk:443", credentials=mock_cred, credentials_file=None, - scopes=( - "https://www.googleapis.com/auth/cloud-platform", - "https://www.googleapis.com/auth/pubsub", - ), + scopes=None, ssl_credentials=mock_ssl_cred, quota_project_id=None, options=[ diff --git a/tests/unit/gapic/pubsub_v1/test_schema_service.py b/tests/unit/gapic/pubsub_v1/test_schema_service.py index 061d0bf00..79d93e159 100644 --- a/tests/unit/gapic/pubsub_v1/test_schema_service.py +++ b/tests/unit/gapic/pubsub_v1/test_schema_service.py @@ -2072,10 +2072,7 @@ def test_schema_service_grpc_transport_client_cert_source_for_mtls(transport_cla "squid.clam.whelk:443", credentials=cred, credentials_file=None, - scopes=( - "https://www.googleapis.com/auth/cloud-platform", - "https://www.googleapis.com/auth/pubsub", - ), + scopes=None, ssl_credentials=mock_ssl_channel_creds, quota_project_id=None, options=[ @@ -2183,10 +2180,7 @@ def test_schema_service_transport_channel_mtls_with_client_cert_source(transport "mtls.squid.clam.whelk:443", credentials=cred, credentials_file=None, - scopes=( - "https://www.googleapis.com/auth/cloud-platform", - "https://www.googleapis.com/auth/pubsub", - ), + scopes=None, ssl_credentials=mock_ssl_cred, quota_project_id=None, options=[ @@ -2234,10 +2228,7 @@ def test_schema_service_transport_channel_mtls_with_adc(transport_class): "mtls.squid.clam.whelk:443", credentials=mock_cred, credentials_file=None, - scopes=( - "https://www.googleapis.com/auth/cloud-platform", - "https://www.googleapis.com/auth/pubsub", - ), + scopes=None, ssl_credentials=mock_ssl_cred, quota_project_id=None, options=[ diff --git a/tests/unit/gapic/pubsub_v1/test_subscriber.py b/tests/unit/gapic/pubsub_v1/test_subscriber.py index 2f279b3e1..68614e8a9 100644 --- a/tests/unit/gapic/pubsub_v1/test_subscriber.py +++ b/tests/unit/gapic/pubsub_v1/test_subscriber.py @@ -4085,10 +4085,7 @@ def test_subscriber_grpc_transport_client_cert_source_for_mtls(transport_class): "squid.clam.whelk:443", credentials=cred, credentials_file=None, - scopes=( - "https://www.googleapis.com/auth/cloud-platform", - "https://www.googleapis.com/auth/pubsub", - ), + scopes=None, ssl_credentials=mock_ssl_channel_creds, quota_project_id=None, options=[ @@ -4193,10 +4190,7 @@ def test_subscriber_transport_channel_mtls_with_client_cert_source(transport_cla "mtls.squid.clam.whelk:443", credentials=cred, credentials_file=None, - scopes=( - "https://www.googleapis.com/auth/cloud-platform", - "https://www.googleapis.com/auth/pubsub", - ), + scopes=None, ssl_credentials=mock_ssl_cred, quota_project_id=None, options=[ @@ -4241,10 +4235,7 @@ def test_subscriber_transport_channel_mtls_with_adc(transport_class): "mtls.squid.clam.whelk:443", credentials=mock_cred, credentials_file=None, - scopes=( - "https://www.googleapis.com/auth/cloud-platform", - "https://www.googleapis.com/auth/pubsub", - ), + scopes=None, ssl_credentials=mock_ssl_cred, quota_project_id=None, options=[ From 3ab055652c49ab3942f4b696101595e6c0504f55 Mon Sep 17 00:00:00 2001 From: yoshi-automation Date: Sun, 18 Jul 2021 05:05:52 +0000 Subject: [PATCH 11/18] chore: use gapic-generator-python 0.50.3 fix: disable always_use_jwt_access Committer: @busunkim96 PiperOrigin-RevId: 382142900 Source-Author: Google APIs Source-Date: Tue Jun 29 12:38:25 2021 -0700 Source-Repo: googleapis/googleapis Source-Sha: 513440fda515f3c799c22a30e3906dcda325004e Source-Link: https://github.com/googleapis/googleapis/commit/513440fda515f3c799c22a30e3906dcda325004e --- .../services/publisher/transports/grpc.py | 5 ++++- .../publisher/transports/grpc_asyncio.py | 5 ++++- .../schema_service/transports/grpc.py | 5 ++++- .../schema_service/transports/grpc_asyncio.py | 5 ++++- .../services/subscriber/transports/grpc.py | 5 ++++- .../subscriber/transports/grpc_asyncio.py | 5 ++++- synth.metadata | 4 ++-- tests/unit/gapic/pubsub_v1/test_publisher.py | 20 ++++++++++++++++++- .../gapic/pubsub_v1/test_schema_service.py | 20 ++++++++++++++++++- tests/unit/gapic/pubsub_v1/test_subscriber.py | 20 ++++++++++++++++++- 10 files changed, 83 insertions(+), 11 deletions(-) diff --git a/google/pubsub_v1/services/publisher/transports/grpc.py b/google/pubsub_v1/services/publisher/transports/grpc.py index 0b30ccb64..d6c127d10 100644 --- a/google/pubsub_v1/services/publisher/transports/grpc.py +++ b/google/pubsub_v1/services/publisher/transports/grpc.py @@ -61,6 +61,7 @@ def __init__( 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. @@ -101,6 +102,8 @@ def __init__( 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 @@ -153,7 +156,7 @@ def __init__( scopes=scopes, quota_project_id=quota_project_id, client_info=client_info, - always_use_jwt_access=True, + always_use_jwt_access=always_use_jwt_access, ) if not self._grpc_channel: diff --git a/google/pubsub_v1/services/publisher/transports/grpc_asyncio.py b/google/pubsub_v1/services/publisher/transports/grpc_asyncio.py index e762307ce..d98b8fc1c 100644 --- a/google/pubsub_v1/services/publisher/transports/grpc_asyncio.py +++ b/google/pubsub_v1/services/publisher/transports/grpc_asyncio.py @@ -107,6 +107,7 @@ def __init__( 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. @@ -148,6 +149,8 @@ def __init__( 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 @@ -199,7 +202,7 @@ def __init__( scopes=scopes, quota_project_id=quota_project_id, client_info=client_info, - always_use_jwt_access=True, + always_use_jwt_access=always_use_jwt_access, ) if not self._grpc_channel: diff --git a/google/pubsub_v1/services/schema_service/transports/grpc.py b/google/pubsub_v1/services/schema_service/transports/grpc.py index 6c6ddcdcd..c99633ca2 100644 --- a/google/pubsub_v1/services/schema_service/transports/grpc.py +++ b/google/pubsub_v1/services/schema_service/transports/grpc.py @@ -61,6 +61,7 @@ def __init__( 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. @@ -101,6 +102,8 @@ def __init__( 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 @@ -153,7 +156,7 @@ def __init__( scopes=scopes, quota_project_id=quota_project_id, client_info=client_info, - always_use_jwt_access=True, + always_use_jwt_access=always_use_jwt_access, ) if not self._grpc_channel: diff --git a/google/pubsub_v1/services/schema_service/transports/grpc_asyncio.py b/google/pubsub_v1/services/schema_service/transports/grpc_asyncio.py index bb423f47d..0f4c93370 100644 --- a/google/pubsub_v1/services/schema_service/transports/grpc_asyncio.py +++ b/google/pubsub_v1/services/schema_service/transports/grpc_asyncio.py @@ -107,6 +107,7 @@ def __init__( 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. @@ -148,6 +149,8 @@ def __init__( 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 @@ -199,7 +202,7 @@ def __init__( scopes=scopes, quota_project_id=quota_project_id, client_info=client_info, - always_use_jwt_access=True, + always_use_jwt_access=always_use_jwt_access, ) if not self._grpc_channel: diff --git a/google/pubsub_v1/services/subscriber/transports/grpc.py b/google/pubsub_v1/services/subscriber/transports/grpc.py index 1489ead2a..b116b018c 100644 --- a/google/pubsub_v1/services/subscriber/transports/grpc.py +++ b/google/pubsub_v1/services/subscriber/transports/grpc.py @@ -63,6 +63,7 @@ def __init__( 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. @@ -103,6 +104,8 @@ def __init__( 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 @@ -155,7 +158,7 @@ def __init__( scopes=scopes, quota_project_id=quota_project_id, client_info=client_info, - always_use_jwt_access=True, + always_use_jwt_access=always_use_jwt_access, ) if not self._grpc_channel: diff --git a/google/pubsub_v1/services/subscriber/transports/grpc_asyncio.py b/google/pubsub_v1/services/subscriber/transports/grpc_asyncio.py index 50cea83ca..91d557790 100644 --- a/google/pubsub_v1/services/subscriber/transports/grpc_asyncio.py +++ b/google/pubsub_v1/services/subscriber/transports/grpc_asyncio.py @@ -109,6 +109,7 @@ def __init__( 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. @@ -150,6 +151,8 @@ def __init__( 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 @@ -201,7 +204,7 @@ def __init__( scopes=scopes, quota_project_id=quota_project_id, client_info=client_info, - always_use_jwt_access=True, + always_use_jwt_access=always_use_jwt_access, ) if not self._grpc_channel: diff --git a/synth.metadata b/synth.metadata index bb138259b..f3bb53d5d 100644 --- a/synth.metadata +++ b/synth.metadata @@ -11,8 +11,8 @@ "git": { "name": "googleapis", "remote": "https://github.com/googleapis/googleapis.git", - "sha": "2bf1e2a6711b228debfadbe639973920671a01ef", - "internalRef": "381898347" + "sha": "513440fda515f3c799c22a30e3906dcda325004e", + "internalRef": "382142900" } } ], diff --git a/tests/unit/gapic/pubsub_v1/test_publisher.py b/tests/unit/gapic/pubsub_v1/test_publisher.py index c5bdb3184..b171fb3e7 100644 --- a/tests/unit/gapic/pubsub_v1/test_publisher.py +++ b/tests/unit/gapic/pubsub_v1/test_publisher.py @@ -122,7 +122,25 @@ def test_publisher_client_service_account_always_use_jwt(client_class): ) as use_jwt: creds = service_account.Credentials(None, None, None) client = client_class(credentials=creds) - use_jwt.assert_called_with(True) + use_jwt.assert_not_called() + + +@pytest.mark.parametrize( + "transport_class,transport_name", + [ + (transports.PublisherGrpcTransport, "grpc"), + (transports.PublisherGrpcAsyncIOTransport, "grpc_asyncio"), + ], +) +def test_publisher_client_service_account_always_use_jwt_true( + 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) @pytest.mark.parametrize("client_class", [PublisherClient, PublisherAsyncClient,]) diff --git a/tests/unit/gapic/pubsub_v1/test_schema_service.py b/tests/unit/gapic/pubsub_v1/test_schema_service.py index 79d93e159..fcc8b68e1 100644 --- a/tests/unit/gapic/pubsub_v1/test_schema_service.py +++ b/tests/unit/gapic/pubsub_v1/test_schema_service.py @@ -131,7 +131,25 @@ def test_schema_service_client_service_account_always_use_jwt(client_class): ) as use_jwt: creds = service_account.Credentials(None, None, None) client = client_class(credentials=creds) - use_jwt.assert_called_with(True) + use_jwt.assert_not_called() + + +@pytest.mark.parametrize( + "transport_class,transport_name", + [ + (transports.SchemaServiceGrpcTransport, "grpc"), + (transports.SchemaServiceGrpcAsyncIOTransport, "grpc_asyncio"), + ], +) +def test_schema_service_client_service_account_always_use_jwt_true( + 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) @pytest.mark.parametrize( diff --git a/tests/unit/gapic/pubsub_v1/test_subscriber.py b/tests/unit/gapic/pubsub_v1/test_subscriber.py index 68614e8a9..67e6b26cc 100644 --- a/tests/unit/gapic/pubsub_v1/test_subscriber.py +++ b/tests/unit/gapic/pubsub_v1/test_subscriber.py @@ -125,7 +125,25 @@ def test_subscriber_client_service_account_always_use_jwt(client_class): ) as use_jwt: creds = service_account.Credentials(None, None, None) client = client_class(credentials=creds) - use_jwt.assert_called_with(True) + use_jwt.assert_not_called() + + +@pytest.mark.parametrize( + "transport_class,transport_name", + [ + (transports.SubscriberGrpcTransport, "grpc"), + (transports.SubscriberGrpcAsyncIOTransport, "grpc_asyncio"), + ], +) +def test_subscriber_client_service_account_always_use_jwt_true( + 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) @pytest.mark.parametrize("client_class", [SubscriberClient, SubscriberAsyncClient,]) From f27e48e6bc09d57950608a8da1aeaa5ac9f14de1 Mon Sep 17 00:00:00 2001 From: yoshi-automation Date: Sun, 18 Jul 2021 05:06:54 +0000 Subject: [PATCH 12/18] feat: Adding subscription properties to streaming pull response in third party pubsub.proto. PiperOrigin-RevId: 382318016 Source-Author: Google APIs Source-Date: Wed Jun 30 09:11:17 2021 -0700 Source-Repo: googleapis/googleapis Source-Sha: e9b2b616a20a11c97c7ac912536e82d33d006104 Source-Link: https://github.com/googleapis/googleapis/commit/e9b2b616a20a11c97c7ac912536e82d33d006104 --- google/cloud/pubsub_v1/proto/pubsub.proto | 11 ++++++++++- google/pubsub_v1/types/pubsub.py | 15 +++++++++++++++ synth.metadata | 4 ++-- 3 files changed, 27 insertions(+), 3 deletions(-) diff --git a/google/cloud/pubsub_v1/proto/pubsub.proto b/google/cloud/pubsub_v1/proto/pubsub.proto index 0da37dd7d..745d6cca4 100644 --- a/google/cloud/pubsub_v1/proto/pubsub.proto +++ b/google/cloud/pubsub_v1/proto/pubsub.proto @@ -1,4 +1,4 @@ -// Copyright 2020 Google LLC +// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -1142,8 +1142,17 @@ message StreamingPullRequest { // Response for the `StreamingPull` method. This response is used to stream // messages from the server to the client. message StreamingPullResponse { + // Subscription properties sent as part of the response. + message SubscriptionProperties { + // True iff message ordering is enabled for this subscription. + bool message_ordering_enabled = 2; + } + // Received Pub/Sub messages. This will not be empty. repeated ReceivedMessage received_messages = 1; + + // Properties associated with this subscription. + SubscriptionProperties subscription_properties = 4; } // Request for the `CreateSnapshot` method. diff --git a/google/pubsub_v1/types/pubsub.py b/google/pubsub_v1/types/pubsub.py index c332309d0..d105a9048 100644 --- a/google/pubsub_v1/types/pubsub.py +++ b/google/pubsub_v1/types/pubsub.py @@ -1046,11 +1046,26 @@ class StreamingPullResponse(proto.Message): received_messages (Sequence[google.pubsub_v1.types.ReceivedMessage]): Received Pub/Sub messages. This will not be empty. + subscription_properties (google.pubsub_v1.types.StreamingPullResponse.SubscriptionProperties): + Properties associated with this subscription. """ + class SubscriptionProperties(proto.Message): + r"""Subscription properties sent as part of the response. + Attributes: + message_ordering_enabled (bool): + True iff message ordering is enabled for this + subscription. + """ + + message_ordering_enabled = proto.Field(proto.BOOL, number=2,) + received_messages = proto.RepeatedField( proto.MESSAGE, number=1, message="ReceivedMessage", ) + subscription_properties = proto.Field( + proto.MESSAGE, number=4, message=SubscriptionProperties, + ) class CreateSnapshotRequest(proto.Message): diff --git a/synth.metadata b/synth.metadata index f3bb53d5d..37ed1b51c 100644 --- a/synth.metadata +++ b/synth.metadata @@ -11,8 +11,8 @@ "git": { "name": "googleapis", "remote": "https://github.com/googleapis/googleapis.git", - "sha": "513440fda515f3c799c22a30e3906dcda325004e", - "internalRef": "382142900" + "sha": "e9b2b616a20a11c97c7ac912536e82d33d006104", + "internalRef": "382318016" } } ], From 195dcba8db4e41d8f0394f2f946656eceed439ec Mon Sep 17 00:00:00 2001 From: yoshi-automation Date: Sun, 18 Jul 2021 05:08:33 +0000 Subject: [PATCH 13/18] feat: Add method signature for Subscriber.Pull without the deprecated return_immediately field. PiperOrigin-RevId: 383459959 Source-Author: Google APIs Source-Date: Wed Jul 7 11:45:38 2021 -0700 Source-Repo: googleapis/googleapis Source-Sha: fe3cc5e650b8e52537f02549fe5fb49fc386f3a9 Source-Link: https://github.com/googleapis/googleapis/commit/fe3cc5e650b8e52537f02549fe5fb49fc386f3a9 --- google/cloud/pubsub_v1/proto/pubsub.proto | 1 + synth.metadata | 4 ++-- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/google/cloud/pubsub_v1/proto/pubsub.proto b/google/cloud/pubsub_v1/proto/pubsub.proto index 745d6cca4..173c4ce71 100644 --- a/google/cloud/pubsub_v1/proto/pubsub.proto +++ b/google/cloud/pubsub_v1/proto/pubsub.proto @@ -505,6 +505,7 @@ service Subscriber { }; option (google.api.method_signature) = "subscription,return_immediately,max_messages"; + option (google.api.method_signature) = "subscription,max_messages"; } // Establishes a stream with the server, which sends messages down to the diff --git a/synth.metadata b/synth.metadata index 37ed1b51c..7036b40f6 100644 --- a/synth.metadata +++ b/synth.metadata @@ -11,8 +11,8 @@ "git": { "name": "googleapis", "remote": "https://github.com/googleapis/googleapis.git", - "sha": "e9b2b616a20a11c97c7ac912536e82d33d006104", - "internalRef": "382318016" + "sha": "fe3cc5e650b8e52537f02549fe5fb49fc386f3a9", + "internalRef": "383459959" } } ], From 2d63b37604aaf9b1a135031dacdba907f1dff9a5 Mon Sep 17 00:00:00 2001 From: Anthonios Partheniou Date: Sun, 18 Jul 2021 10:41:45 +0000 Subject: [PATCH 14/18] Work around gapic generator docstring bug --- synth.py | 18 +++++++++++++++++- 1 file changed, 17 insertions(+), 1 deletion(-) diff --git a/synth.py b/synth.py index 41b63e89e..f5631974b 100644 --- a/synth.py +++ b/synth.py @@ -49,7 +49,7 @@ # DEFAULT SCOPES and SERVICE_ADDRESS are being used. so let's force them in. s.replace( "google/pubsub_v1/services/*er/*client.py", - r"DEFAULT_ENDPOINT = 'pubsub\.googleapis\.com'", + """DEFAULT_ENDPOINT = "pubsub\.googleapis\.com\"""", """ # The scopes needed to make gRPC calls to all of the methods defined in # this service @@ -302,6 +302,22 @@ "\ggoogle/cloud/__init__.py\n\g<0>", ) +# Work around gapic generator bug https://github.com/googleapis/gapic-generator-python/issues/902 +s.replace(f"google/pubsub_v1/types/*.py", + r""". + Attributes:""", + r""".\n + Attributes:""", +) + +# Work around gapic generator bug https://github.com/googleapis/gapic-generator-python/issues/902 +s.replace("google/pubsub_v1/types/*.py", + r""". + Attributes:""", + r""".\n + Attributes:""", +) + # ---------------------------------------------------------------------------- # Add templated files # ---------------------------------------------------------------------------- From 4578d01af20ddf6dec04e7090f01e4d5293c741f Mon Sep 17 00:00:00 2001 From: Anthonios Partheniou Date: Sun, 18 Jul 2021 10:41:53 +0000 Subject: [PATCH 15/18] run synthtool locally --- google/pubsub_v1/services/publisher/client.py | 10 ++ .../pubsub_v1/services/subscriber/client.py | 10 ++ google/pubsub_v1/types/pubsub.py | 35 ++++ google/pubsub_v1/types/schema.py | 8 + synth.metadata | 150 +++--------------- 5 files changed, 82 insertions(+), 131 deletions(-) diff --git a/google/pubsub_v1/services/publisher/client.py b/google/pubsub_v1/services/publisher/client.py index 321d9efe3..cb4450608 100644 --- a/google/pubsub_v1/services/publisher/client.py +++ b/google/pubsub_v1/services/publisher/client.py @@ -112,6 +112,16 @@ def _get_default_mtls_endpoint(api_endpoint): return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + # The scopes needed to make gRPC calls to all of the methods defined in + # this service + _DEFAULT_SCOPES = ( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/pubsub", + ) + + SERVICE_ADDRESS = "pubsub.googleapis.com:443" + """The default address of the service.""" + DEFAULT_ENDPOINT = "pubsub.googleapis.com" DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore DEFAULT_ENDPOINT diff --git a/google/pubsub_v1/services/subscriber/client.py b/google/pubsub_v1/services/subscriber/client.py index 4c307f462..9f506214a 100644 --- a/google/pubsub_v1/services/subscriber/client.py +++ b/google/pubsub_v1/services/subscriber/client.py @@ -125,6 +125,16 @@ def _get_default_mtls_endpoint(api_endpoint): return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + # The scopes needed to make gRPC calls to all of the methods defined in + # this service + _DEFAULT_SCOPES = ( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/pubsub", + ) + + SERVICE_ADDRESS = "pubsub.googleapis.com:443" + """The default address of the service.""" + DEFAULT_ENDPOINT = "pubsub.googleapis.com" DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore DEFAULT_ENDPOINT diff --git a/google/pubsub_v1/types/pubsub.py b/google/pubsub_v1/types/pubsub.py index d105a9048..bfbbcaf87 100644 --- a/google/pubsub_v1/types/pubsub.py +++ b/google/pubsub_v1/types/pubsub.py @@ -93,6 +93,7 @@ class MessageStoragePolicy(proto.Message): 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 @@ -110,6 +111,7 @@ class SchemaSettings(proto.Message): class Topic(proto.Message): r"""A topic resource. + Attributes: name (str): Required. The name of the topic. It must have the format @@ -207,6 +209,7 @@ class PubsubMessage(proto.Message): class GetTopicRequest(proto.Message): r"""Request for the GetTopic method. + Attributes: topic (str): Required. The name of the topic to get. Format is @@ -218,6 +221,7 @@ class GetTopicRequest(proto.Message): class UpdateTopicRequest(proto.Message): r"""Request for the UpdateTopic method. + Attributes: topic (google.pubsub_v1.types.Topic): Required. The updated topic object. @@ -238,6 +242,7 @@ class UpdateTopicRequest(proto.Message): class PublishRequest(proto.Message): r"""Request for the Publish method. + Attributes: topic (str): Required. The messages in the request will be published on @@ -252,6 +257,7 @@ class PublishRequest(proto.Message): class PublishResponse(proto.Message): r"""Response for the ``Publish`` method. + Attributes: message_ids (Sequence[str]): The server-assigned ID of each published @@ -265,6 +271,7 @@ class PublishResponse(proto.Message): class ListTopicsRequest(proto.Message): r"""Request for the ``ListTopics`` method. + Attributes: project (str): Required. The name of the project in which to list topics. @@ -285,6 +292,7 @@ class ListTopicsRequest(proto.Message): class ListTopicsResponse(proto.Message): r"""Response for the ``ListTopics`` method. + Attributes: topics (Sequence[google.pubsub_v1.types.Topic]): The resulting topics. @@ -304,6 +312,7 @@ def raw_page(self): class ListTopicSubscriptionsRequest(proto.Message): r"""Request for the ``ListTopicSubscriptions`` method. + Attributes: topic (str): Required. The name of the topic that subscriptions are @@ -326,6 +335,7 @@ class ListTopicSubscriptionsRequest(proto.Message): class ListTopicSubscriptionsResponse(proto.Message): r"""Response for the ``ListTopicSubscriptions`` method. + Attributes: subscriptions (Sequence[str]): The names of subscriptions attached to the @@ -346,6 +356,7 @@ def raw_page(self): class ListTopicSnapshotsRequest(proto.Message): r"""Request for the ``ListTopicSnapshots`` method. + Attributes: topic (str): Required. The name of the topic that snapshots are attached @@ -366,6 +377,7 @@ class ListTopicSnapshotsRequest(proto.Message): class ListTopicSnapshotsResponse(proto.Message): r"""Response for the ``ListTopicSnapshots`` method. + Attributes: snapshots (Sequence[str]): The names of the snapshots that match the @@ -386,6 +398,7 @@ def raw_page(self): class DeleteTopicRequest(proto.Message): r"""Request for the ``DeleteTopic`` method. + Attributes: topic (str): Required. Name of the topic to delete. Format is @@ -397,6 +410,7 @@ class DeleteTopicRequest(proto.Message): class DetachSubscriptionRequest(proto.Message): r"""Request for the DetachSubscription method. + Attributes: subscription (str): Required. The subscription to detach. Format is @@ -414,6 +428,7 @@ class DetachSubscriptionResponse(proto.Message): class Subscription(proto.Message): r"""A subscription resource. + Attributes: name (str): Required. The name of the subscription. It must have the @@ -647,6 +662,7 @@ class ExpirationPolicy(proto.Message): class PushConfig(proto.Message): r"""Configuration for a push delivery endpoint. + Attributes: push_endpoint (str): A URL locating the endpoint to which messages should be @@ -725,6 +741,7 @@ class OidcToken(proto.Message): class ReceivedMessage(proto.Message): r"""A message and its corresponding acknowledgment ID. + Attributes: ack_id (str): This ID can be used to acknowledge the @@ -759,6 +776,7 @@ class ReceivedMessage(proto.Message): class GetSubscriptionRequest(proto.Message): r"""Request for the GetSubscription method. + Attributes: subscription (str): Required. The name of the subscription to get. Format is @@ -770,6 +788,7 @@ class GetSubscriptionRequest(proto.Message): class UpdateSubscriptionRequest(proto.Message): r"""Request for the UpdateSubscription method. + Attributes: subscription (google.pubsub_v1.types.Subscription): Required. The updated subscription object. @@ -787,6 +806,7 @@ class UpdateSubscriptionRequest(proto.Message): class ListSubscriptionsRequest(proto.Message): r"""Request for the ``ListSubscriptions`` method. + Attributes: project (str): Required. The name of the project in which to list @@ -807,6 +827,7 @@ class ListSubscriptionsRequest(proto.Message): class ListSubscriptionsResponse(proto.Message): r"""Response for the ``ListSubscriptions`` method. + Attributes: subscriptions (Sequence[google.pubsub_v1.types.Subscription]): The subscriptions that match the request. @@ -828,6 +849,7 @@ def raw_page(self): class DeleteSubscriptionRequest(proto.Message): r"""Request for the DeleteSubscription method. + Attributes: subscription (str): Required. The subscription to delete. Format is @@ -839,6 +861,7 @@ class DeleteSubscriptionRequest(proto.Message): class ModifyPushConfigRequest(proto.Message): r"""Request for the ModifyPushConfig method. + Attributes: subscription (str): Required. The name of the subscription. Format is @@ -859,6 +882,7 @@ class ModifyPushConfigRequest(proto.Message): class PullRequest(proto.Message): r"""Request for the ``Pull`` method. + Attributes: subscription (str): Required. The subscription from which messages should be @@ -887,6 +911,7 @@ class PullRequest(proto.Message): 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 @@ -903,6 +928,7 @@ class PullResponse(proto.Message): class ModifyAckDeadlineRequest(proto.Message): r"""Request for the ModifyAckDeadline method. + Attributes: subscription (str): Required. The name of the subscription. Format is @@ -929,6 +955,7 @@ class ModifyAckDeadlineRequest(proto.Message): class AcknowledgeRequest(proto.Message): r"""Request for the Acknowledge method. + Attributes: subscription (str): Required. The subscription whose message is being @@ -1052,6 +1079,7 @@ class StreamingPullResponse(proto.Message): class SubscriptionProperties(proto.Message): r"""Subscription properties sent as part of the response. + Attributes: message_ordering_enabled (bool): True iff message ordering is enabled for this @@ -1070,6 +1098,7 @@ class SubscriptionProperties(proto.Message): class CreateSnapshotRequest(proto.Message): r"""Request for the ``CreateSnapshot`` method. + Attributes: name (str): Required. User-provided name for this snapshot. If the name @@ -1102,6 +1131,7 @@ class CreateSnapshotRequest(proto.Message): class UpdateSnapshotRequest(proto.Message): r"""Request for the UpdateSnapshot method. + Attributes: snapshot (google.pubsub_v1.types.Snapshot): Required. The updated snapshot object. @@ -1157,6 +1187,7 @@ class Snapshot(proto.Message): class GetSnapshotRequest(proto.Message): r"""Request for the GetSnapshot method. + Attributes: snapshot (str): Required. The name of the snapshot to get. Format is @@ -1168,6 +1199,7 @@ class GetSnapshotRequest(proto.Message): class ListSnapshotsRequest(proto.Message): r"""Request for the ``ListSnapshots`` method. + Attributes: project (str): Required. The name of the project in which to list @@ -1188,6 +1220,7 @@ class ListSnapshotsRequest(proto.Message): class ListSnapshotsResponse(proto.Message): r"""Response for the ``ListSnapshots`` method. + Attributes: snapshots (Sequence[google.pubsub_v1.types.Snapshot]): The resulting snapshots. @@ -1207,6 +1240,7 @@ def raw_page(self): class DeleteSnapshotRequest(proto.Message): r"""Request for the ``DeleteSnapshot`` method. + Attributes: snapshot (str): Required. The name of the snapshot to delete. Format is @@ -1218,6 +1252,7 @@ class DeleteSnapshotRequest(proto.Message): class SeekRequest(proto.Message): r"""Request for the ``Seek`` method. + Attributes: subscription (str): Required. The subscription to affect. diff --git a/google/pubsub_v1/types/schema.py b/google/pubsub_v1/types/schema.py index d15837cbd..d0c96217b 100644 --- a/google/pubsub_v1/types/schema.py +++ b/google/pubsub_v1/types/schema.py @@ -53,6 +53,7 @@ class Encoding(proto.Enum): class Schema(proto.Message): r"""A schema resource. + Attributes: name (str): Required. Name of the schema. Format is @@ -78,6 +79,7 @@ class Type(proto.Enum): class CreateSchemaRequest(proto.Message): r"""Request for the CreateSchema method. + Attributes: parent (str): Required. The name of the project in which to create the @@ -104,6 +106,7 @@ class CreateSchemaRequest(proto.Message): class GetSchemaRequest(proto.Message): r"""Request for the GetSchema method. + Attributes: name (str): Required. The name of the schema to get. Format is @@ -120,6 +123,7 @@ class GetSchemaRequest(proto.Message): class ListSchemasRequest(proto.Message): r"""Request for the ``ListSchemas`` method. + Attributes: parent (str): Required. The name of the project in which to list schemas. @@ -145,6 +149,7 @@ class ListSchemasRequest(proto.Message): class ListSchemasResponse(proto.Message): r"""Response for the ``ListSchemas`` method. + Attributes: schemas (Sequence[google.pubsub_v1.types.Schema]): The resulting schemas. @@ -164,6 +169,7 @@ def raw_page(self): class DeleteSchemaRequest(proto.Message): r"""Request for the ``DeleteSchema`` method. + Attributes: name (str): Required. Name of the schema to delete. Format is @@ -175,6 +181,7 @@ class DeleteSchemaRequest(proto.Message): class ValidateSchemaRequest(proto.Message): r"""Request for the ``ValidateSchema`` method. + Attributes: parent (str): Required. The name of the project in which to validate @@ -193,6 +200,7 @@ class ValidateSchemaResponse(proto.Message): class ValidateMessageRequest(proto.Message): r"""Request for the ``ValidateMessage`` method. + Attributes: parent (str): Required. The name of the project in which to validate diff --git a/synth.metadata b/synth.metadata index 7036b40f6..fd4661251 100644 --- a/synth.metadata +++ b/synth.metadata @@ -3,16 +3,29 @@ { "git": { "name": ".", - "remote": "https://github.com/googleapis/python-pubsub.git", - "sha": "f1ee3463a89a1a994af0cc522d25bfd1c4412824" + "remote": "git@github.com:googleapis/python-pubsub.git", + "sha": "195dcba8db4e41d8f0394f2f946656eceed439ec" } }, { "git": { - "name": "googleapis", - "remote": "https://github.com/googleapis/googleapis.git", - "sha": "fe3cc5e650b8e52537f02549fe5fb49fc386f3a9", - "internalRef": "383459959" + "name": "synthtool", + "remote": "https://github.com/googleapis/synthtool.git", + "sha": "4124d245133c0f740ac5e6fa2e7daeba327f1297" + } + }, + { + "git": { + "name": "synthtool", + "remote": "https://github.com/googleapis/synthtool.git", + "sha": "4124d245133c0f740ac5e6fa2e7daeba327f1297" + } + }, + { + "git": { + "name": "synthtool", + "remote": "https://github.com/googleapis/synthtool.git", + "sha": "4124d245133c0f740ac5e6fa2e7daeba327f1297" } } ], @@ -26,130 +39,5 @@ "generator": "bazel" } } - ], - "generatedFiles": [ - ".coveragerc", - ".flake8", - ".github/CONTRIBUTING.md", - ".github/ISSUE_TEMPLATE/bug_report.md", - ".github/ISSUE_TEMPLATE/feature_request.md", - ".github/ISSUE_TEMPLATE/support_request.md", - ".github/PULL_REQUEST_TEMPLATE.md", - ".github/header-checker-lint.yml", - ".github/release-please.yml", - ".github/snippet-bot.yml", - ".gitignore", - ".kokoro/build.sh", - ".kokoro/continuous/common.cfg", - ".kokoro/continuous/continuous.cfg", - ".kokoro/docker/docs/Dockerfile", - ".kokoro/docs/common.cfg", - ".kokoro/docs/docs-presubmit.cfg", - ".kokoro/docs/docs.cfg", - ".kokoro/populate-secrets.sh", - ".kokoro/presubmit/common.cfg", - ".kokoro/presubmit/presubmit.cfg", - ".kokoro/publish-docs.sh", - ".kokoro/release.sh", - ".kokoro/release/common.cfg", - ".kokoro/release/release.cfg", - ".kokoro/samples/lint/common.cfg", - ".kokoro/samples/lint/continuous.cfg", - ".kokoro/samples/lint/periodic.cfg", - ".kokoro/samples/lint/presubmit.cfg", - ".kokoro/samples/python3.6/common.cfg", - ".kokoro/samples/python3.6/continuous.cfg", - ".kokoro/samples/python3.6/periodic-head.cfg", - ".kokoro/samples/python3.6/periodic.cfg", - ".kokoro/samples/python3.6/presubmit.cfg", - ".kokoro/samples/python3.7/common.cfg", - ".kokoro/samples/python3.7/continuous.cfg", - ".kokoro/samples/python3.7/periodic-head.cfg", - ".kokoro/samples/python3.7/periodic.cfg", - ".kokoro/samples/python3.7/presubmit.cfg", - ".kokoro/samples/python3.8/common.cfg", - ".kokoro/samples/python3.8/continuous.cfg", - ".kokoro/samples/python3.8/periodic-head.cfg", - ".kokoro/samples/python3.8/periodic.cfg", - ".kokoro/samples/python3.8/presubmit.cfg", - ".kokoro/samples/python3.9/common.cfg", - ".kokoro/samples/python3.9/continuous.cfg", - ".kokoro/samples/python3.9/periodic-head.cfg", - ".kokoro/samples/python3.9/periodic.cfg", - ".kokoro/samples/python3.9/presubmit.cfg", - ".kokoro/test-samples-against-head.sh", - ".kokoro/test-samples-impl.sh", - ".kokoro/test-samples.sh", - ".kokoro/trampoline.sh", - ".kokoro/trampoline_v2.sh", - ".pre-commit-config.yaml", - ".trampolinerc", - "CODE_OF_CONDUCT.md", - "CONTRIBUTING.rst", - "LICENSE", - "MANIFEST.in", - "SECURITY.md", - "docs/_static/custom.css", - "docs/_templates/layout.html", - "docs/conf.py", - "docs/multiprocessing.rst", - "google/cloud/pubsub_v1/proto/pubsub.proto", - "google/cloud/pubsub_v1/proto/schema.proto", - "google/pubsub/__init__.py", - "google/pubsub/py.typed", - "google/pubsub_v1/__init__.py", - "google/pubsub_v1/gapic_metadata.json", - "google/pubsub_v1/py.typed", - "google/pubsub_v1/services/__init__.py", - "google/pubsub_v1/services/publisher/__init__.py", - "google/pubsub_v1/services/publisher/async_client.py", - "google/pubsub_v1/services/publisher/client.py", - "google/pubsub_v1/services/publisher/pagers.py", - "google/pubsub_v1/services/publisher/transports/__init__.py", - "google/pubsub_v1/services/publisher/transports/base.py", - "google/pubsub_v1/services/publisher/transports/grpc.py", - "google/pubsub_v1/services/publisher/transports/grpc_asyncio.py", - "google/pubsub_v1/services/schema_service/__init__.py", - "google/pubsub_v1/services/schema_service/async_client.py", - "google/pubsub_v1/services/schema_service/client.py", - "google/pubsub_v1/services/schema_service/pagers.py", - "google/pubsub_v1/services/schema_service/transports/__init__.py", - "google/pubsub_v1/services/schema_service/transports/base.py", - "google/pubsub_v1/services/schema_service/transports/grpc.py", - "google/pubsub_v1/services/schema_service/transports/grpc_asyncio.py", - "google/pubsub_v1/services/subscriber/__init__.py", - "google/pubsub_v1/services/subscriber/async_client.py", - "google/pubsub_v1/services/subscriber/client.py", - "google/pubsub_v1/services/subscriber/pagers.py", - "google/pubsub_v1/services/subscriber/transports/__init__.py", - "google/pubsub_v1/services/subscriber/transports/base.py", - "google/pubsub_v1/services/subscriber/transports/grpc.py", - "google/pubsub_v1/services/subscriber/transports/grpc_asyncio.py", - "google/pubsub_v1/types/__init__.py", - "google/pubsub_v1/types/pubsub.py", - "google/pubsub_v1/types/schema.py", - "mypy.ini", - "noxfile.py", - "renovate.json", - "samples/AUTHORING_GUIDE.md", - "samples/CONTRIBUTING.md", - "samples/snippets/noxfile.py", - "scripts/decrypt-secrets.sh", - "scripts/fixup_pubsub_v1_keywords.py", - "scripts/readme-gen/readme_gen.py", - "scripts/readme-gen/templates/README.tmpl.rst", - "scripts/readme-gen/templates/auth.tmpl.rst", - "scripts/readme-gen/templates/auth_api_key.tmpl.rst", - "scripts/readme-gen/templates/install_deps.tmpl.rst", - "scripts/readme-gen/templates/install_portaudio.tmpl.rst", - "setup.cfg", - "testing/.gitignore", - "tests/__init__.py", - "tests/unit/__init__.py", - "tests/unit/gapic/__init__.py", - "tests/unit/gapic/pubsub_v1/__init__.py", - "tests/unit/gapic/pubsub_v1/test_publisher.py", - "tests/unit/gapic/pubsub_v1/test_schema_service.py", - "tests/unit/gapic/pubsub_v1/test_subscriber.py" ] } \ No newline at end of file From b48db21593773c8b462a322a51ff1507ed89c3e5 Mon Sep 17 00:00:00 2001 From: Anthonios Partheniou Date: Sun, 18 Jul 2021 10:48:25 +0000 Subject: [PATCH 16/18] run synthool locally --- .../services/publisher/async_client.py | 9 -- google/pubsub_v1/types/__init__.py | 2 - synth.metadata | 142 +----------------- 3 files changed, 2 insertions(+), 151 deletions(-) diff --git a/google/pubsub_v1/services/publisher/async_client.py b/google/pubsub_v1/services/publisher/async_client.py index 05d34e3f2..09e4b0e55 100644 --- a/google/pubsub_v1/services/publisher/async_client.py +++ b/google/pubsub_v1/services/publisher/async_client.py @@ -32,7 +32,6 @@ from google.pubsub_v1.services.publisher import pagers from google.pubsub_v1.types import pubsub from google.pubsub_v1.types import TimeoutType - from .transports.base import PublisherTransport, DEFAULT_CLIENT_INFO from .transports.grpc_asyncio import PublisherGrpcAsyncIOTransport from .client import PublisherClient @@ -266,7 +265,6 @@ async def update_topic( Args: request (:class:`google.pubsub_v1.types.UpdateTopicRequest`): The request object. Request for the UpdateTopic method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (TimeoutType): @@ -341,7 +339,6 @@ async def 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 (TimeoutType): @@ -428,7 +425,6 @@ async def get_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 (TimeoutType): @@ -509,7 +505,6 @@ async def list_topics( 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 (TimeoutType): @@ -603,7 +598,6 @@ async def list_topic_subscriptions( 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 (TimeoutType): @@ -701,7 +695,6 @@ async def list_topic_snapshots( 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 (TimeoutType): @@ -798,7 +791,6 @@ async def delete_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 (TimeoutType): @@ -869,7 +861,6 @@ async def detach_subscription( request (:class:`google.pubsub_v1.types.DetachSubscriptionRequest`): The request object. Request for the DetachSubscription method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (TimeoutType): diff --git a/google/pubsub_v1/types/__init__.py b/google/pubsub_v1/types/__init__.py index 5203abfe7..ebc8b5399 100644 --- a/google/pubsub_v1/types/__init__.py +++ b/google/pubsub_v1/types/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from typing import Union from .pubsub import ( diff --git a/synth.metadata b/synth.metadata index c9890856c..ca1d82ffb 100644 --- a/synth.metadata +++ b/synth.metadata @@ -4,29 +4,7 @@ "git": { "name": ".", "remote": "git@github.com:googleapis/python-pubsub.git", - "sha": "195dcba8db4e41d8f0394f2f946656eceed439ec" - } - }, - { - "git": { - "name": "googleapis", - "remote": "https://github.com/googleapis/googleapis.git", - "sha": "6598bb829c9e9a534be674649ffd1b4671a821f9", - "internalRef": "364449524" - } - }, - { - "git": { - "name": "synthtool", - "remote": "https://github.com/googleapis/synthtool.git", - "sha": "043cc620d6a6111816d9e09f2a97208565fde958" - } - }, - { - "git": { - "name": "synthtool", - "remote": "https://github.com/googleapis/synthtool.git", - "sha": "043cc620d6a6111816d9e09f2a97208565fde958" + "sha": "618ceeefab8f1f7f968ee42a94453afde4d58f7b" } }, { @@ -61,121 +39,5 @@ "generator": "bazel" } } - ], - "generatedFiles": [ - ".coveragerc", - ".flake8", - ".github/CONTRIBUTING.md", - ".github/ISSUE_TEMPLATE/bug_report.md", - ".github/ISSUE_TEMPLATE/feature_request.md", - ".github/ISSUE_TEMPLATE/support_request.md", - ".github/PULL_REQUEST_TEMPLATE.md", - ".github/header-checker-lint.yml", - ".github/release-please.yml", - ".github/snippet-bot.yml", - ".gitignore", - ".kokoro/build.sh", - ".kokoro/continuous/common.cfg", - ".kokoro/continuous/continuous.cfg", - ".kokoro/docker/docs/Dockerfile", - ".kokoro/docker/docs/fetch_gpg_keys.sh", - ".kokoro/docs/common.cfg", - ".kokoro/docs/docs-presubmit.cfg", - ".kokoro/docs/docs.cfg", - ".kokoro/populate-secrets.sh", - ".kokoro/presubmit/common.cfg", - ".kokoro/presubmit/presubmit.cfg", - ".kokoro/publish-docs.sh", - ".kokoro/release.sh", - ".kokoro/release/common.cfg", - ".kokoro/release/release.cfg", - ".kokoro/samples/lint/common.cfg", - ".kokoro/samples/lint/continuous.cfg", - ".kokoro/samples/lint/periodic.cfg", - ".kokoro/samples/lint/presubmit.cfg", - ".kokoro/samples/python3.6/common.cfg", - ".kokoro/samples/python3.6/continuous.cfg", - ".kokoro/samples/python3.6/periodic-head.cfg", - ".kokoro/samples/python3.6/periodic.cfg", - ".kokoro/samples/python3.6/presubmit.cfg", - ".kokoro/samples/python3.7/common.cfg", - ".kokoro/samples/python3.7/continuous.cfg", - ".kokoro/samples/python3.7/periodic-head.cfg", - ".kokoro/samples/python3.7/periodic.cfg", - ".kokoro/samples/python3.7/presubmit.cfg", - ".kokoro/samples/python3.8/common.cfg", - ".kokoro/samples/python3.8/continuous.cfg", - ".kokoro/samples/python3.8/periodic-head.cfg", - ".kokoro/samples/python3.8/periodic.cfg", - ".kokoro/samples/python3.8/presubmit.cfg", - ".kokoro/test-samples-against-head.sh", - ".kokoro/test-samples-impl.sh", - ".kokoro/test-samples.sh", - ".kokoro/trampoline.sh", - ".kokoro/trampoline_v2.sh", - ".pre-commit-config.yaml", - ".trampolinerc", - "CODE_OF_CONDUCT.md", - "CONTRIBUTING.rst", - "LICENSE", - "MANIFEST.in", - "docs/_static/custom.css", - "docs/_templates/layout.html", - "docs/conf.py", - "docs/multiprocessing.rst", - "google/cloud/pubsub_v1/proto/pubsub.proto", - "google/cloud/pubsub_v1/proto/schema.proto", - "google/pubsub/__init__.py", - "google/pubsub/py.typed", - "google/pubsub_v1/__init__.py", - "google/pubsub_v1/py.typed", - "google/pubsub_v1/services/__init__.py", - "google/pubsub_v1/services/publisher/__init__.py", - "google/pubsub_v1/services/publisher/async_client.py", - "google/pubsub_v1/services/publisher/client.py", - "google/pubsub_v1/services/publisher/pagers.py", - "google/pubsub_v1/services/publisher/transports/__init__.py", - "google/pubsub_v1/services/publisher/transports/base.py", - "google/pubsub_v1/services/publisher/transports/grpc.py", - "google/pubsub_v1/services/publisher/transports/grpc_asyncio.py", - "google/pubsub_v1/services/schema_service/__init__.py", - "google/pubsub_v1/services/schema_service/async_client.py", - "google/pubsub_v1/services/schema_service/client.py", - "google/pubsub_v1/services/schema_service/pagers.py", - "google/pubsub_v1/services/schema_service/transports/__init__.py", - "google/pubsub_v1/services/schema_service/transports/base.py", - "google/pubsub_v1/services/schema_service/transports/grpc.py", - "google/pubsub_v1/services/schema_service/transports/grpc_asyncio.py", - "google/pubsub_v1/services/subscriber/__init__.py", - "google/pubsub_v1/services/subscriber/async_client.py", - "google/pubsub_v1/services/subscriber/client.py", - "google/pubsub_v1/services/subscriber/pagers.py", - "google/pubsub_v1/services/subscriber/transports/__init__.py", - "google/pubsub_v1/services/subscriber/transports/base.py", - "google/pubsub_v1/services/subscriber/transports/grpc.py", - "google/pubsub_v1/services/subscriber/transports/grpc_asyncio.py", - "google/pubsub_v1/types/__init__.py", - "google/pubsub_v1/types/pubsub.py", - "google/pubsub_v1/types/schema.py", - "mypy.ini", - "noxfile.py", - "renovate.json", - "samples/AUTHORING_GUIDE.md", - "samples/CONTRIBUTING.md", - "samples/snippets/noxfile.py", - "scripts/decrypt-secrets.sh", - "scripts/fixup_pubsub_v1_keywords.py", - "scripts/readme-gen/readme_gen.py", - "scripts/readme-gen/templates/README.tmpl.rst", - "scripts/readme-gen/templates/auth.tmpl.rst", - "scripts/readme-gen/templates/auth_api_key.tmpl.rst", - "scripts/readme-gen/templates/install_deps.tmpl.rst", - "scripts/readme-gen/templates/install_portaudio.tmpl.rst", - "setup.cfg", - "testing/.gitignore", - "tests/unit/gapic/pubsub_v1/__init__.py", - "tests/unit/gapic/pubsub_v1/test_publisher.py", - "tests/unit/gapic/pubsub_v1/test_schema_service.py", - "tests/unit/gapic/pubsub_v1/test_subscriber.py" ] -} +} \ No newline at end of file From b82f5a7d824b6455c89218cdeac87f1704ba2430 Mon Sep 17 00:00:00 2001 From: Anthonios Partheniou Date: Sat, 17 Jul 2021 11:33:21 +0000 Subject: [PATCH 17/18] fix: require google-api-core >= 1.26.0 --- setup.py | 2 +- testing/constraints-3.6.txt | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/setup.py b/setup.py index 2e1d57520..d9dc0f72e 100644 --- a/setup.py +++ b/setup.py @@ -30,7 +30,7 @@ release_status = "Development Status :: 5 - Production/Stable" dependencies = [ "grpcio >= 1.38.1, < 2.0dev", # https://github.com/googleapis/python-pubsub/issues/414 - "google-api-core[grpc] >= 1.22.2, < 2.0.0dev", + "google-api-core[grpc] >= 1.26.0, < 2.0.0dev", "libcst >= 0.3.10", "proto-plus >= 1.7.1", "grpc-google-iam-v1 >= 0.12.3, < 0.13dev", diff --git a/testing/constraints-3.6.txt b/testing/constraints-3.6.txt index 3d58c3f9c..a7cf1bf31 100644 --- a/testing/constraints-3.6.txt +++ b/testing/constraints-3.6.txt @@ -6,7 +6,7 @@ # e.g., if setup.py has "foo >= 1.14.0, < 2.0.0dev", # Then this file should have foo==1.14.0 grpcio==1.38.1 -google-api-core==1.22.2 +google-api-core==1.26.0 libcst==0.3.10 proto-plus==1.7.1 grpc-google-iam-v1==0.12.3 \ No newline at end of file From 412d31f3376d8fcc3864f62150a9156cd6cee6e5 Mon Sep 17 00:00:00 2001 From: Anthonios Partheniou Date: Sun, 18 Jul 2021 11:24:10 +0000 Subject: [PATCH 18/18] fix(deps): add packaging requirement --- setup.py | 1 + testing/constraints-3.6.txt | 5 +++-- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/setup.py b/setup.py index d9dc0f72e..5b05b39a3 100644 --- a/setup.py +++ b/setup.py @@ -34,6 +34,7 @@ "libcst >= 0.3.10", "proto-plus >= 1.7.1", "grpc-google-iam-v1 >= 0.12.3, < 0.13dev", + "packaging >= 14.3", ] extras = {} diff --git a/testing/constraints-3.6.txt b/testing/constraints-3.6.txt index a7cf1bf31..73677dc23 100644 --- a/testing/constraints-3.6.txt +++ b/testing/constraints-3.6.txt @@ -2,11 +2,12 @@ # are correct in setup.py # List *all* library dependencies and extras in this file. # Pin the version to the lower bound. -# # e.g., if setup.py has "foo >= 1.14.0, < 2.0.0dev", # Then this file should have foo==1.14.0 grpcio==1.38.1 google-api-core==1.26.0 libcst==0.3.10 proto-plus==1.7.1 -grpc-google-iam-v1==0.12.3 \ No newline at end of file +grpc-google-iam-v1==0.12.3 +packaging==14.3 +google-auth==1.24.0 # TODO: remove when google-auth>=1.25.0 is transitively required through google-api-core