From fc8fac61de381481c1c199078a4df5f9b50ad791 Mon Sep 17 00:00:00 2001 From: Anthonios Partheniou Date: Wed, 12 May 2021 21:41:41 -0400 Subject: [PATCH 01/14] chore: migrate to owl bot --- .github/.OwlBot.lock.yaml | 4 + .github/.OwlBot.yaml | 26 ++++ owlbot.py | 267 ++++++++++++++++++++++++++++++++++++ synth.metadata | 167 ----------------------- synth.py | 275 -------------------------------------- 5 files changed, 297 insertions(+), 442 deletions(-) create mode 100644 .github/.OwlBot.lock.yaml create mode 100644 .github/.OwlBot.yaml create mode 100644 owlbot.py delete mode 100644 synth.metadata delete mode 100644 synth.py diff --git a/.github/.OwlBot.lock.yaml b/.github/.OwlBot.lock.yaml new file mode 100644 index 000000000..d49860b32 --- /dev/null +++ b/.github/.OwlBot.lock.yaml @@ -0,0 +1,4 @@ +docker: + digest: sha256:457583330eec64daa02aeb7a72a04d33e7be2428f646671ce4045dcbc0191b1e + image: gcr.io/repo-automation-bots/owlbot-python:latest + diff --git a/.github/.OwlBot.yaml b/.github/.OwlBot.yaml new file mode 100644 index 000000000..43e208e72 --- /dev/null +++ b/.github/.OwlBot.yaml @@ -0,0 +1,26 @@ +# 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. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +docker: + image: gcr.io/repo-automation-bots/owlbot-python:latest + +deep-remove-regex: + - /owl-bot-staging + +deep-copy-regex: + - source: /google/pubsub/(v.*)/.*-py/(.*) + dest: /owl-bot-staging/$1/$2 + +begin-after-commit-hash: 40278112d2922ec917140dcb5cc6d5ef2923aeb2 + diff --git a/owlbot.py b/owlbot.py new file mode 100644 index 000000000..ed6865c24 --- /dev/null +++ b/owlbot.py @@ -0,0 +1,267 @@ +# Copyright 2018 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""This script is used to synthesize generated parts of this library.""" + +import re +import textwrap + +import synthtool as s +from synthtool import gcp +from synthtool.languages import python + +common = gcp.CommonTemplates() + +default_version = "v1" + +for library in s.get_staging_dirs(default_version): + # DEFAULT SCOPES and SERVICE_ADDRESS are being used. so let's force them in. + s.replace( + library / f"google/pubsub_{library.name}/services/*er/*client.py", + r"DEFAULT_ENDPOINT = 'pubsub\.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.\""" + + \g<0>""", + ) + + # Modify GRPC options in transports. + count = s.replace( + [ + library / f"google/pubsub_{library.name}/services/*/transports/grpc*", + library / f"tests/unit/gapic/pubsub_{library.name}/*" + ], + "options=\[.*?\]", + """options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ("grpc.keepalive_time_ms", 30000), + ]""", + flags=re.MULTILINE | re.DOTALL, + ) + + if count < 15: + raise Exception("Expected replacements for gRPC channel options not made.") + + # If the emulator is used, force an insecure gRPC channel to avoid SSL errors. + clients_to_patch = [ + library / f"google/pubsub_{library.name}/services/publisher/client.py", + library / f"google/pubsub_{library.name}/services/subscriber/client.py", + ] + err_msg = "Expected replacements for gRPC channel to use with the emulator not made." + + count = s.replace( + clients_to_patch, + r"import os", + "import functools\n\g<0>" + ) + + if count < len(clients_to_patch): + raise Exception(err_msg) + + count = s.replace( + clients_to_patch, + f"from google\.pubsub_{library.name}\.types import pubsub", + "\g<0>\n\nimport grpc" + ) + + if count < len(clients_to_patch): + raise Exception(err_msg) + + count = s.replace( + clients_to_patch, + r"Transport = type\(self\)\.get_transport_class\(transport\)", + """\g<0> + + emulator_host = os.environ.get("PUBSUB_EMULATOR_HOST") + if emulator_host: + if issubclass(Transport, type(self)._transport_registry["grpc"]): + channel = grpc.insecure_channel(target=emulator_host) + else: + channel = grpc.aio.insecure_channel(target=emulator_host) + Transport = functools.partial(Transport, channel=channel) + + """, + ) + + if count < len(clients_to_patch): + raise Exception(err_msg) + + # Monkey patch the streaming_pull() GAPIC method to disable pre-fetching stream + # results. + s.replace( + library / f"google/pubsub_{library.name}/services/subscriber/client.py", + ( + r"# Wrap the RPC method.*\n" + r"\s+# and friendly error.*\n" + r"\s+rpc = self\._transport\._wrapped_methods\[self\._transport\.streaming_pull\]" + ), + """ + # Wrappers in api-core should not automatically pre-fetch the first + # stream result, as this breaks the stream when re-opening it. + # https://github.com/googleapis/python-pubsub/issues/93#issuecomment-630762257 + self._transport.streaming_pull._prefetch_first_result_ = False + + \g<0>""", + ) + + # Emit deprecation warning if return_immediately flag is set with synchronous pull. + s.replace( + library / f"google/pubsub_{library.name}/services/subscriber/*client.py", + r"import pkg_resources", + "import warnings\n\g<0>", + ) + + count = s.replace( + library / f"google/pubsub_{library.name}/services/subscriber/*client.py", + r""" + ([^\n\S]+(?:async\ )?def\ pull\(.*?->\ pubsub\.PullResponse:.*?) + ((?P[^\n\S]+)\#\ Wrap\ the\ RPC\ method) + """, + textwrap.dedent( + """ + \g<1> + \gif request.return_immediately: + \g warnings.warn( + \g "The return_immediately flag is deprecated and should be set to False.", + \g category=DeprecationWarning, + \g ) + + \g<2>"""), + flags=re.MULTILINE | re.DOTALL | re.VERBOSE, + ) + + if count != 2: + raise Exception("Too many or too few replacements in pull() methods.") + + # Silence deprecation warnings in pull() method flattened parameter tests. + s.replace( + library / f"tests/unit/gapic/pubsub_{library.name}/test_subscriber.py", + "import mock", + "\g<0>\nimport warnings", + ) + + count = s.replace( + library / f"tests/unit/gapic/pubsub_{library.name}/test_subscriber.py", + textwrap.dedent( + r""" + ([^\n\S]+# Call the method with a truthy value for each flattened field, + [^\n\S]+# using the keyword arguments to the method\.) + \s+(client\.pull\(.*?\))""" + ), + """\n\g<1> + with warnings.catch_warnings(): + warnings.simplefilter("ignore", category=DeprecationWarning) + \g<2>""", + flags = re.MULTILINE | re.DOTALL, + ) + + if count < 1: + raise Exception("Catch warnings replacement failed.") + + count = s.replace( + library / f"tests/unit/gapic/pubsub_{library.name}/test_subscriber.py", + textwrap.dedent( + r""" + ([^\n\S]+# Call the method with a truthy value for each flattened field, + [^\n\S]+# using the keyword arguments to the method\.) + \s+response = (await client\.pull\(.*?\))""" + ), + """\n\g<1> + with warnings.catch_warnings(): + warnings.simplefilter("ignore", category=DeprecationWarning) + \g<2>""", + flags = re.MULTILINE | re.DOTALL, + ) + + if count < 1: + raise Exception("Catch warnings replacement failed.") + + # Make sure that client library version is present in user agent header. + s.replace( + [ + library / f"google/pubsub_{library.name}/services/publisher/async_client.py", + library / f"google/pubsub_{library.name}/services/publisher/client.py", + library / f"google/pubsub_{library.name}/services/publisher/transports/base.py", + library / f"google/pubsub_{library.name}/services/schema_service/async_client.py", + library / f"google/pubsub_{library.name}/services/schema_service/client.py", + library / f"google/pubsub_{library.name}/services/schema_service/transports/base.py", + library / f"google/pubsub_{library.name}/services/subscriber/async_client.py", + library / f"google/pubsub_{library.name}/services/subscriber/client.py", + library / f"google/pubsub_{library.name}/services/subscriber/transports/base.py", + ], + r"""gapic_version=(pkg_resources\.get_distribution\(\s+)['"]google-pubsub['"]""", + "client_library_version=\g<1>'google-cloud-pubsub'", + ) + + # Docstrings of *_iam_policy() methods are formatted poorly and must be fixed + # in order to avoid docstring format warnings in docs. + s.replace(library / f"google/pubsub_{library.name}/services/*er/client.py", r"(\s+)Args:", "\n\g<1>Args:") + s.replace( + library / f"google/pubsub_{library.name}/services/*er/client.py", + r"(\s+)\*\*JSON Example\*\*\s+::", + "\n\g<1>**JSON Example**::\n", + ) + + s.replace( + library / f"google/pubsub_{library.name}/services/*er/client.py", + r"(\s+)\*\*YAML Example\*\*\s+::", + "\n\g<1>**YAML Example**::\n", + ) + + s.replace( + library / f"google/pubsub_{library.name}/services/*er/client.py", + r"(\s+)For a description of IAM and its features, see", + "\n\g<0>", + ) + + s.move( + library, + excludes=[ + "docs/**/*", + "nox.py", + "README.rst", + "setup.py", + f"google/cloud/pubsub_{library.name}/__init__.py", + f"google/cloud/pubsub_{library.name}/types.py", + ], + ) + +s.remove_staging_dirs() + +# ---------------------------------------------------------------------------- +# Add templated files +# ---------------------------------------------------------------------------- +templated_files = gcp.CommonTemplates().py_library( + microgenerator=True, + samples=True, + cov_level=100, + system_test_external_dependencies=["psutil"], +) +s.move(templated_files, excludes=[".coveragerc"]) + +# ---------------------------------------------------------------------------- +# Samples templates +# ---------------------------------------------------------------------------- +python.py_samples() + +s.shell.run(["nox", "-s", "blacken"], hide_output=False) diff --git a/synth.metadata b/synth.metadata deleted file mode 100644 index 02da2833c..000000000 --- a/synth.metadata +++ /dev/null @@ -1,167 +0,0 @@ -{ - "sources": [ - { - "git": { - "name": ".", - "remote": "https://github.com/googleapis/python-pubsub.git", - "sha": "b8352f91c63e0cb7d64c4d0e557651248cd301b5" - } - }, - { - "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" - } - }, - { - "git": { - "name": "synthtool", - "remote": "https://github.com/googleapis/synthtool.git", - "sha": "043cc620d6a6111816d9e09f2a97208565fde958" - } - } - ], - "destinations": [ - { - "client": { - "source": "googleapis", - "apiName": "pubsub", - "apiVersion": "v1", - "language": "python", - "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 diff --git a/synth.py b/synth.py deleted file mode 100644 index 2ad5d20de..000000000 --- a/synth.py +++ /dev/null @@ -1,275 +0,0 @@ -# Copyright 2018 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""This script is used to synthesize generated parts of this library.""" - -import re -import textwrap - -import synthtool as s -from synthtool import gcp -from synthtool.languages import python - -gapic = gcp.GAPICBazel() -common = gcp.CommonTemplates() -version = "v1" - -# ---------------------------------------------------------------------------- -# Generate pubsub GAPIC layer -# ---------------------------------------------------------------------------- -library = gapic.py_library( - service="pubsub", - version=version, - bazel_target="//google/pubsub/v1:pubsub-v1-py", - include_protos=True, -) -s.move( - library, - excludes=[ - "docs/**/*", - "nox.py", - "README.rst", - "setup.py", - "google/cloud/pubsub_v1/__init__.py", - "google/cloud/pubsub_v1/types.py", - ], -) - -# 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'", - """ - # 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.\""" - - \g<0>""", -) - -# Modify GRPC options in transports. -count = s.replace( - ["google/pubsub_v1/services/*/transports/grpc*", "tests/unit/gapic/pubsub_v1/*"], - "options=\[.*?\]", - """options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ("grpc.keepalive_time_ms", 30000), - ]""", - flags=re.MULTILINE | re.DOTALL, -) - -if count < 15: - raise Exception("Expected replacements for gRPC channel options not made.") - -# If the emulator is used, force an insecure gRPC channel to avoid SSL errors. -clients_to_patch = [ - "google/pubsub_v1/services/publisher/client.py", - "google/pubsub_v1/services/subscriber/client.py", -] -err_msg = "Expected replacements for gRPC channel to use with the emulator not made." - -count = s.replace( - clients_to_patch, - r"import os", - "import functools\n\g<0>" -) - -if count < len(clients_to_patch): - raise Exception(err_msg) - -count = s.replace( - clients_to_patch, - r"from google\.pubsub_v1\.types import pubsub", - "\g<0>\n\nimport grpc" -) - -if count < len(clients_to_patch): - raise Exception(err_msg) - -count = s.replace( - clients_to_patch, - r"Transport = type\(self\)\.get_transport_class\(transport\)", - """\g<0> - - emulator_host = os.environ.get("PUBSUB_EMULATOR_HOST") - if emulator_host: - if issubclass(Transport, type(self)._transport_registry["grpc"]): - channel = grpc.insecure_channel(target=emulator_host) - else: - channel = grpc.aio.insecure_channel(target=emulator_host) - Transport = functools.partial(Transport, channel=channel) - - """, -) - -if count < len(clients_to_patch): - raise Exception(err_msg) - -# Monkey patch the streaming_pull() GAPIC method to disable pre-fetching stream -# results. -s.replace( - "google/pubsub_v1/services/subscriber/client.py", - ( - r"# Wrap the RPC method.*\n" - r"\s+# and friendly error.*\n" - r"\s+rpc = self\._transport\._wrapped_methods\[self\._transport\.streaming_pull\]" - ), - """ - # Wrappers in api-core should not automatically pre-fetch the first - # stream result, as this breaks the stream when re-opening it. - # https://github.com/googleapis/python-pubsub/issues/93#issuecomment-630762257 - self._transport.streaming_pull._prefetch_first_result_ = False - - \g<0>""", -) - -# Emit deprecation warning if return_immediately flag is set with synchronous pull. -s.replace( - "google/pubsub_v1/services/subscriber/*client.py", - r"import pkg_resources", - "import warnings\n\g<0>", -) -count = s.replace( - "google/pubsub_v1/services/subscriber/*client.py", - r""" - ([^\n\S]+(?:async\ )?def\ pull\(.*?->\ pubsub\.PullResponse:.*?) - ((?P[^\n\S]+)\#\ Wrap\ the\ RPC\ method) - """, - textwrap.dedent( - """ - \g<1> - \gif request.return_immediately: - \g warnings.warn( - \g "The return_immediately flag is deprecated and should be set to False.", - \g category=DeprecationWarning, - \g ) - - \g<2>""" - ), - flags=re.MULTILINE | re.DOTALL | re.VERBOSE, -) - -if count != 2: - raise Exception("Too many or too few replacements in pull() methods.") - -# Silence deprecation warnings in pull() method flattened parameter tests. -s.replace( - "tests/unit/gapic/pubsub_v1/test_subscriber.py", - "import mock", - "\g<0>\nimport warnings", -) -count = s.replace( - "tests/unit/gapic/pubsub_v1/test_subscriber.py", - textwrap.dedent( - r""" - ([^\n\S]+# Call the method with a truthy value for each flattened field, - [^\n\S]+# using the keyword arguments to the method\.) - \s+(client\.pull\(.*?\))""" - ), - """\n\g<1> - with warnings.catch_warnings(): - warnings.simplefilter("ignore", category=DeprecationWarning) - \g<2>""", - flags = re.MULTILINE | re.DOTALL, -) - -if count < 1: - raise Exception("Catch warnings replacement failed.") - -count = s.replace( - "tests/unit/gapic/pubsub_v1/test_subscriber.py", - textwrap.dedent( - r""" - ([^\n\S]+# Call the method with a truthy value for each flattened field, - [^\n\S]+# using the keyword arguments to the method\.) - \s+response = (await client\.pull\(.*?\))""" - ), - """\n\g<1> - with warnings.catch_warnings(): - warnings.simplefilter("ignore", category=DeprecationWarning) - \g<2>""", - flags = re.MULTILINE | re.DOTALL, -) - -if count < 1: - raise Exception("Catch warnings replacement failed.") - -# Make sure that client library version is present in user agent header. -s.replace( - [ - "google/pubsub_v1/services/publisher/async_client.py", - "google/pubsub_v1/services/publisher/client.py", - "google/pubsub_v1/services/publisher/transports/base.py", - "google/pubsub_v1/services/schema_service/async_client.py", - "google/pubsub_v1/services/schema_service/client.py", - "google/pubsub_v1/services/schema_service/transports/base.py", - "google/pubsub_v1/services/subscriber/async_client.py", - "google/pubsub_v1/services/subscriber/client.py", - "google/pubsub_v1/services/subscriber/transports/base.py", - ], - r"""gapic_version=(pkg_resources\.get_distribution\(\s+)['"]google-pubsub['"]""", - "client_library_version=\g<1>'google-cloud-pubsub'", -) - -# Docstrings of *_iam_policy() methods are formatted poorly and must be fixed -# in order to avoid docstring format warnings in docs. -s.replace("google/pubsub_v1/services/*er/client.py", r"(\s+)Args:", "\n\g<1>Args:") -s.replace( - "google/pubsub_v1/services/*er/client.py", - r"(\s+)\*\*JSON Example\*\*\s+::", - "\n\g<1>**JSON Example**::\n", -) -s.replace( - "google/pubsub_v1/services/*er/client.py", - r"(\s+)\*\*YAML Example\*\*\s+::", - "\n\g<1>**YAML Example**::\n", -) -s.replace( - "google/pubsub_v1/services/*er/client.py", - r"(\s+)For a description of IAM and its features, see", - "\n\g<0>", -) - -# The namespace package declaration in google/cloud/__init__.py should be excluded -# from coverage. -s.replace( - ".coveragerc", - r"((?P[^\n\S]+)google/pubsub/__init__\.py)", - "\ggoogle/cloud/__init__.py\n\g<0>", -) - -# ---------------------------------------------------------------------------- -# Add templated files -# ---------------------------------------------------------------------------- -templated_files = gcp.CommonTemplates().py_library( - microgenerator=True, - samples=True, - cov_level=100, - system_test_external_dependencies=["psutil"], -) -s.move(templated_files, excludes=[".coveragerc"]) - -# ---------------------------------------------------------------------------- -# Samples templates -# ---------------------------------------------------------------------------- -python.py_samples() - -s.shell.run(["nox", "-s", "blacken"], hide_output=False) From 82406f5c8f0a9bf41735292f11be5db59de7511d Mon Sep 17 00:00:00 2001 From: Anthonios Partheniou Date: Wed, 12 May 2021 21:43:17 -0400 Subject: [PATCH 02/14] chore: copy files from googleapis-gen 40278112d2922ec917140dcb5cc6d5ef2923aeb2 --- owl-bot-staging/v1/MANIFEST.in | 2 + owl-bot-staging/v1/README.rst | 49 + owl-bot-staging/v1/docs/conf.py | 378 ++ owl-bot-staging/v1/docs/index.rst | 7 + .../v1/docs/pubsub_v1/publisher.rst | 11 + .../v1/docs/pubsub_v1/schema_service.rst | 11 + .../v1/docs/pubsub_v1/services.rst | 8 + .../v1/docs/pubsub_v1/subscriber.rst | 11 + owl-bot-staging/v1/docs/pubsub_v1/types.rst | 7 + owl-bot-staging/v1/google/pubsub/__init__.py | 144 + owl-bot-staging/v1/google/pubsub/py.typed | 2 + .../v1/google/pubsub_v1/__init__.py | 139 + owl-bot-staging/v1/google/pubsub_v1/py.typed | 2 + .../v1/google/pubsub_v1/services/__init__.py | 16 + .../pubsub_v1/services/publisher/__init__.py | 24 + .../services/publisher/async_client.py | 1236 ++++ .../pubsub_v1/services/publisher/client.py | 1340 ++++ .../pubsub_v1/services/publisher/pagers.py | 386 ++ .../services/publisher/transports/__init__.py | 35 + .../services/publisher/transports/base.py | 368 ++ .../services/publisher/transports/grpc.py | 558 ++ .../publisher/transports/grpc_asyncio.py | 564 ++ .../services/schema_service/__init__.py | 24 + .../services/schema_service/async_client.py | 906 +++ .../services/schema_service/client.py | 1085 ++++ .../services/schema_service/pagers.py | 142 + .../schema_service/transports/__init__.py | 35 + .../schema_service/transports/base.py | 232 + .../schema_service/transports/grpc.py | 461 ++ .../schema_service/transports/grpc_asyncio.py | 467 ++ .../pubsub_v1/services/subscriber/__init__.py | 24 + .../services/subscriber/async_client.py | 1994 ++++++ .../pubsub_v1/services/subscriber/client.py | 2032 +++++++ .../pubsub_v1/services/subscriber/pagers.py | 264 + .../subscriber/transports/__init__.py | 35 + .../services/subscriber/transports/base.py | 533 ++ .../services/subscriber/transports/grpc.py | 820 +++ .../subscriber/transports/grpc_asyncio.py | 826 +++ .../v1/google/pubsub_v1/types/__init__.py | 136 + .../v1/google/pubsub_v1/types/pubsub.py | 1372 +++++ .../v1/google/pubsub_v1/types/schema.py | 262 + owl-bot-staging/v1/mypy.ini | 3 + owl-bot-staging/v1/noxfile.py | 72 + .../v1/scripts/fixup_pubsub_v1_keywords.py | 213 + owl-bot-staging/v1/setup.py | 56 + .../v1/tests/unit/gapic/pubsub_v1/__init__.py | 17 + .../unit/gapic/pubsub_v1/test_publisher.py | 3983 ++++++++++++ .../gapic/pubsub_v1/test_schema_service.py | 2900 +++++++++ .../unit/gapic/pubsub_v1/test_subscriber.py | 5363 +++++++++++++++++ 49 files changed, 29555 insertions(+) create mode 100644 owl-bot-staging/v1/MANIFEST.in create mode 100644 owl-bot-staging/v1/README.rst create mode 100644 owl-bot-staging/v1/docs/conf.py create mode 100644 owl-bot-staging/v1/docs/index.rst create mode 100644 owl-bot-staging/v1/docs/pubsub_v1/publisher.rst create mode 100644 owl-bot-staging/v1/docs/pubsub_v1/schema_service.rst create mode 100644 owl-bot-staging/v1/docs/pubsub_v1/services.rst create mode 100644 owl-bot-staging/v1/docs/pubsub_v1/subscriber.rst create mode 100644 owl-bot-staging/v1/docs/pubsub_v1/types.rst create mode 100644 owl-bot-staging/v1/google/pubsub/__init__.py create mode 100644 owl-bot-staging/v1/google/pubsub/py.typed create mode 100644 owl-bot-staging/v1/google/pubsub_v1/__init__.py create mode 100644 owl-bot-staging/v1/google/pubsub_v1/py.typed create mode 100644 owl-bot-staging/v1/google/pubsub_v1/services/__init__.py create mode 100644 owl-bot-staging/v1/google/pubsub_v1/services/publisher/__init__.py create mode 100644 owl-bot-staging/v1/google/pubsub_v1/services/publisher/async_client.py create mode 100644 owl-bot-staging/v1/google/pubsub_v1/services/publisher/client.py create mode 100644 owl-bot-staging/v1/google/pubsub_v1/services/publisher/pagers.py create mode 100644 owl-bot-staging/v1/google/pubsub_v1/services/publisher/transports/__init__.py create mode 100644 owl-bot-staging/v1/google/pubsub_v1/services/publisher/transports/base.py create mode 100644 owl-bot-staging/v1/google/pubsub_v1/services/publisher/transports/grpc.py create mode 100644 owl-bot-staging/v1/google/pubsub_v1/services/publisher/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/v1/google/pubsub_v1/services/schema_service/__init__.py create mode 100644 owl-bot-staging/v1/google/pubsub_v1/services/schema_service/async_client.py create mode 100644 owl-bot-staging/v1/google/pubsub_v1/services/schema_service/client.py create mode 100644 owl-bot-staging/v1/google/pubsub_v1/services/schema_service/pagers.py create mode 100644 owl-bot-staging/v1/google/pubsub_v1/services/schema_service/transports/__init__.py create mode 100644 owl-bot-staging/v1/google/pubsub_v1/services/schema_service/transports/base.py create mode 100644 owl-bot-staging/v1/google/pubsub_v1/services/schema_service/transports/grpc.py create mode 100644 owl-bot-staging/v1/google/pubsub_v1/services/schema_service/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/v1/google/pubsub_v1/services/subscriber/__init__.py create mode 100644 owl-bot-staging/v1/google/pubsub_v1/services/subscriber/async_client.py create mode 100644 owl-bot-staging/v1/google/pubsub_v1/services/subscriber/client.py create mode 100644 owl-bot-staging/v1/google/pubsub_v1/services/subscriber/pagers.py create mode 100644 owl-bot-staging/v1/google/pubsub_v1/services/subscriber/transports/__init__.py create mode 100644 owl-bot-staging/v1/google/pubsub_v1/services/subscriber/transports/base.py create mode 100644 owl-bot-staging/v1/google/pubsub_v1/services/subscriber/transports/grpc.py create mode 100644 owl-bot-staging/v1/google/pubsub_v1/services/subscriber/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/v1/google/pubsub_v1/types/__init__.py create mode 100644 owl-bot-staging/v1/google/pubsub_v1/types/pubsub.py create mode 100644 owl-bot-staging/v1/google/pubsub_v1/types/schema.py create mode 100644 owl-bot-staging/v1/mypy.ini create mode 100644 owl-bot-staging/v1/noxfile.py create mode 100644 owl-bot-staging/v1/scripts/fixup_pubsub_v1_keywords.py create mode 100644 owl-bot-staging/v1/setup.py create mode 100644 owl-bot-staging/v1/tests/unit/gapic/pubsub_v1/__init__.py create mode 100644 owl-bot-staging/v1/tests/unit/gapic/pubsub_v1/test_publisher.py create mode 100644 owl-bot-staging/v1/tests/unit/gapic/pubsub_v1/test_schema_service.py create mode 100644 owl-bot-staging/v1/tests/unit/gapic/pubsub_v1/test_subscriber.py diff --git a/owl-bot-staging/v1/MANIFEST.in b/owl-bot-staging/v1/MANIFEST.in new file mode 100644 index 000000000..4daeccbde --- /dev/null +++ b/owl-bot-staging/v1/MANIFEST.in @@ -0,0 +1,2 @@ +recursive-include google/pubsub *.py +recursive-include google/pubsub_v1 *.py diff --git a/owl-bot-staging/v1/README.rst b/owl-bot-staging/v1/README.rst new file mode 100644 index 000000000..4c7897d8f --- /dev/null +++ b/owl-bot-staging/v1/README.rst @@ -0,0 +1,49 @@ +Python Client for Google Pubsub API +================================================= + +Quick Start +----------- + +In order to use this library, you first need to go through the following steps: + +1. `Select or create a Cloud Platform project.`_ +2. `Enable billing for your project.`_ +3. Enable the Google Pubsub API. +4. `Setup Authentication.`_ + +.. _Select or create a Cloud Platform project.: https://console.cloud.google.com/project +.. _Enable billing for your project.: https://cloud.google.com/billing/docs/how-to/modify-project#enable_billing_for_a_project +.. _Setup Authentication.: https://googleapis.dev/python/google-api-core/latest/auth.html + +Installation +~~~~~~~~~~~~ + +Install this library in a `virtualenv`_ using pip. `virtualenv`_ is a tool to +create isolated Python environments. The basic problem it addresses is one of +dependencies and versions, and indirectly permissions. + +With `virtualenv`_, it's possible to install this library without needing system +install permissions, and without clashing with the installed system +dependencies. + +.. _`virtualenv`: https://virtualenv.pypa.io/en/latest/ + + +Mac/Linux +^^^^^^^^^ + +.. code-block:: console + + python3 -m venv + source /bin/activate + /bin/pip install /path/to/library + + +Windows +^^^^^^^ + +.. code-block:: console + + python3 -m venv + \Scripts\activate + \Scripts\pip.exe install \path\to\library diff --git a/owl-bot-staging/v1/docs/conf.py b/owl-bot-staging/v1/docs/conf.py new file mode 100644 index 000000000..3bfe4fa16 --- /dev/null +++ b/owl-bot-staging/v1/docs/conf.py @@ -0,0 +1,378 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +# +# google-pubsub documentation build configuration file +# +# This file is execfile()d with the current directory set to its +# containing dir. +# +# Note that not all possible configuration values are present in this +# autogenerated file. +# +# All configuration values have a default; values that are commented out +# serve to show the default. + +import sys +import os +import shlex + +# If extensions (or modules to document with autodoc) are in another directory, +# add these directories to sys.path here. If the directory is relative to the +# documentation root, use os.path.abspath to make it absolute, like shown here. +sys.path.insert(0, os.path.abspath("..")) + +__version__ = "0.1.0" + +# -- General configuration ------------------------------------------------ + +# If your documentation needs a minimal Sphinx version, state it here. +needs_sphinx = "1.6.3" + +# Add any Sphinx extension module names here, as strings. They can be +# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom +# ones. +extensions = [ + "sphinx.ext.autodoc", + "sphinx.ext.autosummary", + "sphinx.ext.intersphinx", + "sphinx.ext.coverage", + "sphinx.ext.napoleon", + "sphinx.ext.todo", + "sphinx.ext.viewcode", +] + +# autodoc/autosummary flags +autoclass_content = "both" +autodoc_default_flags = ["members"] +autosummary_generate = True + + +# Add any paths that contain templates here, relative to this directory. +templates_path = ["_templates"] + +# Allow markdown includes (so releases.md can include CHANGLEOG.md) +# http://www.sphinx-doc.org/en/master/markdown.html +source_parsers = {".md": "recommonmark.parser.CommonMarkParser"} + +# The suffix(es) of source filenames. +# You can specify multiple suffix as a list of string: +source_suffix = [".rst", ".md"] + +# The encoding of source files. +# source_encoding = 'utf-8-sig' + +# The master toctree document. +master_doc = "index" + +# General information about the project. +project = u"google-pubsub" +copyright = u"2020, Google, LLC" +author = u"Google APIs" # TODO: autogenerate this bit + +# The version info for the project you're documenting, acts as replacement for +# |version| and |release|, also used in various other places throughout the +# built documents. +# +# The full version, including alpha/beta/rc tags. +release = __version__ +# The short X.Y version. +version = ".".join(release.split(".")[0:2]) + +# The language for content autogenerated by Sphinx. Refer to documentation +# for a list of supported languages. +# +# This is also used if you do content translation via gettext catalogs. +# Usually you set "language" from the command line for these cases. +language = None + +# There are two options for replacing |today|: either, you set today to some +# non-false value, then it is used: +# today = '' +# Else, today_fmt is used as the format for a strftime call. +# today_fmt = '%B %d, %Y' + +# List of patterns, relative to source directory, that match files and +# directories to ignore when looking for source files. +exclude_patterns = ["_build"] + +# The reST default role (used for this markup: `text`) to use for all +# documents. +# default_role = None + +# If true, '()' will be appended to :func: etc. cross-reference text. +# add_function_parentheses = True + +# If true, the current module name will be prepended to all description +# unit titles (such as .. function::). +# add_module_names = True + +# If true, sectionauthor and moduleauthor directives will be shown in the +# output. They are ignored by default. +# show_authors = False + +# The name of the Pygments (syntax highlighting) style to use. +pygments_style = "sphinx" + +# A list of ignored prefixes for module index sorting. +# modindex_common_prefix = [] + +# If true, keep warnings as "system message" paragraphs in the built documents. +# keep_warnings = False + +# If true, `todo` and `todoList` produce output, else they produce nothing. +todo_include_todos = True + + +# -- Options for HTML output ---------------------------------------------- + +# The theme to use for HTML and HTML Help pages. See the documentation for +# a list of builtin themes. +html_theme = "alabaster" + +# Theme options are theme-specific and customize the look and feel of a theme +# further. For a list of options available for each theme, see the +# documentation. +html_theme_options = { + "description": "Google Client Libraries for Python", + "github_user": "googleapis", + "github_repo": "google-cloud-python", + "github_banner": True, + "font_family": "'Roboto', Georgia, sans", + "head_font_family": "'Roboto', Georgia, serif", + "code_font_family": "'Roboto Mono', 'Consolas', monospace", +} + +# Add any paths that contain custom themes here, relative to this directory. +# html_theme_path = [] + +# The name for this set of Sphinx documents. If None, it defaults to +# " v documentation". +# html_title = None + +# A shorter title for the navigation bar. Default is the same as html_title. +# html_short_title = None + +# The name of an image file (relative to this directory) to place at the top +# of the sidebar. +# html_logo = None + +# The name of an image file (within the static path) to use as favicon of the +# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 +# pixels large. +# html_favicon = None + +# Add any paths that contain custom static files (such as style sheets) here, +# relative to this directory. They are copied after the builtin static files, +# so a file named "default.css" will overwrite the builtin "default.css". +html_static_path = ["_static"] + +# Add any extra paths that contain custom files (such as robots.txt or +# .htaccess) here, relative to this directory. These files are copied +# directly to the root of the documentation. +# html_extra_path = [] + +# If not '', a 'Last updated on:' timestamp is inserted at every page bottom, +# using the given strftime format. +# html_last_updated_fmt = '%b %d, %Y' + +# If true, SmartyPants will be used to convert quotes and dashes to +# typographically correct entities. +# html_use_smartypants = True + +# Custom sidebar templates, maps document names to template names. +# html_sidebars = {} + +# Additional templates that should be rendered to pages, maps page names to +# template names. +# html_additional_pages = {} + +# If false, no module index is generated. +# html_domain_indices = True + +# If false, no index is generated. +# html_use_index = True + +# If true, the index is split into individual pages for each letter. +# html_split_index = False + +# If true, links to the reST sources are added to the pages. +# html_show_sourcelink = True + +# If true, "Created using Sphinx" is shown in the HTML footer. Default is True. +# html_show_sphinx = True + +# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. +# html_show_copyright = True + +# If true, an OpenSearch description file will be output, and all pages will +# contain a tag referring to it. The value of this option must be the +# base URL from which the finished HTML is served. +# html_use_opensearch = '' + +# This is the file name suffix for HTML files (e.g. ".xhtml"). +# html_file_suffix = None + +# Language to be used for generating the HTML full-text search index. +# Sphinx supports the following languages: +# 'da', 'de', 'en', 'es', 'fi', 'fr', 'hu', 'it', 'ja' +# 'nl', 'no', 'pt', 'ro', 'ru', 'sv', 'tr' +# html_search_language = 'en' + +# A dictionary with options for the search language support, empty by default. +# Now only 'ja' uses this config value +# html_search_options = {'type': 'default'} + +# The name of a javascript file (relative to the configuration directory) that +# implements a search results scorer. If empty, the default will be used. +# html_search_scorer = 'scorer.js' + +# Output file base name for HTML help builder. +htmlhelp_basename = "google-pubsub-doc" + +# -- Options for warnings ------------------------------------------------------ + + +suppress_warnings = [ + # Temporarily suppress this to avoid "more than one target found for + # cross-reference" warning, which are intractable for us to avoid while in + # a mono-repo. + # See https://github.com/sphinx-doc/sphinx/blob + # /2a65ffeef5c107c19084fabdd706cdff3f52d93c/sphinx/domains/python.py#L843 + "ref.python" +] + +# -- Options for LaTeX output --------------------------------------------- + +latex_elements = { + # The paper size ('letterpaper' or 'a4paper'). + # 'papersize': 'letterpaper', + # The font size ('10pt', '11pt' or '12pt'). + # 'pointsize': '10pt', + # Additional stuff for the LaTeX preamble. + # 'preamble': '', + # Latex figure (float) alignment + # 'figure_align': 'htbp', +} + +# Grouping the document tree into LaTeX files. List of tuples +# (source start file, target name, title, +# author, documentclass [howto, manual, or own class]). +latex_documents = [ + ( + master_doc, + "google-pubsub.tex", + u"google-pubsub Documentation", + author, + "manual", + ) +] + +# The name of an image file (relative to this directory) to place at the top of +# the title page. +# latex_logo = None + +# For "manual" documents, if this is true, then toplevel headings are parts, +# not chapters. +# latex_use_parts = False + +# If true, show page references after internal links. +# latex_show_pagerefs = False + +# If true, show URL addresses after external links. +# latex_show_urls = False + +# Documents to append as an appendix to all manuals. +# latex_appendices = [] + +# If false, no module index is generated. +# latex_domain_indices = True + + +# -- Options for manual page output --------------------------------------- + +# One entry per manual page. List of tuples +# (source start file, name, description, authors, manual section). +man_pages = [ + ( + master_doc, + "google-pubsub", + u"Google Pubsub Documentation", + [author], + 1, + ) +] + +# If true, show URL addresses after external links. +# man_show_urls = False + + +# -- Options for Texinfo output ------------------------------------------- + +# Grouping the document tree into Texinfo files. List of tuples +# (source start file, target name, title, author, +# dir menu entry, description, category) +texinfo_documents = [ + ( + master_doc, + "google-pubsub", + u"google-pubsub Documentation", + author, + "google-pubsub", + "GAPIC library for Google Pubsub API", + "APIs", + ) +] + +# Documents to append as an appendix to all manuals. +# texinfo_appendices = [] + +# If false, no module index is generated. +# texinfo_domain_indices = True + +# How to display URL addresses: 'footnote', 'no', or 'inline'. +# texinfo_show_urls = 'footnote' + +# If true, do not generate a @detailmenu in the "Top" node's menu. +# texinfo_no_detailmenu = False + + +# Example configuration for intersphinx: refer to the Python standard library. +intersphinx_mapping = { + "python": ("http://python.readthedocs.org/en/latest/", None), + "gax": ("https://gax-python.readthedocs.org/en/latest/", None), + "google-auth": ("https://google-auth.readthedocs.io/en/stable", None), + "google-gax": ("https://gax-python.readthedocs.io/en/latest/", None), + "google.api_core": ("https://googleapis.dev/python/google-api-core/latest/", None), + "grpc": ("https://grpc.io/grpc/python/", None), + "requests": ("http://requests.kennethreitz.org/en/stable/", None), + "proto": ("https://proto-plus-python.readthedocs.io/en/stable", None), + "protobuf": ("https://googleapis.dev/python/protobuf/latest/", None), +} + + +# Napoleon settings +napoleon_google_docstring = True +napoleon_numpy_docstring = True +napoleon_include_private_with_doc = False +napoleon_include_special_with_doc = True +napoleon_use_admonition_for_examples = False +napoleon_use_admonition_for_notes = False +napoleon_use_admonition_for_references = False +napoleon_use_ivar = False +napoleon_use_param = True +napoleon_use_rtype = True diff --git a/owl-bot-staging/v1/docs/index.rst b/owl-bot-staging/v1/docs/index.rst new file mode 100644 index 000000000..5cb0459d0 --- /dev/null +++ b/owl-bot-staging/v1/docs/index.rst @@ -0,0 +1,7 @@ +API Reference +------------- +.. toctree:: + :maxdepth: 2 + + pubsub_v1/services + pubsub_v1/types diff --git a/owl-bot-staging/v1/docs/pubsub_v1/publisher.rst b/owl-bot-staging/v1/docs/pubsub_v1/publisher.rst new file mode 100644 index 000000000..bc5c9c7d0 --- /dev/null +++ b/owl-bot-staging/v1/docs/pubsub_v1/publisher.rst @@ -0,0 +1,11 @@ +Publisher +--------------------------- + +.. automodule:: google.pubsub_v1.services.publisher + :members: + :inherited-members: + + +.. automodule:: google.pubsub_v1.services.publisher.pagers + :members: + :inherited-members: diff --git a/owl-bot-staging/v1/docs/pubsub_v1/schema_service.rst b/owl-bot-staging/v1/docs/pubsub_v1/schema_service.rst new file mode 100644 index 000000000..c52db7a12 --- /dev/null +++ b/owl-bot-staging/v1/docs/pubsub_v1/schema_service.rst @@ -0,0 +1,11 @@ +SchemaService +------------------------------- + +.. automodule:: google.pubsub_v1.services.schema_service + :members: + :inherited-members: + + +.. automodule:: google.pubsub_v1.services.schema_service.pagers + :members: + :inherited-members: diff --git a/owl-bot-staging/v1/docs/pubsub_v1/services.rst b/owl-bot-staging/v1/docs/pubsub_v1/services.rst new file mode 100644 index 000000000..6ab7d9e52 --- /dev/null +++ b/owl-bot-staging/v1/docs/pubsub_v1/services.rst @@ -0,0 +1,8 @@ +Services for Google Pubsub v1 API +================================= +.. toctree:: + :maxdepth: 2 + + publisher + schema_service + subscriber diff --git a/owl-bot-staging/v1/docs/pubsub_v1/subscriber.rst b/owl-bot-staging/v1/docs/pubsub_v1/subscriber.rst new file mode 100644 index 000000000..808840ed7 --- /dev/null +++ b/owl-bot-staging/v1/docs/pubsub_v1/subscriber.rst @@ -0,0 +1,11 @@ +Subscriber +---------------------------- + +.. automodule:: google.pubsub_v1.services.subscriber + :members: + :inherited-members: + + +.. automodule:: google.pubsub_v1.services.subscriber.pagers + :members: + :inherited-members: diff --git a/owl-bot-staging/v1/docs/pubsub_v1/types.rst b/owl-bot-staging/v1/docs/pubsub_v1/types.rst new file mode 100644 index 000000000..964dfe575 --- /dev/null +++ b/owl-bot-staging/v1/docs/pubsub_v1/types.rst @@ -0,0 +1,7 @@ +Types for Google Pubsub v1 API +============================== + +.. automodule:: google.pubsub_v1.types + :members: + :undoc-members: + :show-inheritance: diff --git a/owl-bot-staging/v1/google/pubsub/__init__.py b/owl-bot-staging/v1/google/pubsub/__init__.py new file mode 100644 index 000000000..3af00486b --- /dev/null +++ b/owl-bot-staging/v1/google/pubsub/__init__.py @@ -0,0 +1,144 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from google.pubsub_v1.services.publisher.async_client import PublisherAsyncClient +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.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 +from google.pubsub_v1.types.pubsub import DeleteSnapshotRequest +from google.pubsub_v1.types.pubsub import DeleteSubscriptionRequest +from google.pubsub_v1.types.pubsub import DeleteTopicRequest +from google.pubsub_v1.types.pubsub import DetachSubscriptionRequest +from google.pubsub_v1.types.pubsub import DetachSubscriptionResponse +from google.pubsub_v1.types.pubsub import ExpirationPolicy +from google.pubsub_v1.types.pubsub import GetSnapshotRequest +from google.pubsub_v1.types.pubsub import GetSubscriptionRequest +from google.pubsub_v1.types.pubsub import GetTopicRequest +from google.pubsub_v1.types.pubsub import ListSnapshotsRequest +from google.pubsub_v1.types.pubsub import ListSnapshotsResponse +from google.pubsub_v1.types.pubsub import ListSubscriptionsRequest +from google.pubsub_v1.types.pubsub import ListSubscriptionsResponse +from google.pubsub_v1.types.pubsub import ListTopicSnapshotsRequest +from google.pubsub_v1.types.pubsub import ListTopicSnapshotsResponse +from google.pubsub_v1.types.pubsub import 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 +from google.pubsub_v1.types.pubsub import PublishRequest +from google.pubsub_v1.types.pubsub import PublishResponse +from google.pubsub_v1.types.pubsub import PubsubMessage +from google.pubsub_v1.types.pubsub import PullRequest +from google.pubsub_v1.types.pubsub import PullResponse +from google.pubsub_v1.types.pubsub import PushConfig +from google.pubsub_v1.types.pubsub import ReceivedMessage +from google.pubsub_v1.types.pubsub import RetryPolicy +from google.pubsub_v1.types.pubsub import SchemaSettings +from google.pubsub_v1.types.pubsub import SeekRequest +from google.pubsub_v1.types.pubsub import SeekResponse +from google.pubsub_v1.types.pubsub import Snapshot +from google.pubsub_v1.types.pubsub import StreamingPullRequest +from google.pubsub_v1.types.pubsub import StreamingPullResponse +from google.pubsub_v1.types.pubsub import Subscription +from google.pubsub_v1.types.pubsub import Topic +from google.pubsub_v1.types.pubsub import UpdateSnapshotRequest +from google.pubsub_v1.types.pubsub import UpdateSubscriptionRequest +from google.pubsub_v1.types.pubsub import UpdateTopicRequest +from google.pubsub_v1.types.schema import CreateSchemaRequest +from google.pubsub_v1.types.schema import DeleteSchemaRequest +from google.pubsub_v1.types.schema import 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 + +__all__ = ( + 'AcknowledgeRequest', + 'CreateSchemaRequest', + 'CreateSnapshotRequest', + 'DeadLetterPolicy', + 'DeleteSchemaRequest', + 'DeleteSnapshotRequest', + 'DeleteSubscriptionRequest', + 'DeleteTopicRequest', + 'DetachSubscriptionRequest', + 'DetachSubscriptionResponse', + 'Encoding', + 'ExpirationPolicy', + 'GetSchemaRequest', + 'GetSnapshotRequest', + 'GetSubscriptionRequest', + 'GetTopicRequest', + 'ListSchemasRequest', + 'ListSchemasResponse', + 'ListSnapshotsRequest', + 'ListSnapshotsResponse', + 'ListSubscriptionsRequest', + 'ListSubscriptionsResponse', + 'ListTopicSnapshotsRequest', + 'ListTopicSnapshotsResponse', + 'ListTopicSubscriptionsRequest', + 'ListTopicSubscriptionsResponse', + 'ListTopicsRequest', + 'ListTopicsResponse', + 'MessageStoragePolicy', + 'ModifyAckDeadlineRequest', + 'ModifyPushConfigRequest', + 'PublishRequest', + 'PublishResponse', + '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', + 'ValidateMessageRequest', + 'ValidateMessageResponse', + 'ValidateSchemaRequest', + 'ValidateSchemaResponse', +) diff --git a/owl-bot-staging/v1/google/pubsub/py.typed b/owl-bot-staging/v1/google/pubsub/py.typed new file mode 100644 index 000000000..9b0e37433 --- /dev/null +++ b/owl-bot-staging/v1/google/pubsub/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-pubsub package uses inline types. diff --git a/owl-bot-staging/v1/google/pubsub_v1/__init__.py b/owl-bot-staging/v1/google/pubsub_v1/__init__.py new file mode 100644 index 000000000..4fbae4d67 --- /dev/null +++ b/owl-bot-staging/v1/google/pubsub_v1/__init__.py @@ -0,0 +1,139 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from .services.publisher import PublisherClient +from .services.schema_service import SchemaServiceClient +from .services.subscriber import SubscriberClient +from .types.pubsub import AcknowledgeRequest +from .types.pubsub import CreateSnapshotRequest +from .types.pubsub import DeadLetterPolicy +from .types.pubsub import DeleteSnapshotRequest +from .types.pubsub import DeleteSubscriptionRequest +from .types.pubsub import DeleteTopicRequest +from .types.pubsub import DetachSubscriptionRequest +from .types.pubsub import DetachSubscriptionResponse +from .types.pubsub import ExpirationPolicy +from .types.pubsub import GetSnapshotRequest +from .types.pubsub import GetSubscriptionRequest +from .types.pubsub import GetTopicRequest +from .types.pubsub import ListSnapshotsRequest +from .types.pubsub import ListSnapshotsResponse +from .types.pubsub import ListSubscriptionsRequest +from .types.pubsub import ListSubscriptionsResponse +from .types.pubsub import ListTopicSnapshotsRequest +from .types.pubsub import ListTopicSnapshotsResponse +from .types.pubsub import 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 +from .types.pubsub import PublishRequest +from .types.pubsub import PublishResponse +from .types.pubsub import PubsubMessage +from .types.pubsub import PullRequest +from .types.pubsub import PullResponse +from .types.pubsub import PushConfig +from .types.pubsub import ReceivedMessage +from .types.pubsub import RetryPolicy +from .types.pubsub import SchemaSettings +from .types.pubsub import SeekRequest +from .types.pubsub import SeekResponse +from .types.pubsub import Snapshot +from .types.pubsub import StreamingPullRequest +from .types.pubsub import StreamingPullResponse +from .types.pubsub import Subscription +from .types.pubsub import Topic +from .types.pubsub import UpdateSnapshotRequest +from .types.pubsub import UpdateSubscriptionRequest +from .types.pubsub import UpdateTopicRequest +from .types.schema import CreateSchemaRequest +from .types.schema import DeleteSchemaRequest +from .types.schema import 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 + + +__all__ = ( + 'AcknowledgeRequest', + 'CreateSchemaRequest', + 'CreateSnapshotRequest', + 'DeadLetterPolicy', + 'DeleteSchemaRequest', + 'DeleteSnapshotRequest', + 'DeleteSubscriptionRequest', + 'DeleteTopicRequest', + 'DetachSubscriptionRequest', + 'DetachSubscriptionResponse', + 'Encoding', + 'ExpirationPolicy', + 'GetSchemaRequest', + 'GetSnapshotRequest', + 'GetSubscriptionRequest', + 'GetTopicRequest', + 'ListSchemasRequest', + 'ListSchemasResponse', + 'ListSnapshotsRequest', + 'ListSnapshotsResponse', + 'ListSubscriptionsRequest', + 'ListSubscriptionsResponse', + 'ListTopicSnapshotsRequest', + 'ListTopicSnapshotsResponse', + 'ListTopicSubscriptionsRequest', + 'ListTopicSubscriptionsResponse', + 'ListTopicsRequest', + 'ListTopicsResponse', + 'MessageStoragePolicy', + 'ModifyAckDeadlineRequest', + 'ModifyPushConfigRequest', + 'PublishRequest', + 'PublishResponse', + 'PubsubMessage', + 'PullRequest', + 'PullResponse', + 'PushConfig', + 'ReceivedMessage', + 'RetryPolicy', + 'Schema', + 'SchemaServiceClient', + 'SchemaSettings', + 'SchemaView', + 'SeekRequest', + 'SeekResponse', + 'Snapshot', + 'StreamingPullRequest', + 'StreamingPullResponse', + 'SubscriberClient', + 'Subscription', + 'Topic', + 'UpdateSnapshotRequest', + 'UpdateSubscriptionRequest', + 'UpdateTopicRequest', + 'ValidateMessageRequest', + 'ValidateMessageResponse', + 'ValidateSchemaRequest', + 'ValidateSchemaResponse', +'PublisherClient', +) diff --git a/owl-bot-staging/v1/google/pubsub_v1/py.typed b/owl-bot-staging/v1/google/pubsub_v1/py.typed new file mode 100644 index 000000000..9b0e37433 --- /dev/null +++ b/owl-bot-staging/v1/google/pubsub_v1/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-pubsub package uses inline types. diff --git a/owl-bot-staging/v1/google/pubsub_v1/services/__init__.py b/owl-bot-staging/v1/google/pubsub_v1/services/__init__.py new file mode 100644 index 000000000..42ffdf2bc --- /dev/null +++ b/owl-bot-staging/v1/google/pubsub_v1/services/__init__.py @@ -0,0 +1,16 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/owl-bot-staging/v1/google/pubsub_v1/services/publisher/__init__.py b/owl-bot-staging/v1/google/pubsub_v1/services/publisher/__init__.py new file mode 100644 index 000000000..3ef7d2838 --- /dev/null +++ b/owl-bot-staging/v1/google/pubsub_v1/services/publisher/__init__.py @@ -0,0 +1,24 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from .client import PublisherClient +from .async_client import PublisherAsyncClient + +__all__ = ( + 'PublisherClient', + 'PublisherAsyncClient', +) diff --git a/owl-bot-staging/v1/google/pubsub_v1/services/publisher/async_client.py b/owl-bot-staging/v1/google/pubsub_v1/services/publisher/async_client.py new file mode 100644 index 000000000..35087e7ef --- /dev/null +++ b/owl-bot-staging/v1/google/pubsub_v1/services/publisher/async_client.py @@ -0,0 +1,1236 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from collections import OrderedDict +import functools +import re +from typing import Dict, Sequence, Tuple, Type, Union +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 gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import 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.pubsub_v1.services.publisher import pagers +from google.pubsub_v1.types import pubsub + +from .transports.base import PublisherTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import PublisherGrpcAsyncIOTransport +from .client import PublisherClient + + +class PublisherAsyncClient: + """The service that an application uses to manipulate topics, + and to send messages to a topic. + """ + + _client: PublisherClient + + DEFAULT_ENDPOINT = PublisherClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = PublisherClient.DEFAULT_MTLS_ENDPOINT + + schema_path = staticmethod(PublisherClient.schema_path) + parse_schema_path = staticmethod(PublisherClient.parse_schema_path) + subscription_path = staticmethod(PublisherClient.subscription_path) + parse_subscription_path = staticmethod(PublisherClient.parse_subscription_path) + topic_path = staticmethod(PublisherClient.topic_path) + parse_topic_path = staticmethod(PublisherClient.parse_topic_path) + + common_billing_account_path = staticmethod(PublisherClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(PublisherClient.parse_common_billing_account_path) + + common_folder_path = staticmethod(PublisherClient.common_folder_path) + parse_common_folder_path = staticmethod(PublisherClient.parse_common_folder_path) + + common_organization_path = staticmethod(PublisherClient.common_organization_path) + parse_common_organization_path = staticmethod(PublisherClient.parse_common_organization_path) + + common_project_path = staticmethod(PublisherClient.common_project_path) + parse_common_project_path = staticmethod(PublisherClient.parse_common_project_path) + + common_location_path = staticmethod(PublisherClient.common_location_path) + parse_common_location_path = staticmethod(PublisherClient.parse_common_location_path) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + PublisherAsyncClient: The constructed client. + """ + return PublisherClient.from_service_account_info.__func__(PublisherAsyncClient, info, *args, **kwargs) # type: ignore + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + PublisherAsyncClient: The constructed client. + """ + return PublisherClient.from_service_account_file.__func__(PublisherAsyncClient, filename, *args, **kwargs) # type: ignore + + from_service_account_json = from_service_account_file + + @property + def transport(self) -> PublisherTransport: + """Return the transport used by the client instance. + + Returns: + PublisherTransport: The transport used by the client instance. + """ + return self._client.transport + + get_transport_class = functools.partial(type(PublisherClient).get_transport_class, type(PublisherClient)) + + def __init__(self, *, + credentials: credentials.Credentials = None, + transport: Union[str, PublisherTransport] = 'grpc_asyncio', + client_options: ClientOptions = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiate the publisher client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, ~.PublisherTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (ClientOptions): Custom options for the client. It + won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + """ + + self._client = PublisherClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def create_topic(self, + request: pubsub.Topic = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pubsub.Topic: + r"""Creates the given topic with the given name. See the [resource + name rules] + (https://cloud.google.com/pubsub/docs/admin#resource_names). + + Args: + request (:class:`google.pubsub_v1.types.Topic`): + The request object. A topic resource. + name (:class:`str`): + Required. The name of the topic. It must have the format + ``"projects/{project}/topics/{topic}"``. ``{topic}`` + must start with a letter, and contain only letters + (``[A-Za-z]``), numbers (``[0-9]``), dashes (``-``), + underscores (``_``), periods (``.``), tildes (``~``), + plus (``+``) or percent signs (``%``). It must be + between 3 and 255 characters in length, and it must not + start with ``"goog"``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.pubsub_v1.types.Topic: + A topic resource. + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + request = pubsub.Topic(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.create_topic, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('name', request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def update_topic(self, + request: pubsub.UpdateTopicRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pubsub.Topic: + r"""Updates an existing topic. Note that certain + properties of a topic are not modifiable. + + 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 (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.pubsub_v1.types.Topic: + A topic resource. + """ + # Create or coerce a protobuf request object. + + request = pubsub.UpdateTopicRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.update_topic, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('topic.name', request.topic.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def publish(self, + request: pubsub.PublishRequest = None, + *, + topic: str = None, + messages: Sequence[pubsub.PubsubMessage] = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pubsub.PublishResponse: + r"""Adds one or more messages to the topic. Returns ``NOT_FOUND`` if + the topic does not exist. + + Args: + request (:class:`google.pubsub_v1.types.PublishRequest`): + The request object. Request for the Publish method. + topic (:class:`str`): + Required. The messages in the request will be published + on this topic. Format is + ``projects/{project}/topics/{topic}``. + + This corresponds to the ``topic`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + messages (:class:`Sequence[google.pubsub_v1.types.PubsubMessage]`): + Required. The messages to publish. + This corresponds to the ``messages`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.pubsub_v1.types.PublishResponse: + Response for the Publish method. + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([topic, messages]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + request = pubsub.PublishRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if topic is not None: + request.topic = topic + + if messages: + request.messages.extend(messages) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.publish, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.Aborted, + exceptions.Cancelled, + exceptions.DeadlineExceeded, + exceptions.InternalServerError, + exceptions.ResourceExhausted, + exceptions.ServiceUnavailable, + exceptions.Unknown, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('topic', request.topic), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_topic(self, + request: pubsub.GetTopicRequest = None, + *, + topic: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pubsub.Topic: + r"""Gets the configuration of a topic. + + Args: + request (:class:`google.pubsub_v1.types.GetTopicRequest`): + The request object. Request for the GetTopic method. + topic (:class:`str`): + Required. The name of the topic to get. Format is + ``projects/{project}/topics/{topic}``. + + This corresponds to the ``topic`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.pubsub_v1.types.Topic: + A topic resource. + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([topic]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + request = pubsub.GetTopicRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if topic is not None: + request.topic = topic + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.get_topic, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.Aborted, + exceptions.ServiceUnavailable, + exceptions.Unknown, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('topic', request.topic), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_topics(self, + request: pubsub.ListTopicsRequest = None, + *, + project: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListTopicsAsyncPager: + r"""Lists matching topics. + + Args: + request (:class:`google.pubsub_v1.types.ListTopicsRequest`): + The request object. Request for the `ListTopics` method. + project (:class:`str`): + Required. The name of the project in which to list + topics. Format is ``projects/{project-id}``. + + This corresponds to the ``project`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.pubsub_v1.services.publisher.pagers.ListTopicsAsyncPager: + Response for the ListTopics method. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([project]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + request = pubsub.ListTopicsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if project is not None: + request.project = project + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.list_topics, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.Aborted, + exceptions.ServiceUnavailable, + exceptions.Unknown, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('project', request.project), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListTopicsAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_topic_subscriptions(self, + request: pubsub.ListTopicSubscriptionsRequest = None, + *, + topic: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListTopicSubscriptionsAsyncPager: + r"""Lists the names of the attached subscriptions on this + topic. + + Args: + request (:class:`google.pubsub_v1.types.ListTopicSubscriptionsRequest`): + The request object. Request for the + `ListTopicSubscriptions` method. + topic (:class:`str`): + Required. The name of the topic that subscriptions are + attached to. Format is + ``projects/{project}/topics/{topic}``. + + This corresponds to the ``topic`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.pubsub_v1.services.publisher.pagers.ListTopicSubscriptionsAsyncPager: + Response for the ListTopicSubscriptions method. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([topic]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + request = pubsub.ListTopicSubscriptionsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if topic is not None: + request.topic = topic + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.list_topic_subscriptions, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.Aborted, + exceptions.ServiceUnavailable, + exceptions.Unknown, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('topic', request.topic), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListTopicSubscriptionsAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_topic_snapshots(self, + request: pubsub.ListTopicSnapshotsRequest = None, + *, + topic: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListTopicSnapshotsAsyncPager: + r"""Lists the names of the snapshots on this topic. Snapshots are + used in + `Seek `__ + operations, which allow you to manage message acknowledgments in + bulk. That is, you can set the acknowledgment state of messages + in an existing subscription to the state captured by a snapshot. + + Args: + request (:class:`google.pubsub_v1.types.ListTopicSnapshotsRequest`): + The request object. Request for the `ListTopicSnapshots` + method. + topic (:class:`str`): + Required. The name of the topic that snapshots are + attached to. Format is + ``projects/{project}/topics/{topic}``. + + This corresponds to the ``topic`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.pubsub_v1.services.publisher.pagers.ListTopicSnapshotsAsyncPager: + Response for the ListTopicSnapshots method. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([topic]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + request = pubsub.ListTopicSnapshotsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if topic is not None: + request.topic = topic + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.list_topic_snapshots, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.Aborted, + exceptions.ServiceUnavailable, + exceptions.Unknown, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('topic', request.topic), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListTopicSnapshotsAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def delete_topic(self, + request: pubsub.DeleteTopicRequest = None, + *, + topic: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes the topic with the given name. Returns ``NOT_FOUND`` if + the topic does not exist. After a topic is deleted, a new topic + may be created with the same name; this is an entirely new topic + with none of the old configuration or subscriptions. Existing + subscriptions to this topic are not deleted, but their ``topic`` + field is set to ``_deleted-topic_``. + + Args: + request (:class:`google.pubsub_v1.types.DeleteTopicRequest`): + The request object. Request for the `DeleteTopic` + method. + topic (:class:`str`): + Required. Name of the topic to delete. Format is + ``projects/{project}/topics/{topic}``. + + This corresponds to the ``topic`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([topic]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + request = pubsub.DeleteTopicRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if topic is not None: + request.topic = topic + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.delete_topic, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('topic', request.topic), + )), + ) + + # Send the request. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def detach_subscription(self, + request: pubsub.DetachSubscriptionRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pubsub.DetachSubscriptionResponse: + r"""Detaches a subscription from this topic. All messages retained + in the subscription are dropped. Subsequent ``Pull`` and + ``StreamingPull`` requests will return FAILED_PRECONDITION. If + the subscription is a push subscription, pushes to the endpoint + will stop. + + Args: + 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 (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.pubsub_v1.types.DetachSubscriptionResponse: + Response for the DetachSubscription + method. Reserved for future use. + + """ + # Create or coerce a protobuf request object. + + request = pubsub.DetachSubscriptionRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.detach_subscription, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('subscription', request.subscription), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def set_iam_policy( + self, + request: iam_policy.SetIamPolicyRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> policy.Policy: + r"""Sets the IAM access control policy on the specified + function. Replaces any existing policy. + Args: + request (:class:`~.iam_policy.SetIamPolicyRequest`): + The request object. Request message for `SetIamPolicy` + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.policy.Policy: + Defines an Identity and Access Management (IAM) policy. + It is used to specify access control policies for Cloud + Platform resources. + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members`` to a single + ``role``. Members can be user accounts, service + accounts, Google groups, and domains (such as G Suite). + A ``role`` is a named list of permissions (defined by + IAM or configured by users). A ``binding`` can + optionally specify a ``condition``, which is a logic + expression that further constrains the role binding + based on attributes about the request and/or target + resource. + **JSON Example** + :: + { + "bindings": [ + { + "role": "roles/resourcemanager.organizationAdmin", + "members": [ + "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + }, + { + "role": "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { + "title": "expirable access", + "description": "Does not grant access after Sep 2020", + "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", + } + } + ] + } + **YAML Example** + :: + bindings: + - members: + - user:mike@example.com + - group:admins@example.com + - domain:google.com + - serviceAccount:my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin + - members: + - user:eve@example.com + role: roles/resourcemanager.organizationViewer + condition: + title: expirable access + description: Does not grant access after Sep 2020 + expression: request.time < timestamp('2020-10-01T00:00:00.000Z') + For a description of IAM and its features, see the `IAM + developer's + guide `__. + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = iam_policy.SetIamPolicyRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.set_iam_policy, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("resource", request.resource),)), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def get_iam_policy( + self, + request: iam_policy.GetIamPolicyRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> policy.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`): + The request object. Request message for `GetIamPolicy` + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.policy.Policy: + Defines an Identity and Access Management (IAM) policy. + It is used to specify access control policies for Cloud + Platform resources. + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members`` to a single + ``role``. Members can be user accounts, service + accounts, Google groups, and domains (such as G Suite). + A ``role`` is a named list of permissions (defined by + IAM or configured by users). A ``binding`` can + optionally specify a ``condition``, which is a logic + expression that further constrains the role binding + based on attributes about the request and/or target + resource. + **JSON Example** + :: + { + "bindings": [ + { + "role": "roles/resourcemanager.organizationAdmin", + "members": [ + "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + }, + { + "role": "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { + "title": "expirable access", + "description": "Does not grant access after Sep 2020", + "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", + } + } + ] + } + **YAML Example** + :: + bindings: + - members: + - user:mike@example.com + - group:admins@example.com + - domain:google.com + - serviceAccount:my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin + - members: + - user:eve@example.com + role: roles/resourcemanager.organizationViewer + condition: + title: expirable access + description: Does not grant access after Sep 2020 + expression: request.time < timestamp('2020-10-01T00:00:00.000Z') + For a description of IAM and its features, see the `IAM + developer's + guide `__. + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = iam_policy.GetIamPolicyRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.get_iam_policy, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("resource", request.resource),)), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def test_iam_permissions( + self, + request: iam_policy.TestIamPermissionsRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> iam_policy.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`): + The request object. Request message for + `TestIamPermissions` method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.iam_policy.TestIamPermissionsResponse: + Response message for ``TestIamPermissions`` method. + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = iam_policy.TestIamPermissionsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.test_iam_permissions, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("resource", request.resource),)), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + 'google-pubsub', + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + 'PublisherAsyncClient', +) diff --git a/owl-bot-staging/v1/google/pubsub_v1/services/publisher/client.py b/owl-bot-staging/v1/google/pubsub_v1/services/publisher/client.py new file mode 100644 index 000000000..d37e13661 --- /dev/null +++ b/owl-bot-staging/v1/google/pubsub_v1/services/publisher/client.py @@ -0,0 +1,1340 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from collections import OrderedDict +from distutils import util +import os +import re +from typing import Callable, Dict, Optional, Sequence, Tuple, Type, Union +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 gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import 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.pubsub_v1.services.publisher import pagers +from google.pubsub_v1.types import pubsub + +from .transports.base import PublisherTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import PublisherGrpcTransport +from .transports.grpc_asyncio import PublisherGrpcAsyncIOTransport + + +class PublisherClientMeta(type): + """Metaclass for the Publisher client. + + This provides class-level methods for building and retrieving + support objects (e.g. transport) without polluting the client instance + objects. + """ + _transport_registry = OrderedDict() # type: Dict[str, Type[PublisherTransport]] + _transport_registry['grpc'] = PublisherGrpcTransport + _transport_registry['grpc_asyncio'] = PublisherGrpcAsyncIOTransport + + def get_transport_class(cls, + label: str = None, + ) -> Type[PublisherTransport]: + """Return an appropriate transport class. + + Args: + label: The name of the desired transport. If none is + provided, then the first transport in the registry is used. + + Returns: + The transport class to use. + """ + # If a specific transport is requested, return that one. + if label: + return cls._transport_registry[label] + + # No transport is requested; return the default (that is, the first one + # in the dictionary). + return next(iter(cls._transport_registry.values())) + + +class PublisherClient(metaclass=PublisherClientMeta): + """The service that an application uses to manipulate topics, + and to send messages to a topic. + """ + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint): + """Convert api endpoint to mTLS endpoint. + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to + "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + Args: + api_endpoint (Optional[str]): the api endpoint to convert. + Returns: + str: converted mTLS api endpoint. + """ + if not api_endpoint: + return api_endpoint + + mtls_endpoint_re = re.compile( + r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" + ) + + m = mtls_endpoint_re.match(api_endpoint) + name, mtls, sandbox, googledomain = m.groups() + if mtls or not googledomain: + return api_endpoint + + if sandbox: + return api_endpoint.replace( + "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" + ) + + return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + + DEFAULT_ENDPOINT = 'pubsub.googleapis.com' + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + PublisherClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_info(info) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + PublisherClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_file( + filename) + kwargs['credentials'] = credentials + return cls(*args, **kwargs) + + from_service_account_json = from_service_account_file + + @property + def transport(self) -> PublisherTransport: + """Return the transport used by the client instance. + + Returns: + PublisherTransport: The transport used by the client instance. + """ + return self._transport + + @staticmethod + def schema_path(project: str,schema: str,) -> str: + """Return 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.""" + 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.""" + 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.""" + m = re.match(r"^projects/(?P.+?)/subscriptions/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def topic_path(project: str,topic: str,) -> str: + """Return 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.""" + 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.""" + return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str,str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path(folder: str, ) -> str: + """Return a fully-qualified folder string.""" + return "folders/{folder}".format(folder=folder, ) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str,str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path(organization: str, ) -> str: + """Return a fully-qualified organization string.""" + return "organizations/{organization}".format(organization=organization, ) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str,str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path(project: str, ) -> str: + """Return a fully-qualified project string.""" + return "projects/{project}".format(project=project, ) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str,str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path(project: str, location: str, ) -> str: + """Return a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format(project=project, location=location, ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str,str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + + def __init__(self, *, + credentials: Optional[credentials.Credentials] = None, + transport: Union[str, PublisherTransport, None] = None, + client_options: Optional[client_options_lib.ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiate the publisher client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, PublisherTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. It won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + if isinstance(client_options, dict): + client_options = client_options_lib.from_dict(client_options) + if client_options is None: + client_options = client_options_lib.ClientOptions() + + # Create SSL credentials for mutual TLS if needed. + use_client_cert = bool(util.strtobool(os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false"))) + + client_cert_source_func = None + is_mtls = False + if use_client_cert: + if client_options.client_cert_source: + is_mtls = True + 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 + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + else: + use_mtls_env = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_mtls_env == "never": + api_endpoint = self.DEFAULT_ENDPOINT + 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 + else: + raise MutualTLSChannelError( + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted values: never, auto, always" + ) + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + if isinstance(transport, PublisherTransport): + # transport is a PublisherTransport instance. + if credentials or client_options.credentials_file: + raise ValueError('When providing a transport instance, ' + 'provide its credentials directly.') + if client_options.scopes: + raise ValueError( + "When providing a transport instance, " + "provide its scopes directly." + ) + self._transport = transport + else: + Transport = type(self).get_transport_class(transport) + self._transport = Transport( + credentials=credentials, + credentials_file=client_options.credentials_file, + host=api_endpoint, + scopes=client_options.scopes, + client_cert_source_for_mtls=client_cert_source_func, + quota_project_id=client_options.quota_project_id, + client_info=client_info, + ) + + def create_topic(self, + request: pubsub.Topic = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pubsub.Topic: + r"""Creates the given topic with the given name. See the [resource + name rules] + (https://cloud.google.com/pubsub/docs/admin#resource_names). + + Args: + request (google.pubsub_v1.types.Topic): + The request object. A topic resource. + name (str): + Required. The name of the topic. It must have the format + ``"projects/{project}/topics/{topic}"``. ``{topic}`` + must start with a letter, and contain only letters + (``[A-Za-z]``), numbers (``[0-9]``), dashes (``-``), + underscores (``_``), periods (``.``), tildes (``~``), + plus (``+``) or percent signs (``%``). It must be + between 3 and 255 characters in length, and it must not + start with ``"goog"``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.pubsub_v1.types.Topic: + A topic resource. + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a pubsub.Topic. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, pubsub.Topic): + request = pubsub.Topic(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_topic] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('name', request.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def update_topic(self, + request: pubsub.UpdateTopicRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pubsub.Topic: + r"""Updates an existing topic. Note that certain + properties of a topic are not modifiable. + + 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 (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.pubsub_v1.types.Topic: + A topic resource. + """ + # Create or coerce a protobuf request object. + + # Minor optimization to avoid making a copy if the user passes + # in a pubsub.UpdateTopicRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, pubsub.UpdateTopicRequest): + request = pubsub.UpdateTopicRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update_topic] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('topic.name', request.topic.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def publish(self, + request: pubsub.PublishRequest = None, + *, + topic: str = None, + messages: Sequence[pubsub.PubsubMessage] = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pubsub.PublishResponse: + r"""Adds one or more messages to the topic. Returns ``NOT_FOUND`` if + the topic does not exist. + + Args: + request (google.pubsub_v1.types.PublishRequest): + The request object. Request for the Publish method. + topic (str): + Required. The messages in the request will be published + on this topic. Format is + ``projects/{project}/topics/{topic}``. + + This corresponds to the ``topic`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + messages (Sequence[google.pubsub_v1.types.PubsubMessage]): + Required. The messages to publish. + This corresponds to the ``messages`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.pubsub_v1.types.PublishResponse: + Response for the Publish method. + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([topic, messages]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a pubsub.PublishRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, pubsub.PublishRequest): + request = pubsub.PublishRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if topic is not None: + request.topic = topic + if messages is not None: + request.messages = messages + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.publish] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('topic', request.topic), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_topic(self, + request: pubsub.GetTopicRequest = None, + *, + topic: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pubsub.Topic: + r"""Gets the configuration of a topic. + + Args: + request (google.pubsub_v1.types.GetTopicRequest): + The request object. Request for the GetTopic method. + topic (str): + Required. The name of the topic to get. Format is + ``projects/{project}/topics/{topic}``. + + This corresponds to the ``topic`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.pubsub_v1.types.Topic: + A topic resource. + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([topic]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a pubsub.GetTopicRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, pubsub.GetTopicRequest): + request = pubsub.GetTopicRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if topic is not None: + request.topic = topic + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_topic] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('topic', request.topic), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_topics(self, + request: pubsub.ListTopicsRequest = None, + *, + project: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListTopicsPager: + r"""Lists matching topics. + + Args: + request (google.pubsub_v1.types.ListTopicsRequest): + The request object. Request for the `ListTopics` method. + project (str): + Required. The name of the project in which to list + topics. Format is ``projects/{project-id}``. + + This corresponds to the ``project`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.pubsub_v1.services.publisher.pagers.ListTopicsPager: + Response for the ListTopics method. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([project]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a pubsub.ListTopicsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, pubsub.ListTopicsRequest): + request = pubsub.ListTopicsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if project is not None: + request.project = project + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_topics] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('project', request.project), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListTopicsPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_topic_subscriptions(self, + request: pubsub.ListTopicSubscriptionsRequest = None, + *, + topic: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListTopicSubscriptionsPager: + r"""Lists the names of the attached subscriptions on this + topic. + + Args: + request (google.pubsub_v1.types.ListTopicSubscriptionsRequest): + The request object. Request for the + `ListTopicSubscriptions` method. + topic (str): + Required. The name of the topic that subscriptions are + attached to. Format is + ``projects/{project}/topics/{topic}``. + + This corresponds to the ``topic`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.pubsub_v1.services.publisher.pagers.ListTopicSubscriptionsPager: + Response for the ListTopicSubscriptions method. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([topic]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a pubsub.ListTopicSubscriptionsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, pubsub.ListTopicSubscriptionsRequest): + request = pubsub.ListTopicSubscriptionsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if topic is not None: + request.topic = topic + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_topic_subscriptions] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('topic', request.topic), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListTopicSubscriptionsPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_topic_snapshots(self, + request: pubsub.ListTopicSnapshotsRequest = None, + *, + topic: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListTopicSnapshotsPager: + r"""Lists the names of the snapshots on this topic. Snapshots are + used in + `Seek `__ + operations, which allow you to manage message acknowledgments in + bulk. That is, you can set the acknowledgment state of messages + in an existing subscription to the state captured by a snapshot. + + Args: + request (google.pubsub_v1.types.ListTopicSnapshotsRequest): + The request object. Request for the `ListTopicSnapshots` + method. + topic (str): + Required. The name of the topic that snapshots are + attached to. Format is + ``projects/{project}/topics/{topic}``. + + This corresponds to the ``topic`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.pubsub_v1.services.publisher.pagers.ListTopicSnapshotsPager: + Response for the ListTopicSnapshots method. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([topic]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a pubsub.ListTopicSnapshotsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, pubsub.ListTopicSnapshotsRequest): + request = pubsub.ListTopicSnapshotsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if topic is not None: + request.topic = topic + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_topic_snapshots] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('topic', request.topic), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListTopicSnapshotsPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def delete_topic(self, + request: pubsub.DeleteTopicRequest = None, + *, + topic: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes the topic with the given name. Returns ``NOT_FOUND`` if + the topic does not exist. After a topic is deleted, a new topic + may be created with the same name; this is an entirely new topic + with none of the old configuration or subscriptions. Existing + subscriptions to this topic are not deleted, but their ``topic`` + field is set to ``_deleted-topic_``. + + Args: + request (google.pubsub_v1.types.DeleteTopicRequest): + The request object. Request for the `DeleteTopic` + method. + topic (str): + Required. Name of the topic to delete. Format is + ``projects/{project}/topics/{topic}``. + + This corresponds to the ``topic`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([topic]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a pubsub.DeleteTopicRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, pubsub.DeleteTopicRequest): + request = pubsub.DeleteTopicRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if topic is not None: + request.topic = topic + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.delete_topic] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('topic', request.topic), + )), + ) + + # Send the request. + rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + def detach_subscription(self, + request: pubsub.DetachSubscriptionRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pubsub.DetachSubscriptionResponse: + r"""Detaches a subscription from this topic. All messages retained + in the subscription are dropped. Subsequent ``Pull`` and + ``StreamingPull`` requests will return FAILED_PRECONDITION. If + the subscription is a push subscription, pushes to the endpoint + will stop. + + Args: + 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 (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.pubsub_v1.types.DetachSubscriptionResponse: + Response for the DetachSubscription + method. Reserved for future use. + + """ + # Create or coerce a protobuf request object. + + # Minor optimization to avoid making a copy if the user passes + # in a pubsub.DetachSubscriptionRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, pubsub.DetachSubscriptionRequest): + request = pubsub.DetachSubscriptionRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.detach_subscription] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('subscription', request.subscription), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def set_iam_policy( + self, + request: iam_policy.SetIamPolicyRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> policy.Policy: + r"""Sets the IAM access control policy on the specified + function. Replaces any existing policy. + Args: + request (:class:`~.iam_policy.SetIamPolicyRequest`): + The request object. Request message for `SetIamPolicy` + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.policy.Policy: + Defines an Identity and Access Management (IAM) policy. + It is used to specify access control policies for Cloud + Platform resources. + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members`` to a single + ``role``. Members can be user accounts, service + accounts, Google groups, and domains (such as G Suite). + A ``role`` is a named list of permissions (defined by + IAM or configured by users). A ``binding`` can + optionally specify a ``condition``, which is a logic + expression that further constrains the role binding + based on attributes about the request and/or target + resource. + **JSON Example** + :: + { + "bindings": [ + { + "role": "roles/resourcemanager.organizationAdmin", + "members": [ + "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + }, + { + "role": "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { + "title": "expirable access", + "description": "Does not grant access after Sep 2020", + "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", + } + } + ] + } + **YAML Example** + :: + bindings: + - members: + - user:mike@example.com + - group:admins@example.com + - domain:google.com + - serviceAccount:my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin + - members: + - user:eve@example.com + role: roles/resourcemanager.organizationViewer + condition: + title: expirable access + description: Does not grant access after Sep 2020 + expression: request.time < timestamp('2020-10-01T00:00:00.000Z') + For a description of IAM and its features, see the `IAM + developer's + guide `__. + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = iam_policy.SetIamPolicyRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.set_iam_policy, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("resource", request.resource),)), + ) + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def get_iam_policy( + self, + request: iam_policy.GetIamPolicyRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> policy.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`): + The request object. Request message for `GetIamPolicy` + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.policy.Policy: + Defines an Identity and Access Management (IAM) policy. + It is used to specify access control policies for Cloud + Platform resources. + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members`` to a single + ``role``. Members can be user accounts, service + accounts, Google groups, and domains (such as G Suite). + A ``role`` is a named list of permissions (defined by + IAM or configured by users). A ``binding`` can + optionally specify a ``condition``, which is a logic + expression that further constrains the role binding + based on attributes about the request and/or target + resource. + **JSON Example** + :: + { + "bindings": [ + { + "role": "roles/resourcemanager.organizationAdmin", + "members": [ + "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + }, + { + "role": "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { + "title": "expirable access", + "description": "Does not grant access after Sep 2020", + "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", + } + } + ] + } + **YAML Example** + :: + bindings: + - members: + - user:mike@example.com + - group:admins@example.com + - domain:google.com + - serviceAccount:my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin + - members: + - user:eve@example.com + role: roles/resourcemanager.organizationViewer + condition: + title: expirable access + description: Does not grant access after Sep 2020 + expression: request.time < timestamp('2020-10-01T00:00:00.000Z') + For a description of IAM and its features, see the `IAM + developer's + guide `__. + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = iam_policy.GetIamPolicyRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.get_iam_policy, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("resource", request.resource),)), + ) + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def test_iam_permissions( + self, + request: iam_policy.TestIamPermissionsRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> iam_policy.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`): + The request object. Request message for + `TestIamPermissions` method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.iam_policy.TestIamPermissionsResponse: + Response message for ``TestIamPermissions`` method. + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = iam_policy.TestIamPermissionsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.test_iam_permissions, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("resource", request.resource),)), + ) + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + 'google-pubsub', + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + 'PublisherClient', +) diff --git a/owl-bot-staging/v1/google/pubsub_v1/services/publisher/pagers.py b/owl-bot-staging/v1/google/pubsub_v1/services/publisher/pagers.py new file mode 100644 index 000000000..1b237533a --- /dev/null +++ b/owl-bot-staging/v1/google/pubsub_v1/services/publisher/pagers.py @@ -0,0 +1,386 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from typing import Any, AsyncIterable, Awaitable, Callable, Iterable, Sequence, Tuple, Optional + +from google.pubsub_v1.types import pubsub + + +class ListTopicsPager: + """A pager for iterating through ``list_topics`` requests. + + This class thinly wraps an initial + :class:`google.pubsub_v1.types.ListTopicsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``topics`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListTopics`` requests and continue to iterate + through the ``topics`` field on the + corresponding responses. + + All the usual :class:`google.pubsub_v1.types.ListTopicsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + def __init__(self, + method: Callable[..., pubsub.ListTopicsResponse], + request: pubsub.ListTopicsRequest, + response: pubsub.ListTopicsResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.pubsub_v1.types.ListTopicsRequest): + The initial request object. + response (google.pubsub_v1.types.ListTopicsResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = pubsub.ListTopicsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterable[pubsub.ListTopicsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterable[pubsub.Topic]: + for page in self.pages: + yield from page.topics + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListTopicsAsyncPager: + """A pager for iterating through ``list_topics`` requests. + + This class thinly wraps an initial + :class:`google.pubsub_v1.types.ListTopicsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``topics`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListTopics`` requests and continue to iterate + through the ``topics`` field on the + corresponding responses. + + All the usual :class:`google.pubsub_v1.types.ListTopicsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + def __init__(self, + method: Callable[..., Awaitable[pubsub.ListTopicsResponse]], + request: pubsub.ListTopicsRequest, + response: pubsub.ListTopicsResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.pubsub_v1.types.ListTopicsRequest): + The initial request object. + response (google.pubsub_v1.types.ListTopicsResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = pubsub.ListTopicsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterable[pubsub.ListTopicsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method(self._request, metadata=self._metadata) + yield self._response + + def __aiter__(self) -> AsyncIterable[pubsub.Topic]: + async def async_generator(): + async for page in self.pages: + for response in page.topics: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListTopicSubscriptionsPager: + """A pager for iterating through ``list_topic_subscriptions`` requests. + + This class thinly wraps an initial + :class:`google.pubsub_v1.types.ListTopicSubscriptionsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``subscriptions`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListTopicSubscriptions`` requests and continue to iterate + through the ``subscriptions`` field on the + corresponding responses. + + All the usual :class:`google.pubsub_v1.types.ListTopicSubscriptionsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + def __init__(self, + method: Callable[..., pubsub.ListTopicSubscriptionsResponse], + request: pubsub.ListTopicSubscriptionsRequest, + response: pubsub.ListTopicSubscriptionsResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.pubsub_v1.types.ListTopicSubscriptionsRequest): + The initial request object. + response (google.pubsub_v1.types.ListTopicSubscriptionsResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = pubsub.ListTopicSubscriptionsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterable[pubsub.ListTopicSubscriptionsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterable[str]: + for page in self.pages: + yield from page.subscriptions + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListTopicSubscriptionsAsyncPager: + """A pager for iterating through ``list_topic_subscriptions`` requests. + + This class thinly wraps an initial + :class:`google.pubsub_v1.types.ListTopicSubscriptionsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``subscriptions`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListTopicSubscriptions`` requests and continue to iterate + through the ``subscriptions`` field on the + corresponding responses. + + All the usual :class:`google.pubsub_v1.types.ListTopicSubscriptionsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + def __init__(self, + method: Callable[..., Awaitable[pubsub.ListTopicSubscriptionsResponse]], + request: pubsub.ListTopicSubscriptionsRequest, + response: pubsub.ListTopicSubscriptionsResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.pubsub_v1.types.ListTopicSubscriptionsRequest): + The initial request object. + response (google.pubsub_v1.types.ListTopicSubscriptionsResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = pubsub.ListTopicSubscriptionsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterable[pubsub.ListTopicSubscriptionsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method(self._request, metadata=self._metadata) + yield self._response + + def __aiter__(self) -> AsyncIterable[str]: + async def async_generator(): + async for page in self.pages: + for response in page.subscriptions: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListTopicSnapshotsPager: + """A pager for iterating through ``list_topic_snapshots`` requests. + + This class thinly wraps an initial + :class:`google.pubsub_v1.types.ListTopicSnapshotsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``snapshots`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListTopicSnapshots`` requests and continue to iterate + through the ``snapshots`` field on the + corresponding responses. + + All the usual :class:`google.pubsub_v1.types.ListTopicSnapshotsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + def __init__(self, + method: Callable[..., pubsub.ListTopicSnapshotsResponse], + request: pubsub.ListTopicSnapshotsRequest, + response: pubsub.ListTopicSnapshotsResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.pubsub_v1.types.ListTopicSnapshotsRequest): + The initial request object. + response (google.pubsub_v1.types.ListTopicSnapshotsResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = pubsub.ListTopicSnapshotsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterable[pubsub.ListTopicSnapshotsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterable[str]: + for page in self.pages: + yield from page.snapshots + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListTopicSnapshotsAsyncPager: + """A pager for iterating through ``list_topic_snapshots`` requests. + + This class thinly wraps an initial + :class:`google.pubsub_v1.types.ListTopicSnapshotsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``snapshots`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListTopicSnapshots`` requests and continue to iterate + through the ``snapshots`` field on the + corresponding responses. + + All the usual :class:`google.pubsub_v1.types.ListTopicSnapshotsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + def __init__(self, + method: Callable[..., Awaitable[pubsub.ListTopicSnapshotsResponse]], + request: pubsub.ListTopicSnapshotsRequest, + response: pubsub.ListTopicSnapshotsResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.pubsub_v1.types.ListTopicSnapshotsRequest): + The initial request object. + response (google.pubsub_v1.types.ListTopicSnapshotsResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = pubsub.ListTopicSnapshotsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterable[pubsub.ListTopicSnapshotsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method(self._request, metadata=self._metadata) + yield self._response + + def __aiter__(self) -> AsyncIterable[str]: + async def async_generator(): + async for page in self.pages: + for response in page.snapshots: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) diff --git a/owl-bot-staging/v1/google/pubsub_v1/services/publisher/transports/__init__.py b/owl-bot-staging/v1/google/pubsub_v1/services/publisher/transports/__init__.py new file mode 100644 index 000000000..0d8e158e6 --- /dev/null +++ b/owl-bot-staging/v1/google/pubsub_v1/services/publisher/transports/__init__.py @@ -0,0 +1,35 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from collections import OrderedDict +from typing import Dict, Type + +from .base import PublisherTransport +from .grpc import PublisherGrpcTransport +from .grpc_asyncio import PublisherGrpcAsyncIOTransport + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[PublisherTransport]] +_transport_registry['grpc'] = PublisherGrpcTransport +_transport_registry['grpc_asyncio'] = PublisherGrpcAsyncIOTransport + +__all__ = ( + 'PublisherTransport', + 'PublisherGrpcTransport', + 'PublisherGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v1/google/pubsub_v1/services/publisher/transports/base.py b/owl-bot-staging/v1/google/pubsub_v1/services/publisher/transports/base.py new file mode 100644 index 000000000..9f17d8e2e --- /dev/null +++ b/owl-bot-staging/v1/google/pubsub_v1/services/publisher/transports/base.py @@ -0,0 +1,368 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +import abc +import typing +import pkg_resources + +from google import auth # 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 +from google.auth import 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.pubsub_v1.types import pubsub + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + 'google-pubsub', + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + +class PublisherTransport(abc.ABC): + """Abstract transport class for Publisher.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/pubsub', + ) + + 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, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + 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): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + """ + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ':' not in host: + host += ':443' + self._host = host + + # 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("'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 + ) + + elif credentials is None: + credentials, _ = auth.default(scopes=self._scopes, quota_project_id=quota_project_id) + + # Save the credentials. + self._credentials = credentials + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.create_topic: gapic_v1.method.wrap_method( + self.create_topic, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.update_topic: gapic_v1.method.wrap_method( + self.update_topic, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.publish: gapic_v1.method.wrap_method( + self.publish, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.Aborted, + exceptions.Cancelled, + exceptions.DeadlineExceeded, + exceptions.InternalServerError, + exceptions.ResourceExhausted, + exceptions.ServiceUnavailable, + exceptions.Unknown, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.get_topic: gapic_v1.method.wrap_method( + self.get_topic, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.Aborted, + exceptions.ServiceUnavailable, + exceptions.Unknown, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.list_topics: gapic_v1.method.wrap_method( + self.list_topics, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.Aborted, + exceptions.ServiceUnavailable, + exceptions.Unknown, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.list_topic_subscriptions: gapic_v1.method.wrap_method( + self.list_topic_subscriptions, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.Aborted, + exceptions.ServiceUnavailable, + exceptions.Unknown, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.list_topic_snapshots: gapic_v1.method.wrap_method( + self.list_topic_snapshots, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.Aborted, + exceptions.ServiceUnavailable, + exceptions.Unknown, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.delete_topic: gapic_v1.method.wrap_method( + self.delete_topic, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.detach_subscription: gapic_v1.method.wrap_method( + self.detach_subscription, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + + } + + @property + def create_topic(self) -> typing.Callable[ + [pubsub.Topic], + typing.Union[ + pubsub.Topic, + typing.Awaitable[pubsub.Topic] + ]]: + raise NotImplementedError() + + @property + def update_topic(self) -> typing.Callable[ + [pubsub.UpdateTopicRequest], + typing.Union[ + pubsub.Topic, + typing.Awaitable[pubsub.Topic] + ]]: + raise NotImplementedError() + + @property + def publish(self) -> typing.Callable[ + [pubsub.PublishRequest], + typing.Union[ + pubsub.PublishResponse, + typing.Awaitable[pubsub.PublishResponse] + ]]: + raise NotImplementedError() + + @property + def get_topic(self) -> typing.Callable[ + [pubsub.GetTopicRequest], + typing.Union[ + pubsub.Topic, + typing.Awaitable[pubsub.Topic] + ]]: + raise NotImplementedError() + + @property + def list_topics(self) -> typing.Callable[ + [pubsub.ListTopicsRequest], + typing.Union[ + pubsub.ListTopicsResponse, + typing.Awaitable[pubsub.ListTopicsResponse] + ]]: + raise NotImplementedError() + + @property + def list_topic_subscriptions(self) -> typing.Callable[ + [pubsub.ListTopicSubscriptionsRequest], + typing.Union[ + pubsub.ListTopicSubscriptionsResponse, + typing.Awaitable[pubsub.ListTopicSubscriptionsResponse] + ]]: + raise NotImplementedError() + + @property + def list_topic_snapshots(self) -> typing.Callable[ + [pubsub.ListTopicSnapshotsRequest], + typing.Union[ + pubsub.ListTopicSnapshotsResponse, + typing.Awaitable[pubsub.ListTopicSnapshotsResponse] + ]]: + raise NotImplementedError() + + @property + def delete_topic(self) -> typing.Callable[ + [pubsub.DeleteTopicRequest], + typing.Union[ + empty.Empty, + typing.Awaitable[empty.Empty] + ]]: + raise NotImplementedError() + + @property + def detach_subscription(self) -> typing.Callable[ + [pubsub.DetachSubscriptionRequest], + typing.Union[ + pubsub.DetachSubscriptionResponse, + typing.Awaitable[pubsub.DetachSubscriptionResponse] + ]]: + raise NotImplementedError() + + @property + def set_iam_policy( + self, + ) -> typing.Callable[ + [iam_policy.SetIamPolicyRequest], + typing.Union[policy.Policy, typing.Awaitable[policy.Policy]], + ]: + raise NotImplementedError() + + @property + def get_iam_policy( + self, + ) -> typing.Callable[ + [iam_policy.GetIamPolicyRequest], + typing.Union[policy.Policy, typing.Awaitable[policy.Policy]], + ]: + raise NotImplementedError() + + @property + def test_iam_permissions( + self, + ) -> typing.Callable[ + [iam_policy.TestIamPermissionsRequest], + typing.Union[ + iam_policy.TestIamPermissionsResponse, + typing.Awaitable[iam_policy.TestIamPermissionsResponse], + ], + ]: + raise NotImplementedError() + + +__all__ = ( + 'PublisherTransport', +) diff --git a/owl-bot-staging/v1/google/pubsub_v1/services/publisher/transports/grpc.py b/owl-bot-staging/v1/google/pubsub_v1/services/publisher/transports/grpc.py new file mode 100644 index 000000000..699339228 --- /dev/null +++ b/owl-bot-staging/v1/google/pubsub_v1/services/publisher/transports/grpc.py @@ -0,0 +1,558 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple + +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 +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.pubsub_v1.types import pubsub + +from .base import PublisherTransport, DEFAULT_CLIENT_INFO + + +class PublisherGrpcTransport(PublisherTransport): + """gRPC backend transport for Publisher. + + The service that an application uses to manipulate topics, + and to send messages to a topic. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + _stubs: Dict[str, Callable] + + def __init__(self, *, + host: str = 'pubsub.googleapis.com', + credentials: credentials.Credentials = None, + credentials_file: str = None, + scopes: Sequence[str] = None, + channel: grpc.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + channel (Optional[grpc.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or applicatin default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + credentials=self._credentials, + credentials_file=credentials_file, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel(cls, + host: str = 'pubsub.googleapis.com', + credentials: credentials.Credentials = None, + credentials_file: str = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> grpc.Channel: + """Create and return a gRPC channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + grpc.Channel: A gRPC channel object. + + Raises: + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + 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, + **kwargs + ) + + @property + def grpc_channel(self) -> grpc.Channel: + """Return the channel designed to connect to this service. + """ + return self._grpc_channel + + @property + def create_topic(self) -> Callable[ + [pubsub.Topic], + pubsub.Topic]: + r"""Return a callable for the create topic method over gRPC. + + Creates the given topic with the given name. See the [resource + name rules] + (https://cloud.google.com/pubsub/docs/admin#resource_names). + + Returns: + Callable[[~.Topic], + ~.Topic]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'create_topic' not in self._stubs: + self._stubs['create_topic'] = self.grpc_channel.unary_unary( + '/google.pubsub.v1.Publisher/CreateTopic', + request_serializer=pubsub.Topic.serialize, + response_deserializer=pubsub.Topic.deserialize, + ) + return self._stubs['create_topic'] + + @property + def update_topic(self) -> Callable[ + [pubsub.UpdateTopicRequest], + pubsub.Topic]: + r"""Return a callable for the update topic method over gRPC. + + Updates an existing topic. Note that certain + properties of a topic are not modifiable. + + Returns: + Callable[[~.UpdateTopicRequest], + ~.Topic]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'update_topic' not in self._stubs: + self._stubs['update_topic'] = self.grpc_channel.unary_unary( + '/google.pubsub.v1.Publisher/UpdateTopic', + request_serializer=pubsub.UpdateTopicRequest.serialize, + response_deserializer=pubsub.Topic.deserialize, + ) + return self._stubs['update_topic'] + + @property + def publish(self) -> Callable[ + [pubsub.PublishRequest], + pubsub.PublishResponse]: + r"""Return a callable for the publish method over gRPC. + + Adds one or more messages to the topic. Returns ``NOT_FOUND`` if + the topic does not exist. + + Returns: + Callable[[~.PublishRequest], + ~.PublishResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'publish' not in self._stubs: + self._stubs['publish'] = self.grpc_channel.unary_unary( + '/google.pubsub.v1.Publisher/Publish', + request_serializer=pubsub.PublishRequest.serialize, + response_deserializer=pubsub.PublishResponse.deserialize, + ) + return self._stubs['publish'] + + @property + def get_topic(self) -> Callable[ + [pubsub.GetTopicRequest], + pubsub.Topic]: + r"""Return a callable for the get topic method over gRPC. + + Gets the configuration of a topic. + + Returns: + Callable[[~.GetTopicRequest], + ~.Topic]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_topic' not in self._stubs: + self._stubs['get_topic'] = self.grpc_channel.unary_unary( + '/google.pubsub.v1.Publisher/GetTopic', + request_serializer=pubsub.GetTopicRequest.serialize, + response_deserializer=pubsub.Topic.deserialize, + ) + return self._stubs['get_topic'] + + @property + def list_topics(self) -> Callable[ + [pubsub.ListTopicsRequest], + pubsub.ListTopicsResponse]: + r"""Return a callable for the list topics method over gRPC. + + Lists matching topics. + + Returns: + Callable[[~.ListTopicsRequest], + ~.ListTopicsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'list_topics' not in self._stubs: + self._stubs['list_topics'] = self.grpc_channel.unary_unary( + '/google.pubsub.v1.Publisher/ListTopics', + request_serializer=pubsub.ListTopicsRequest.serialize, + response_deserializer=pubsub.ListTopicsResponse.deserialize, + ) + return self._stubs['list_topics'] + + @property + def list_topic_subscriptions(self) -> Callable[ + [pubsub.ListTopicSubscriptionsRequest], + pubsub.ListTopicSubscriptionsResponse]: + r"""Return a callable for the list topic subscriptions method over gRPC. + + Lists the names of the attached subscriptions on this + topic. + + Returns: + Callable[[~.ListTopicSubscriptionsRequest], + ~.ListTopicSubscriptionsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'list_topic_subscriptions' not in self._stubs: + self._stubs['list_topic_subscriptions'] = self.grpc_channel.unary_unary( + '/google.pubsub.v1.Publisher/ListTopicSubscriptions', + request_serializer=pubsub.ListTopicSubscriptionsRequest.serialize, + response_deserializer=pubsub.ListTopicSubscriptionsResponse.deserialize, + ) + return self._stubs['list_topic_subscriptions'] + + @property + def list_topic_snapshots(self) -> Callable[ + [pubsub.ListTopicSnapshotsRequest], + pubsub.ListTopicSnapshotsResponse]: + r"""Return a callable for the list topic snapshots method over gRPC. + + Lists the names of the snapshots on this topic. Snapshots are + used in + `Seek `__ + operations, which allow you to manage message acknowledgments in + bulk. That is, you can set the acknowledgment state of messages + in an existing subscription to the state captured by a snapshot. + + Returns: + Callable[[~.ListTopicSnapshotsRequest], + ~.ListTopicSnapshotsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'list_topic_snapshots' not in self._stubs: + self._stubs['list_topic_snapshots'] = self.grpc_channel.unary_unary( + '/google.pubsub.v1.Publisher/ListTopicSnapshots', + request_serializer=pubsub.ListTopicSnapshotsRequest.serialize, + response_deserializer=pubsub.ListTopicSnapshotsResponse.deserialize, + ) + return self._stubs['list_topic_snapshots'] + + @property + def delete_topic(self) -> Callable[ + [pubsub.DeleteTopicRequest], + empty.Empty]: + r"""Return a callable for the delete topic method over gRPC. + + Deletes the topic with the given name. Returns ``NOT_FOUND`` if + the topic does not exist. After a topic is deleted, a new topic + may be created with the same name; this is an entirely new topic + with none of the old configuration or subscriptions. Existing + subscriptions to this topic are not deleted, but their ``topic`` + field is set to ``_deleted-topic_``. + + Returns: + Callable[[~.DeleteTopicRequest], + ~.Empty]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'delete_topic' not in self._stubs: + self._stubs['delete_topic'] = self.grpc_channel.unary_unary( + '/google.pubsub.v1.Publisher/DeleteTopic', + request_serializer=pubsub.DeleteTopicRequest.serialize, + response_deserializer=empty.Empty.FromString, + ) + return self._stubs['delete_topic'] + + @property + def detach_subscription(self) -> Callable[ + [pubsub.DetachSubscriptionRequest], + pubsub.DetachSubscriptionResponse]: + r"""Return a callable for the detach subscription method over gRPC. + + Detaches a subscription from this topic. All messages retained + in the subscription are dropped. Subsequent ``Pull`` and + ``StreamingPull`` requests will return FAILED_PRECONDITION. If + the subscription is a push subscription, pushes to the endpoint + will stop. + + Returns: + Callable[[~.DetachSubscriptionRequest], + ~.DetachSubscriptionResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'detach_subscription' not in self._stubs: + self._stubs['detach_subscription'] = self.grpc_channel.unary_unary( + '/google.pubsub.v1.Publisher/DetachSubscription', + request_serializer=pubsub.DetachSubscriptionRequest.serialize, + response_deserializer=pubsub.DetachSubscriptionResponse.deserialize, + ) + return self._stubs['detach_subscription'] + + @property + def set_iam_policy( + self, + ) -> Callable[[iam_policy.SetIamPolicyRequest], policy.Policy]: + r"""Return a callable for the set iam policy method over gRPC. + Sets the IAM access control policy on the specified + function. Replaces any existing policy. + Returns: + Callable[[~.SetIamPolicyRequest], + ~.Policy]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "set_iam_policy" not in self._stubs: + self._stubs["set_iam_policy"] = self.grpc_channel.unary_unary( + "/google.iam.v1.IAMPolicy/SetIamPolicy", + request_serializer=iam_policy.SetIamPolicyRequest.SerializeToString, + response_deserializer=policy.Policy.FromString, + ) + return self._stubs["set_iam_policy"] + + @property + def get_iam_policy( + self, + ) -> Callable[[iam_policy.GetIamPolicyRequest], policy.Policy]: + r"""Return a callable for the get iam policy method over gRPC. + Gets the IAM access control policy for a function. + Returns an empty policy if the function exists and does + not have a policy set. + Returns: + Callable[[~.GetIamPolicyRequest], + ~.Policy]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_iam_policy" not in self._stubs: + self._stubs["get_iam_policy"] = self.grpc_channel.unary_unary( + "/google.iam.v1.IAMPolicy/GetIamPolicy", + request_serializer=iam_policy.GetIamPolicyRequest.SerializeToString, + response_deserializer=policy.Policy.FromString, + ) + return self._stubs["get_iam_policy"] + + @property + def test_iam_permissions( + self, + ) -> Callable[ + [iam_policy.TestIamPermissionsRequest], iam_policy.TestIamPermissionsResponse + ]: + r"""Return a callable for the test iam permissions method over gRPC. + Tests the specified permissions against the IAM access control + policy for a function. If the function does not exist, this will + return an empty set of permissions, not a NOT_FOUND error. + Returns: + Callable[[~.TestIamPermissionsRequest], + ~.TestIamPermissionsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "test_iam_permissions" not in self._stubs: + self._stubs["test_iam_permissions"] = self.grpc_channel.unary_unary( + "/google.iam.v1.IAMPolicy/TestIamPermissions", + request_serializer=iam_policy.TestIamPermissionsRequest.SerializeToString, + response_deserializer=iam_policy.TestIamPermissionsResponse.FromString, + ) + return self._stubs["test_iam_permissions"] + + +__all__ = ( + 'PublisherGrpcTransport', +) diff --git a/owl-bot-staging/v1/google/pubsub_v1/services/publisher/transports/grpc_asyncio.py b/owl-bot-staging/v1/google/pubsub_v1/services/publisher/transports/grpc_asyncio.py new file mode 100644 index 000000000..80c8a32ce --- /dev/null +++ b/owl-bot-staging/v1/google/pubsub_v1/services/publisher/transports/grpc_asyncio.py @@ -0,0 +1,564 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple + +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 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.pubsub_v1.types import pubsub + +from .base import PublisherTransport, DEFAULT_CLIENT_INFO +from .grpc import PublisherGrpcTransport + + +class PublisherGrpcAsyncIOTransport(PublisherTransport): + """gRPC AsyncIO backend transport for Publisher. + + The service that an application uses to manipulate topics, + and to send messages to a topic. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + + _grpc_channel: aio.Channel + _stubs: Dict[str, Callable] = {} + + @classmethod + def create_channel(cls, + host: str = 'pubsub.googleapis.com', + credentials: credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + 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, + **kwargs + ) + + def __init__(self, *, + host: str = 'pubsub.googleapis.com', + credentials: credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: aio.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id=None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[aio.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or applicatin default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + credentials=self._credentials, + credentials_file=credentials_file, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def create_topic(self) -> Callable[ + [pubsub.Topic], + Awaitable[pubsub.Topic]]: + r"""Return a callable for the create topic method over gRPC. + + Creates the given topic with the given name. See the [resource + name rules] + (https://cloud.google.com/pubsub/docs/admin#resource_names). + + Returns: + Callable[[~.Topic], + Awaitable[~.Topic]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'create_topic' not in self._stubs: + self._stubs['create_topic'] = self.grpc_channel.unary_unary( + '/google.pubsub.v1.Publisher/CreateTopic', + request_serializer=pubsub.Topic.serialize, + response_deserializer=pubsub.Topic.deserialize, + ) + return self._stubs['create_topic'] + + @property + def update_topic(self) -> Callable[ + [pubsub.UpdateTopicRequest], + Awaitable[pubsub.Topic]]: + r"""Return a callable for the update topic method over gRPC. + + Updates an existing topic. Note that certain + properties of a topic are not modifiable. + + Returns: + Callable[[~.UpdateTopicRequest], + Awaitable[~.Topic]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'update_topic' not in self._stubs: + self._stubs['update_topic'] = self.grpc_channel.unary_unary( + '/google.pubsub.v1.Publisher/UpdateTopic', + request_serializer=pubsub.UpdateTopicRequest.serialize, + response_deserializer=pubsub.Topic.deserialize, + ) + return self._stubs['update_topic'] + + @property + def publish(self) -> Callable[ + [pubsub.PublishRequest], + Awaitable[pubsub.PublishResponse]]: + r"""Return a callable for the publish method over gRPC. + + Adds one or more messages to the topic. Returns ``NOT_FOUND`` if + the topic does not exist. + + Returns: + Callable[[~.PublishRequest], + Awaitable[~.PublishResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'publish' not in self._stubs: + self._stubs['publish'] = self.grpc_channel.unary_unary( + '/google.pubsub.v1.Publisher/Publish', + request_serializer=pubsub.PublishRequest.serialize, + response_deserializer=pubsub.PublishResponse.deserialize, + ) + return self._stubs['publish'] + + @property + def get_topic(self) -> Callable[ + [pubsub.GetTopicRequest], + Awaitable[pubsub.Topic]]: + r"""Return a callable for the get topic method over gRPC. + + Gets the configuration of a topic. + + Returns: + Callable[[~.GetTopicRequest], + Awaitable[~.Topic]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_topic' not in self._stubs: + self._stubs['get_topic'] = self.grpc_channel.unary_unary( + '/google.pubsub.v1.Publisher/GetTopic', + request_serializer=pubsub.GetTopicRequest.serialize, + response_deserializer=pubsub.Topic.deserialize, + ) + return self._stubs['get_topic'] + + @property + def list_topics(self) -> Callable[ + [pubsub.ListTopicsRequest], + Awaitable[pubsub.ListTopicsResponse]]: + r"""Return a callable for the list topics method over gRPC. + + Lists matching topics. + + Returns: + Callable[[~.ListTopicsRequest], + Awaitable[~.ListTopicsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'list_topics' not in self._stubs: + self._stubs['list_topics'] = self.grpc_channel.unary_unary( + '/google.pubsub.v1.Publisher/ListTopics', + request_serializer=pubsub.ListTopicsRequest.serialize, + response_deserializer=pubsub.ListTopicsResponse.deserialize, + ) + return self._stubs['list_topics'] + + @property + def list_topic_subscriptions(self) -> Callable[ + [pubsub.ListTopicSubscriptionsRequest], + Awaitable[pubsub.ListTopicSubscriptionsResponse]]: + r"""Return a callable for the list topic subscriptions method over gRPC. + + Lists the names of the attached subscriptions on this + topic. + + Returns: + Callable[[~.ListTopicSubscriptionsRequest], + Awaitable[~.ListTopicSubscriptionsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'list_topic_subscriptions' not in self._stubs: + self._stubs['list_topic_subscriptions'] = self.grpc_channel.unary_unary( + '/google.pubsub.v1.Publisher/ListTopicSubscriptions', + request_serializer=pubsub.ListTopicSubscriptionsRequest.serialize, + response_deserializer=pubsub.ListTopicSubscriptionsResponse.deserialize, + ) + return self._stubs['list_topic_subscriptions'] + + @property + def list_topic_snapshots(self) -> Callable[ + [pubsub.ListTopicSnapshotsRequest], + Awaitable[pubsub.ListTopicSnapshotsResponse]]: + r"""Return a callable for the list topic snapshots method over gRPC. + + Lists the names of the snapshots on this topic. Snapshots are + used in + `Seek `__ + operations, which allow you to manage message acknowledgments in + bulk. That is, you can set the acknowledgment state of messages + in an existing subscription to the state captured by a snapshot. + + Returns: + Callable[[~.ListTopicSnapshotsRequest], + Awaitable[~.ListTopicSnapshotsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'list_topic_snapshots' not in self._stubs: + self._stubs['list_topic_snapshots'] = self.grpc_channel.unary_unary( + '/google.pubsub.v1.Publisher/ListTopicSnapshots', + request_serializer=pubsub.ListTopicSnapshotsRequest.serialize, + response_deserializer=pubsub.ListTopicSnapshotsResponse.deserialize, + ) + return self._stubs['list_topic_snapshots'] + + @property + def delete_topic(self) -> Callable[ + [pubsub.DeleteTopicRequest], + Awaitable[empty.Empty]]: + r"""Return a callable for the delete topic method over gRPC. + + Deletes the topic with the given name. Returns ``NOT_FOUND`` if + the topic does not exist. After a topic is deleted, a new topic + may be created with the same name; this is an entirely new topic + with none of the old configuration or subscriptions. Existing + subscriptions to this topic are not deleted, but their ``topic`` + field is set to ``_deleted-topic_``. + + Returns: + Callable[[~.DeleteTopicRequest], + Awaitable[~.Empty]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'delete_topic' not in self._stubs: + self._stubs['delete_topic'] = self.grpc_channel.unary_unary( + '/google.pubsub.v1.Publisher/DeleteTopic', + request_serializer=pubsub.DeleteTopicRequest.serialize, + response_deserializer=empty.Empty.FromString, + ) + return self._stubs['delete_topic'] + + @property + def detach_subscription(self) -> Callable[ + [pubsub.DetachSubscriptionRequest], + Awaitable[pubsub.DetachSubscriptionResponse]]: + r"""Return a callable for the detach subscription method over gRPC. + + Detaches a subscription from this topic. All messages retained + in the subscription are dropped. Subsequent ``Pull`` and + ``StreamingPull`` requests will return FAILED_PRECONDITION. If + the subscription is a push subscription, pushes to the endpoint + will stop. + + Returns: + Callable[[~.DetachSubscriptionRequest], + Awaitable[~.DetachSubscriptionResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'detach_subscription' not in self._stubs: + self._stubs['detach_subscription'] = self.grpc_channel.unary_unary( + '/google.pubsub.v1.Publisher/DetachSubscription', + request_serializer=pubsub.DetachSubscriptionRequest.serialize, + response_deserializer=pubsub.DetachSubscriptionResponse.deserialize, + ) + return self._stubs['detach_subscription'] + + @property + def set_iam_policy( + self, + ) -> Callable[[iam_policy.SetIamPolicyRequest], Awaitable[policy.Policy]]: + r"""Return a callable for the set iam policy method over gRPC. + Sets the IAM access control policy on the specified + function. Replaces any existing policy. + Returns: + Callable[[~.SetIamPolicyRequest], + Awaitable[~.Policy]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "set_iam_policy" not in self._stubs: + self._stubs["set_iam_policy"] = self.grpc_channel.unary_unary( + "/google.iam.v1.IAMPolicy/SetIamPolicy", + request_serializer=iam_policy.SetIamPolicyRequest.SerializeToString, + response_deserializer=policy.Policy.FromString, + ) + return self._stubs["set_iam_policy"] + + @property + def get_iam_policy( + self, + ) -> Callable[[iam_policy.GetIamPolicyRequest], Awaitable[policy.Policy]]: + r"""Return a callable for the get iam policy method over gRPC. + Gets the IAM access control policy for a function. + Returns an empty policy if the function exists and does + not have a policy set. + Returns: + Callable[[~.GetIamPolicyRequest], + Awaitable[~.Policy]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_iam_policy" not in self._stubs: + self._stubs["get_iam_policy"] = self.grpc_channel.unary_unary( + "/google.iam.v1.IAMPolicy/GetIamPolicy", + request_serializer=iam_policy.GetIamPolicyRequest.SerializeToString, + response_deserializer=policy.Policy.FromString, + ) + return self._stubs["get_iam_policy"] + + @property + def test_iam_permissions( + self, + ) -> Callable[ + [iam_policy.TestIamPermissionsRequest], + Awaitable[iam_policy.TestIamPermissionsResponse], + ]: + r"""Return a callable for the test iam permissions method over gRPC. + Tests the specified permissions against the IAM access control + policy for a function. If the function does not exist, this will + return an empty set of permissions, not a NOT_FOUND error. + Returns: + Callable[[~.TestIamPermissionsRequest], + Awaitable[~.TestIamPermissionsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "test_iam_permissions" not in self._stubs: + self._stubs["test_iam_permissions"] = self.grpc_channel.unary_unary( + "/google.iam.v1.IAMPolicy/TestIamPermissions", + request_serializer=iam_policy.TestIamPermissionsRequest.SerializeToString, + response_deserializer=iam_policy.TestIamPermissionsResponse.FromString, + ) + return self._stubs["test_iam_permissions"] + + +__all__ = ( + 'PublisherGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v1/google/pubsub_v1/services/schema_service/__init__.py b/owl-bot-staging/v1/google/pubsub_v1/services/schema_service/__init__.py new file mode 100644 index 000000000..e971e94da --- /dev/null +++ b/owl-bot-staging/v1/google/pubsub_v1/services/schema_service/__init__.py @@ -0,0 +1,24 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from .client import SchemaServiceClient +from .async_client import SchemaServiceAsyncClient + +__all__ = ( + 'SchemaServiceClient', + 'SchemaServiceAsyncClient', +) diff --git a/owl-bot-staging/v1/google/pubsub_v1/services/schema_service/async_client.py b/owl-bot-staging/v1/google/pubsub_v1/services/schema_service/async_client.py new file mode 100644 index 000000000..6787855f8 --- /dev/null +++ b/owl-bot-staging/v1/google/pubsub_v1/services/schema_service/async_client.py @@ -0,0 +1,906 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from collections import OrderedDict +import functools +import re +from typing import Dict, Sequence, Tuple, Type, Union +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 gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import 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.pubsub_v1.services.schema_service import pagers +from google.pubsub_v1.types import schema +from google.pubsub_v1.types import schema as gp_schema + +from .transports.base import SchemaServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import SchemaServiceGrpcAsyncIOTransport +from .client import SchemaServiceClient + + +class SchemaServiceAsyncClient: + """Service for doing schema-related operations.""" + + _client: SchemaServiceClient + + DEFAULT_ENDPOINT = SchemaServiceClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = SchemaServiceClient.DEFAULT_MTLS_ENDPOINT + + schema_path = staticmethod(SchemaServiceClient.schema_path) + parse_schema_path = staticmethod(SchemaServiceClient.parse_schema_path) + + common_billing_account_path = staticmethod(SchemaServiceClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(SchemaServiceClient.parse_common_billing_account_path) + + common_folder_path = staticmethod(SchemaServiceClient.common_folder_path) + parse_common_folder_path = staticmethod(SchemaServiceClient.parse_common_folder_path) + + common_organization_path = staticmethod(SchemaServiceClient.common_organization_path) + parse_common_organization_path = staticmethod(SchemaServiceClient.parse_common_organization_path) + + common_project_path = staticmethod(SchemaServiceClient.common_project_path) + parse_common_project_path = staticmethod(SchemaServiceClient.parse_common_project_path) + + common_location_path = staticmethod(SchemaServiceClient.common_location_path) + parse_common_location_path = staticmethod(SchemaServiceClient.parse_common_location_path) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + SchemaServiceAsyncClient: The constructed client. + """ + return SchemaServiceClient.from_service_account_info.__func__(SchemaServiceAsyncClient, info, *args, **kwargs) # type: ignore + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + SchemaServiceAsyncClient: The constructed client. + """ + return SchemaServiceClient.from_service_account_file.__func__(SchemaServiceAsyncClient, filename, *args, **kwargs) # type: ignore + + from_service_account_json = from_service_account_file + + @property + def transport(self) -> SchemaServiceTransport: + """Return the transport used by the client instance. + + Returns: + SchemaServiceTransport: The transport used by the client instance. + """ + return self._client.transport + + get_transport_class = functools.partial(type(SchemaServiceClient).get_transport_class, type(SchemaServiceClient)) + + def __init__(self, *, + credentials: credentials.Credentials = None, + transport: Union[str, SchemaServiceTransport] = 'grpc_asyncio', + client_options: ClientOptions = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiate the schema service client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, ~.SchemaServiceTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (ClientOptions): Custom options for the client. It + won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + """ + + self._client = SchemaServiceClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def create_schema(self, + request: gp_schema.CreateSchemaRequest = None, + *, + parent: str = None, + schema: gp_schema.Schema = None, + schema_id: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gp_schema.Schema: + r"""Creates a schema. + + Args: + request (:class:`google.pubsub_v1.types.CreateSchemaRequest`): + The request object. Request for the CreateSchema method. + parent (:class:`str`): + Required. The name of the project in which to create the + schema. Format is ``projects/{project-id}``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + schema (:class:`google.pubsub_v1.types.Schema`): + Required. The schema object to create. + + This schema's ``name`` parameter is ignored. The schema + object returned by CreateSchema will have a ``name`` + made using the given ``parent`` and ``schema_id``. + + This corresponds to the ``schema`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + schema_id (:class:`str`): + The ID to use for the schema, which will become the + final component of the schema's resource name. + + See + https://cloud.google.com/pubsub/docs/admin#resource_names + for resource name constraints. + + This corresponds to the ``schema_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.pubsub_v1.types.Schema: + A schema resource. + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, schema, schema_id]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + request = gp_schema.CreateSchemaRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if parent is not None: + request.parent = parent + if schema is not None: + request.schema = schema + if schema_id is not None: + request.schema_id = schema_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.create_schema, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_schema(self, + request: schema.GetSchemaRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> schema.Schema: + r"""Gets a schema. + + Args: + request (:class:`google.pubsub_v1.types.GetSchemaRequest`): + The request object. Request for the GetSchema method. + name (:class:`str`): + Required. The name of the schema to get. Format is + ``projects/{project}/schemas/{schema}``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.pubsub_v1.types.Schema: + A schema resource. + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + request = schema.GetSchemaRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.get_schema, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('name', request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_schemas(self, + request: schema.ListSchemasRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListSchemasAsyncPager: + r"""Lists schemas in a project. + + Args: + request (:class:`google.pubsub_v1.types.ListSchemasRequest`): + The request object. Request for the `ListSchemas` + method. + parent (:class:`str`): + Required. The name of the project in which to list + schemas. Format is ``projects/{project-id}``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.pubsub_v1.services.schema_service.pagers.ListSchemasAsyncPager: + Response for the ListSchemas method. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + request = schema.ListSchemasRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.list_schemas, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListSchemasAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def delete_schema(self, + request: schema.DeleteSchemaRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes a schema. + + Args: + request (:class:`google.pubsub_v1.types.DeleteSchemaRequest`): + The request object. Request for the `DeleteSchema` + method. + name (:class:`str`): + Required. Name of the schema to delete. Format is + ``projects/{project}/schemas/{schema}``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + request = schema.DeleteSchemaRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.delete_schema, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('name', request.name), + )), + ) + + # Send the request. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def validate_schema(self, + request: gp_schema.ValidateSchemaRequest = None, + *, + parent: str = None, + schema: gp_schema.Schema = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gp_schema.ValidateSchemaResponse: + r"""Validates a schema. + + Args: + request (:class:`google.pubsub_v1.types.ValidateSchemaRequest`): + The request object. Request for the `ValidateSchema` + method. + parent (:class:`str`): + Required. The name of the project in which to validate + schemas. Format is ``projects/{project-id}``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + schema (:class:`google.pubsub_v1.types.Schema`): + Required. The schema object to + validate. + + This corresponds to the ``schema`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.pubsub_v1.types.ValidateSchemaResponse: + Response for the ValidateSchema method. + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, schema]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + request = gp_schema.ValidateSchemaRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if parent is not None: + request.parent = parent + if schema is not None: + request.schema = schema + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.validate_schema, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def validate_message(self, + request: schema.ValidateMessageRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> schema.ValidateMessageResponse: + r"""Validates a message against a schema. + + Args: + 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. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.pubsub_v1.types.ValidateMessageResponse: + Response for the ValidateMessage method. + """ + # Create or coerce a protobuf request object. + + request = schema.ValidateMessageRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.validate_message, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def set_iam_policy( + self, + request: iam_policy.SetIamPolicyRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> policy.Policy: + r"""Sets the IAM access control policy on the specified + function. Replaces any existing policy. + Args: + request (:class:`~.iam_policy.SetIamPolicyRequest`): + The request object. Request message for `SetIamPolicy` + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.policy.Policy: + Defines an Identity and Access Management (IAM) policy. + It is used to specify access control policies for Cloud + Platform resources. + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members`` to a single + ``role``. Members can be user accounts, service + accounts, Google groups, and domains (such as G Suite). + A ``role`` is a named list of permissions (defined by + IAM or configured by users). A ``binding`` can + optionally specify a ``condition``, which is a logic + expression that further constrains the role binding + based on attributes about the request and/or target + resource. + **JSON Example** + :: + { + "bindings": [ + { + "role": "roles/resourcemanager.organizationAdmin", + "members": [ + "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + }, + { + "role": "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { + "title": "expirable access", + "description": "Does not grant access after Sep 2020", + "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", + } + } + ] + } + **YAML Example** + :: + bindings: + - members: + - user:mike@example.com + - group:admins@example.com + - domain:google.com + - serviceAccount:my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin + - members: + - user:eve@example.com + role: roles/resourcemanager.organizationViewer + condition: + title: expirable access + description: Does not grant access after Sep 2020 + expression: request.time < timestamp('2020-10-01T00:00:00.000Z') + For a description of IAM and its features, see the `IAM + developer's + guide `__. + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = iam_policy.SetIamPolicyRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.set_iam_policy, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("resource", request.resource),)), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def get_iam_policy( + self, + request: iam_policy.GetIamPolicyRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> policy.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`): + The request object. Request message for `GetIamPolicy` + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.policy.Policy: + Defines an Identity and Access Management (IAM) policy. + It is used to specify access control policies for Cloud + Platform resources. + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members`` to a single + ``role``. Members can be user accounts, service + accounts, Google groups, and domains (such as G Suite). + A ``role`` is a named list of permissions (defined by + IAM or configured by users). A ``binding`` can + optionally specify a ``condition``, which is a logic + expression that further constrains the role binding + based on attributes about the request and/or target + resource. + **JSON Example** + :: + { + "bindings": [ + { + "role": "roles/resourcemanager.organizationAdmin", + "members": [ + "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + }, + { + "role": "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { + "title": "expirable access", + "description": "Does not grant access after Sep 2020", + "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", + } + } + ] + } + **YAML Example** + :: + bindings: + - members: + - user:mike@example.com + - group:admins@example.com + - domain:google.com + - serviceAccount:my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin + - members: + - user:eve@example.com + role: roles/resourcemanager.organizationViewer + condition: + title: expirable access + description: Does not grant access after Sep 2020 + expression: request.time < timestamp('2020-10-01T00:00:00.000Z') + For a description of IAM and its features, see the `IAM + developer's + guide `__. + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = iam_policy.GetIamPolicyRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.get_iam_policy, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("resource", request.resource),)), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def test_iam_permissions( + self, + request: iam_policy.TestIamPermissionsRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> iam_policy.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`): + The request object. Request message for + `TestIamPermissions` method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.iam_policy.TestIamPermissionsResponse: + Response message for ``TestIamPermissions`` method. + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = iam_policy.TestIamPermissionsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.test_iam_permissions, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("resource", request.resource),)), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + 'google-pubsub', + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + 'SchemaServiceAsyncClient', +) diff --git a/owl-bot-staging/v1/google/pubsub_v1/services/schema_service/client.py b/owl-bot-staging/v1/google/pubsub_v1/services/schema_service/client.py new file mode 100644 index 000000000..5e32b6c0d --- /dev/null +++ b/owl-bot-staging/v1/google/pubsub_v1/services/schema_service/client.py @@ -0,0 +1,1085 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from collections import OrderedDict +from distutils import util +import os +import re +from typing import Callable, Dict, Optional, Sequence, Tuple, Type, Union +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 gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import 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.pubsub_v1.services.schema_service import pagers +from google.pubsub_v1.types import schema +from google.pubsub_v1.types import schema as gp_schema + +from .transports.base import SchemaServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import SchemaServiceGrpcTransport +from .transports.grpc_asyncio import SchemaServiceGrpcAsyncIOTransport + + +class SchemaServiceClientMeta(type): + """Metaclass for the SchemaService client. + + This provides class-level methods for building and retrieving + support objects (e.g. transport) without polluting the client instance + objects. + """ + _transport_registry = OrderedDict() # type: Dict[str, Type[SchemaServiceTransport]] + _transport_registry['grpc'] = SchemaServiceGrpcTransport + _transport_registry['grpc_asyncio'] = SchemaServiceGrpcAsyncIOTransport + + def get_transport_class(cls, + label: str = None, + ) -> Type[SchemaServiceTransport]: + """Return an appropriate transport class. + + Args: + label: The name of the desired transport. If none is + provided, then the first transport in the registry is used. + + Returns: + The transport class to use. + """ + # If a specific transport is requested, return that one. + if label: + return cls._transport_registry[label] + + # No transport is requested; return the default (that is, the first one + # in the dictionary). + return next(iter(cls._transport_registry.values())) + + +class SchemaServiceClient(metaclass=SchemaServiceClientMeta): + """Service for doing schema-related operations.""" + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint): + """Convert api endpoint to mTLS endpoint. + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to + "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + Args: + api_endpoint (Optional[str]): the api endpoint to convert. + Returns: + str: converted mTLS api endpoint. + """ + if not api_endpoint: + return api_endpoint + + mtls_endpoint_re = re.compile( + r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" + ) + + m = mtls_endpoint_re.match(api_endpoint) + name, mtls, sandbox, googledomain = m.groups() + if mtls or not googledomain: + return api_endpoint + + if sandbox: + return api_endpoint.replace( + "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" + ) + + return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + + DEFAULT_ENDPOINT = 'pubsub.googleapis.com' + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + SchemaServiceClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_info(info) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + SchemaServiceClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_file( + filename) + kwargs['credentials'] = credentials + return cls(*args, **kwargs) + + from_service_account_json = from_service_account_file + + @property + def transport(self) -> SchemaServiceTransport: + """Return the transport used by the client instance. + + Returns: + SchemaServiceTransport: The transport used by the client instance. + """ + return self._transport + + @staticmethod + def schema_path(project: str,schema: str,) -> str: + """Return 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.""" + 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.""" + return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str,str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path(folder: str, ) -> str: + """Return a fully-qualified folder string.""" + return "folders/{folder}".format(folder=folder, ) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str,str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path(organization: str, ) -> str: + """Return a fully-qualified organization string.""" + return "organizations/{organization}".format(organization=organization, ) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str,str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path(project: str, ) -> str: + """Return a fully-qualified project string.""" + return "projects/{project}".format(project=project, ) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str,str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path(project: str, location: str, ) -> str: + """Return a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format(project=project, location=location, ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str,str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + + def __init__(self, *, + credentials: Optional[credentials.Credentials] = None, + transport: Union[str, SchemaServiceTransport, None] = None, + client_options: Optional[client_options_lib.ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiate the schema service client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, SchemaServiceTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. It won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + if isinstance(client_options, dict): + client_options = client_options_lib.from_dict(client_options) + if client_options is None: + client_options = client_options_lib.ClientOptions() + + # Create SSL credentials for mutual TLS if needed. + use_client_cert = bool(util.strtobool(os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false"))) + + client_cert_source_func = None + is_mtls = False + if use_client_cert: + if client_options.client_cert_source: + is_mtls = True + 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 + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + else: + use_mtls_env = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_mtls_env == "never": + api_endpoint = self.DEFAULT_ENDPOINT + 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 + else: + raise MutualTLSChannelError( + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted values: never, auto, always" + ) + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + if isinstance(transport, SchemaServiceTransport): + # transport is a SchemaServiceTransport instance. + if credentials or client_options.credentials_file: + raise ValueError('When providing a transport instance, ' + 'provide its credentials directly.') + if client_options.scopes: + raise ValueError( + "When providing a transport instance, " + "provide its scopes directly." + ) + self._transport = transport + else: + Transport = type(self).get_transport_class(transport) + self._transport = Transport( + credentials=credentials, + credentials_file=client_options.credentials_file, + host=api_endpoint, + scopes=client_options.scopes, + client_cert_source_for_mtls=client_cert_source_func, + quota_project_id=client_options.quota_project_id, + client_info=client_info, + ) + + def create_schema(self, + request: gp_schema.CreateSchemaRequest = None, + *, + parent: str = None, + schema: gp_schema.Schema = None, + schema_id: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gp_schema.Schema: + r"""Creates a schema. + + Args: + request (google.pubsub_v1.types.CreateSchemaRequest): + The request object. Request for the CreateSchema method. + parent (str): + Required. The name of the project in which to create the + schema. Format is ``projects/{project-id}``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + schema (google.pubsub_v1.types.Schema): + Required. The schema object to create. + + This schema's ``name`` parameter is ignored. The schema + object returned by CreateSchema will have a ``name`` + made using the given ``parent`` and ``schema_id``. + + This corresponds to the ``schema`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + schema_id (str): + The ID to use for the schema, which will become the + final component of the schema's resource name. + + See + https://cloud.google.com/pubsub/docs/admin#resource_names + for resource name constraints. + + This corresponds to the ``schema_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.pubsub_v1.types.Schema: + A schema resource. + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, schema, schema_id]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a gp_schema.CreateSchemaRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, gp_schema.CreateSchemaRequest): + request = gp_schema.CreateSchemaRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if parent is not None: + request.parent = parent + if schema is not None: + request.schema = schema + if schema_id is not None: + request.schema_id = schema_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_schema] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_schema(self, + request: schema.GetSchemaRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> schema.Schema: + r"""Gets a schema. + + Args: + request (google.pubsub_v1.types.GetSchemaRequest): + The request object. Request for the GetSchema method. + name (str): + Required. The name of the schema to get. Format is + ``projects/{project}/schemas/{schema}``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.pubsub_v1.types.Schema: + A schema resource. + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a schema.GetSchemaRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, schema.GetSchemaRequest): + request = schema.GetSchemaRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_schema] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('name', request.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_schemas(self, + request: schema.ListSchemasRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListSchemasPager: + r"""Lists schemas in a project. + + Args: + request (google.pubsub_v1.types.ListSchemasRequest): + The request object. Request for the `ListSchemas` + method. + parent (str): + Required. The name of the project in which to list + schemas. Format is ``projects/{project-id}``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.pubsub_v1.services.schema_service.pagers.ListSchemasPager: + Response for the ListSchemas method. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a schema.ListSchemasRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, schema.ListSchemasRequest): + request = schema.ListSchemasRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_schemas] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListSchemasPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def delete_schema(self, + request: schema.DeleteSchemaRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes a schema. + + Args: + request (google.pubsub_v1.types.DeleteSchemaRequest): + The request object. Request for the `DeleteSchema` + method. + name (str): + Required. Name of the schema to delete. Format is + ``projects/{project}/schemas/{schema}``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a schema.DeleteSchemaRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, schema.DeleteSchemaRequest): + request = schema.DeleteSchemaRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.delete_schema] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('name', request.name), + )), + ) + + # Send the request. + rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + def validate_schema(self, + request: gp_schema.ValidateSchemaRequest = None, + *, + parent: str = None, + schema: gp_schema.Schema = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gp_schema.ValidateSchemaResponse: + r"""Validates a schema. + + Args: + request (google.pubsub_v1.types.ValidateSchemaRequest): + The request object. Request for the `ValidateSchema` + method. + parent (str): + Required. The name of the project in which to validate + schemas. Format is ``projects/{project-id}``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + schema (google.pubsub_v1.types.Schema): + Required. The schema object to + validate. + + This corresponds to the ``schema`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.pubsub_v1.types.ValidateSchemaResponse: + Response for the ValidateSchema method. + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, schema]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a gp_schema.ValidateSchemaRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, gp_schema.ValidateSchemaRequest): + request = gp_schema.ValidateSchemaRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if parent is not None: + request.parent = parent + if schema is not None: + request.schema = schema + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.validate_schema] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def validate_message(self, + request: schema.ValidateMessageRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> schema.ValidateMessageResponse: + r"""Validates a message against a schema. + + Args: + 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. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.pubsub_v1.types.ValidateMessageResponse: + Response for the ValidateMessage method. + """ + # Create or coerce a protobuf request object. + + # Minor optimization to avoid making a copy if the user passes + # in a schema.ValidateMessageRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, schema.ValidateMessageRequest): + request = schema.ValidateMessageRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.validate_message] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def set_iam_policy( + self, + request: iam_policy.SetIamPolicyRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> policy.Policy: + r"""Sets the IAM access control policy on the specified + function. Replaces any existing policy. + Args: + request (:class:`~.iam_policy.SetIamPolicyRequest`): + The request object. Request message for `SetIamPolicy` + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.policy.Policy: + Defines an Identity and Access Management (IAM) policy. + It is used to specify access control policies for Cloud + Platform resources. + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members`` to a single + ``role``. Members can be user accounts, service + accounts, Google groups, and domains (such as G Suite). + A ``role`` is a named list of permissions (defined by + IAM or configured by users). A ``binding`` can + optionally specify a ``condition``, which is a logic + expression that further constrains the role binding + based on attributes about the request and/or target + resource. + **JSON Example** + :: + { + "bindings": [ + { + "role": "roles/resourcemanager.organizationAdmin", + "members": [ + "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + }, + { + "role": "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { + "title": "expirable access", + "description": "Does not grant access after Sep 2020", + "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", + } + } + ] + } + **YAML Example** + :: + bindings: + - members: + - user:mike@example.com + - group:admins@example.com + - domain:google.com + - serviceAccount:my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin + - members: + - user:eve@example.com + role: roles/resourcemanager.organizationViewer + condition: + title: expirable access + description: Does not grant access after Sep 2020 + expression: request.time < timestamp('2020-10-01T00:00:00.000Z') + For a description of IAM and its features, see the `IAM + developer's + guide `__. + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = iam_policy.SetIamPolicyRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.set_iam_policy, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("resource", request.resource),)), + ) + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def get_iam_policy( + self, + request: iam_policy.GetIamPolicyRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> policy.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`): + The request object. Request message for `GetIamPolicy` + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.policy.Policy: + Defines an Identity and Access Management (IAM) policy. + It is used to specify access control policies for Cloud + Platform resources. + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members`` to a single + ``role``. Members can be user accounts, service + accounts, Google groups, and domains (such as G Suite). + A ``role`` is a named list of permissions (defined by + IAM or configured by users). A ``binding`` can + optionally specify a ``condition``, which is a logic + expression that further constrains the role binding + based on attributes about the request and/or target + resource. + **JSON Example** + :: + { + "bindings": [ + { + "role": "roles/resourcemanager.organizationAdmin", + "members": [ + "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + }, + { + "role": "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { + "title": "expirable access", + "description": "Does not grant access after Sep 2020", + "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", + } + } + ] + } + **YAML Example** + :: + bindings: + - members: + - user:mike@example.com + - group:admins@example.com + - domain:google.com + - serviceAccount:my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin + - members: + - user:eve@example.com + role: roles/resourcemanager.organizationViewer + condition: + title: expirable access + description: Does not grant access after Sep 2020 + expression: request.time < timestamp('2020-10-01T00:00:00.000Z') + For a description of IAM and its features, see the `IAM + developer's + guide `__. + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = iam_policy.GetIamPolicyRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.get_iam_policy, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("resource", request.resource),)), + ) + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def test_iam_permissions( + self, + request: iam_policy.TestIamPermissionsRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> iam_policy.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`): + The request object. Request message for + `TestIamPermissions` method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.iam_policy.TestIamPermissionsResponse: + Response message for ``TestIamPermissions`` method. + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = iam_policy.TestIamPermissionsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.test_iam_permissions, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("resource", request.resource),)), + ) + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + 'google-pubsub', + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + 'SchemaServiceClient', +) diff --git a/owl-bot-staging/v1/google/pubsub_v1/services/schema_service/pagers.py b/owl-bot-staging/v1/google/pubsub_v1/services/schema_service/pagers.py new file mode 100644 index 000000000..33081ca44 --- /dev/null +++ b/owl-bot-staging/v1/google/pubsub_v1/services/schema_service/pagers.py @@ -0,0 +1,142 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from typing import Any, AsyncIterable, Awaitable, Callable, Iterable, Sequence, Tuple, Optional + +from google.pubsub_v1.types import schema + + +class ListSchemasPager: + """A pager for iterating through ``list_schemas`` requests. + + This class thinly wraps an initial + :class:`google.pubsub_v1.types.ListSchemasResponse` object, and + provides an ``__iter__`` method to iterate through its + ``schemas`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListSchemas`` requests and continue to iterate + through the ``schemas`` field on the + corresponding responses. + + All the usual :class:`google.pubsub_v1.types.ListSchemasResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + def __init__(self, + method: Callable[..., schema.ListSchemasResponse], + request: schema.ListSchemasRequest, + response: schema.ListSchemasResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.pubsub_v1.types.ListSchemasRequest): + The initial request object. + response (google.pubsub_v1.types.ListSchemasResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = schema.ListSchemasRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterable[schema.ListSchemasResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterable[schema.Schema]: + for page in self.pages: + yield from page.schemas + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListSchemasAsyncPager: + """A pager for iterating through ``list_schemas`` requests. + + This class thinly wraps an initial + :class:`google.pubsub_v1.types.ListSchemasResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``schemas`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListSchemas`` requests and continue to iterate + through the ``schemas`` field on the + corresponding responses. + + All the usual :class:`google.pubsub_v1.types.ListSchemasResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + def __init__(self, + method: Callable[..., Awaitable[schema.ListSchemasResponse]], + request: schema.ListSchemasRequest, + response: schema.ListSchemasResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.pubsub_v1.types.ListSchemasRequest): + The initial request object. + response (google.pubsub_v1.types.ListSchemasResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = schema.ListSchemasRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterable[schema.ListSchemasResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method(self._request, metadata=self._metadata) + yield self._response + + def __aiter__(self) -> AsyncIterable[schema.Schema]: + async def async_generator(): + async for page in self.pages: + for response in page.schemas: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) diff --git a/owl-bot-staging/v1/google/pubsub_v1/services/schema_service/transports/__init__.py b/owl-bot-staging/v1/google/pubsub_v1/services/schema_service/transports/__init__.py new file mode 100644 index 000000000..e8b9b6315 --- /dev/null +++ b/owl-bot-staging/v1/google/pubsub_v1/services/schema_service/transports/__init__.py @@ -0,0 +1,35 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from collections import OrderedDict +from typing import Dict, Type + +from .base import SchemaServiceTransport +from .grpc import SchemaServiceGrpcTransport +from .grpc_asyncio import SchemaServiceGrpcAsyncIOTransport + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[SchemaServiceTransport]] +_transport_registry['grpc'] = SchemaServiceGrpcTransport +_transport_registry['grpc_asyncio'] = SchemaServiceGrpcAsyncIOTransport + +__all__ = ( + 'SchemaServiceTransport', + 'SchemaServiceGrpcTransport', + 'SchemaServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v1/google/pubsub_v1/services/schema_service/transports/base.py b/owl-bot-staging/v1/google/pubsub_v1/services/schema_service/transports/base.py new file mode 100644 index 000000000..75209ec2a --- /dev/null +++ b/owl-bot-staging/v1/google/pubsub_v1/services/schema_service/transports/base.py @@ -0,0 +1,232 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +import abc +import typing +import pkg_resources + +from google import auth # 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 +from google.auth import 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.pubsub_v1.types import schema +from google.pubsub_v1.types import schema as gp_schema + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + 'google-pubsub', + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + +class SchemaServiceTransport(abc.ABC): + """Abstract transport class for SchemaService.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/pubsub', + ) + + 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, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + 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): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + """ + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ':' not in host: + host += ':443' + self._host = host + + # 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("'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 + ) + + elif credentials is None: + credentials, _ = auth.default(scopes=self._scopes, quota_project_id=quota_project_id) + + # Save the credentials. + self._credentials = credentials + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.create_schema: gapic_v1.method.wrap_method( + self.create_schema, + default_timeout=None, + client_info=client_info, + ), + self.get_schema: gapic_v1.method.wrap_method( + self.get_schema, + default_timeout=None, + client_info=client_info, + ), + self.list_schemas: gapic_v1.method.wrap_method( + self.list_schemas, + default_timeout=None, + client_info=client_info, + ), + self.delete_schema: gapic_v1.method.wrap_method( + self.delete_schema, + default_timeout=None, + client_info=client_info, + ), + self.validate_schema: gapic_v1.method.wrap_method( + self.validate_schema, + default_timeout=None, + client_info=client_info, + ), + self.validate_message: gapic_v1.method.wrap_method( + self.validate_message, + default_timeout=None, + client_info=client_info, + ), + + } + + @property + def create_schema(self) -> typing.Callable[ + [gp_schema.CreateSchemaRequest], + typing.Union[ + gp_schema.Schema, + typing.Awaitable[gp_schema.Schema] + ]]: + raise NotImplementedError() + + @property + def get_schema(self) -> typing.Callable[ + [schema.GetSchemaRequest], + typing.Union[ + schema.Schema, + typing.Awaitable[schema.Schema] + ]]: + raise NotImplementedError() + + @property + def list_schemas(self) -> typing.Callable[ + [schema.ListSchemasRequest], + typing.Union[ + schema.ListSchemasResponse, + typing.Awaitable[schema.ListSchemasResponse] + ]]: + raise NotImplementedError() + + @property + def delete_schema(self) -> typing.Callable[ + [schema.DeleteSchemaRequest], + typing.Union[ + empty.Empty, + typing.Awaitable[empty.Empty] + ]]: + raise NotImplementedError() + + @property + def validate_schema(self) -> typing.Callable[ + [gp_schema.ValidateSchemaRequest], + typing.Union[ + gp_schema.ValidateSchemaResponse, + typing.Awaitable[gp_schema.ValidateSchemaResponse] + ]]: + raise NotImplementedError() + + @property + def validate_message(self) -> typing.Callable[ + [schema.ValidateMessageRequest], + typing.Union[ + schema.ValidateMessageResponse, + typing.Awaitable[schema.ValidateMessageResponse] + ]]: + raise NotImplementedError() + + @property + def set_iam_policy( + self, + ) -> typing.Callable[ + [iam_policy.SetIamPolicyRequest], + typing.Union[policy.Policy, typing.Awaitable[policy.Policy]], + ]: + raise NotImplementedError() + + @property + def get_iam_policy( + self, + ) -> typing.Callable[ + [iam_policy.GetIamPolicyRequest], + typing.Union[policy.Policy, typing.Awaitable[policy.Policy]], + ]: + raise NotImplementedError() + + @property + def test_iam_permissions( + self, + ) -> typing.Callable[ + [iam_policy.TestIamPermissionsRequest], + typing.Union[ + iam_policy.TestIamPermissionsResponse, + typing.Awaitable[iam_policy.TestIamPermissionsResponse], + ], + ]: + raise NotImplementedError() + + +__all__ = ( + 'SchemaServiceTransport', +) diff --git a/owl-bot-staging/v1/google/pubsub_v1/services/schema_service/transports/grpc.py b/owl-bot-staging/v1/google/pubsub_v1/services/schema_service/transports/grpc.py new file mode 100644 index 000000000..e0b15742f --- /dev/null +++ b/owl-bot-staging/v1/google/pubsub_v1/services/schema_service/transports/grpc.py @@ -0,0 +1,461 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple + +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 +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.pubsub_v1.types import schema +from google.pubsub_v1.types import schema as gp_schema + +from .base import SchemaServiceTransport, DEFAULT_CLIENT_INFO + + +class SchemaServiceGrpcTransport(SchemaServiceTransport): + """gRPC backend transport for SchemaService. + + Service for doing schema-related operations. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + _stubs: Dict[str, Callable] + + def __init__(self, *, + host: str = 'pubsub.googleapis.com', + credentials: credentials.Credentials = None, + credentials_file: str = None, + scopes: Sequence[str] = None, + channel: grpc.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + channel (Optional[grpc.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or applicatin default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + credentials=self._credentials, + credentials_file=credentials_file, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel(cls, + host: str = 'pubsub.googleapis.com', + credentials: credentials.Credentials = None, + credentials_file: str = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> grpc.Channel: + """Create and return a gRPC channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + grpc.Channel: A gRPC channel object. + + Raises: + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + 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, + **kwargs + ) + + @property + def grpc_channel(self) -> grpc.Channel: + """Return the channel designed to connect to this service. + """ + return self._grpc_channel + + @property + def create_schema(self) -> Callable[ + [gp_schema.CreateSchemaRequest], + gp_schema.Schema]: + r"""Return a callable for the create schema method over gRPC. + + Creates a schema. + + Returns: + Callable[[~.CreateSchemaRequest], + ~.Schema]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'create_schema' not in self._stubs: + self._stubs['create_schema'] = self.grpc_channel.unary_unary( + '/google.pubsub.v1.SchemaService/CreateSchema', + request_serializer=gp_schema.CreateSchemaRequest.serialize, + response_deserializer=gp_schema.Schema.deserialize, + ) + return self._stubs['create_schema'] + + @property + def get_schema(self) -> Callable[ + [schema.GetSchemaRequest], + schema.Schema]: + r"""Return a callable for the get schema method over gRPC. + + Gets a schema. + + Returns: + Callable[[~.GetSchemaRequest], + ~.Schema]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_schema' not in self._stubs: + self._stubs['get_schema'] = self.grpc_channel.unary_unary( + '/google.pubsub.v1.SchemaService/GetSchema', + request_serializer=schema.GetSchemaRequest.serialize, + response_deserializer=schema.Schema.deserialize, + ) + return self._stubs['get_schema'] + + @property + def list_schemas(self) -> Callable[ + [schema.ListSchemasRequest], + schema.ListSchemasResponse]: + r"""Return a callable for the list schemas method over gRPC. + + Lists schemas in a project. + + Returns: + Callable[[~.ListSchemasRequest], + ~.ListSchemasResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'list_schemas' not in self._stubs: + self._stubs['list_schemas'] = self.grpc_channel.unary_unary( + '/google.pubsub.v1.SchemaService/ListSchemas', + request_serializer=schema.ListSchemasRequest.serialize, + response_deserializer=schema.ListSchemasResponse.deserialize, + ) + return self._stubs['list_schemas'] + + @property + def delete_schema(self) -> Callable[ + [schema.DeleteSchemaRequest], + empty.Empty]: + r"""Return a callable for the delete schema method over gRPC. + + Deletes a schema. + + Returns: + Callable[[~.DeleteSchemaRequest], + ~.Empty]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'delete_schema' not in self._stubs: + self._stubs['delete_schema'] = self.grpc_channel.unary_unary( + '/google.pubsub.v1.SchemaService/DeleteSchema', + request_serializer=schema.DeleteSchemaRequest.serialize, + response_deserializer=empty.Empty.FromString, + ) + return self._stubs['delete_schema'] + + @property + def validate_schema(self) -> Callable[ + [gp_schema.ValidateSchemaRequest], + gp_schema.ValidateSchemaResponse]: + r"""Return a callable for the validate schema method over gRPC. + + Validates a schema. + + Returns: + Callable[[~.ValidateSchemaRequest], + ~.ValidateSchemaResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'validate_schema' not in self._stubs: + self._stubs['validate_schema'] = self.grpc_channel.unary_unary( + '/google.pubsub.v1.SchemaService/ValidateSchema', + request_serializer=gp_schema.ValidateSchemaRequest.serialize, + response_deserializer=gp_schema.ValidateSchemaResponse.deserialize, + ) + return self._stubs['validate_schema'] + + @property + def validate_message(self) -> Callable[ + [schema.ValidateMessageRequest], + schema.ValidateMessageResponse]: + r"""Return a callable for the validate message method over gRPC. + + Validates a message against a schema. + + Returns: + Callable[[~.ValidateMessageRequest], + ~.ValidateMessageResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'validate_message' not in self._stubs: + self._stubs['validate_message'] = self.grpc_channel.unary_unary( + '/google.pubsub.v1.SchemaService/ValidateMessage', + request_serializer=schema.ValidateMessageRequest.serialize, + response_deserializer=schema.ValidateMessageResponse.deserialize, + ) + return self._stubs['validate_message'] + + @property + def set_iam_policy( + self, + ) -> Callable[[iam_policy.SetIamPolicyRequest], policy.Policy]: + r"""Return a callable for the set iam policy method over gRPC. + Sets the IAM access control policy on the specified + function. Replaces any existing policy. + Returns: + Callable[[~.SetIamPolicyRequest], + ~.Policy]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "set_iam_policy" not in self._stubs: + self._stubs["set_iam_policy"] = self.grpc_channel.unary_unary( + "/google.iam.v1.IAMPolicy/SetIamPolicy", + request_serializer=iam_policy.SetIamPolicyRequest.SerializeToString, + response_deserializer=policy.Policy.FromString, + ) + return self._stubs["set_iam_policy"] + + @property + def get_iam_policy( + self, + ) -> Callable[[iam_policy.GetIamPolicyRequest], policy.Policy]: + r"""Return a callable for the get iam policy method over gRPC. + Gets the IAM access control policy for a function. + Returns an empty policy if the function exists and does + not have a policy set. + Returns: + Callable[[~.GetIamPolicyRequest], + ~.Policy]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_iam_policy" not in self._stubs: + self._stubs["get_iam_policy"] = self.grpc_channel.unary_unary( + "/google.iam.v1.IAMPolicy/GetIamPolicy", + request_serializer=iam_policy.GetIamPolicyRequest.SerializeToString, + response_deserializer=policy.Policy.FromString, + ) + return self._stubs["get_iam_policy"] + + @property + def test_iam_permissions( + self, + ) -> Callable[ + [iam_policy.TestIamPermissionsRequest], iam_policy.TestIamPermissionsResponse + ]: + r"""Return a callable for the test iam permissions method over gRPC. + Tests the specified permissions against the IAM access control + policy for a function. If the function does not exist, this will + return an empty set of permissions, not a NOT_FOUND error. + Returns: + Callable[[~.TestIamPermissionsRequest], + ~.TestIamPermissionsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "test_iam_permissions" not in self._stubs: + self._stubs["test_iam_permissions"] = self.grpc_channel.unary_unary( + "/google.iam.v1.IAMPolicy/TestIamPermissions", + request_serializer=iam_policy.TestIamPermissionsRequest.SerializeToString, + response_deserializer=iam_policy.TestIamPermissionsResponse.FromString, + ) + return self._stubs["test_iam_permissions"] + + +__all__ = ( + 'SchemaServiceGrpcTransport', +) diff --git a/owl-bot-staging/v1/google/pubsub_v1/services/schema_service/transports/grpc_asyncio.py b/owl-bot-staging/v1/google/pubsub_v1/services/schema_service/transports/grpc_asyncio.py new file mode 100644 index 000000000..8972d09be --- /dev/null +++ b/owl-bot-staging/v1/google/pubsub_v1/services/schema_service/transports/grpc_asyncio.py @@ -0,0 +1,467 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple + +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 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.pubsub_v1.types import schema +from google.pubsub_v1.types import schema as gp_schema + +from .base import SchemaServiceTransport, DEFAULT_CLIENT_INFO +from .grpc import SchemaServiceGrpcTransport + + +class SchemaServiceGrpcAsyncIOTransport(SchemaServiceTransport): + """gRPC AsyncIO backend transport for SchemaService. + + Service for doing schema-related operations. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + + _grpc_channel: aio.Channel + _stubs: Dict[str, Callable] = {} + + @classmethod + def create_channel(cls, + host: str = 'pubsub.googleapis.com', + credentials: credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + 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, + **kwargs + ) + + def __init__(self, *, + host: str = 'pubsub.googleapis.com', + credentials: credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: aio.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id=None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[aio.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or applicatin default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + credentials=self._credentials, + credentials_file=credentials_file, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def create_schema(self) -> Callable[ + [gp_schema.CreateSchemaRequest], + Awaitable[gp_schema.Schema]]: + r"""Return a callable for the create schema method over gRPC. + + Creates a schema. + + Returns: + Callable[[~.CreateSchemaRequest], + Awaitable[~.Schema]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'create_schema' not in self._stubs: + self._stubs['create_schema'] = self.grpc_channel.unary_unary( + '/google.pubsub.v1.SchemaService/CreateSchema', + request_serializer=gp_schema.CreateSchemaRequest.serialize, + response_deserializer=gp_schema.Schema.deserialize, + ) + return self._stubs['create_schema'] + + @property + def get_schema(self) -> Callable[ + [schema.GetSchemaRequest], + Awaitable[schema.Schema]]: + r"""Return a callable for the get schema method over gRPC. + + Gets a schema. + + Returns: + Callable[[~.GetSchemaRequest], + Awaitable[~.Schema]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_schema' not in self._stubs: + self._stubs['get_schema'] = self.grpc_channel.unary_unary( + '/google.pubsub.v1.SchemaService/GetSchema', + request_serializer=schema.GetSchemaRequest.serialize, + response_deserializer=schema.Schema.deserialize, + ) + return self._stubs['get_schema'] + + @property + def list_schemas(self) -> Callable[ + [schema.ListSchemasRequest], + Awaitable[schema.ListSchemasResponse]]: + r"""Return a callable for the list schemas method over gRPC. + + Lists schemas in a project. + + Returns: + Callable[[~.ListSchemasRequest], + Awaitable[~.ListSchemasResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'list_schemas' not in self._stubs: + self._stubs['list_schemas'] = self.grpc_channel.unary_unary( + '/google.pubsub.v1.SchemaService/ListSchemas', + request_serializer=schema.ListSchemasRequest.serialize, + response_deserializer=schema.ListSchemasResponse.deserialize, + ) + return self._stubs['list_schemas'] + + @property + def delete_schema(self) -> Callable[ + [schema.DeleteSchemaRequest], + Awaitable[empty.Empty]]: + r"""Return a callable for the delete schema method over gRPC. + + Deletes a schema. + + Returns: + Callable[[~.DeleteSchemaRequest], + Awaitable[~.Empty]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'delete_schema' not in self._stubs: + self._stubs['delete_schema'] = self.grpc_channel.unary_unary( + '/google.pubsub.v1.SchemaService/DeleteSchema', + request_serializer=schema.DeleteSchemaRequest.serialize, + response_deserializer=empty.Empty.FromString, + ) + return self._stubs['delete_schema'] + + @property + def validate_schema(self) -> Callable[ + [gp_schema.ValidateSchemaRequest], + Awaitable[gp_schema.ValidateSchemaResponse]]: + r"""Return a callable for the validate schema method over gRPC. + + Validates a schema. + + Returns: + Callable[[~.ValidateSchemaRequest], + Awaitable[~.ValidateSchemaResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'validate_schema' not in self._stubs: + self._stubs['validate_schema'] = self.grpc_channel.unary_unary( + '/google.pubsub.v1.SchemaService/ValidateSchema', + request_serializer=gp_schema.ValidateSchemaRequest.serialize, + response_deserializer=gp_schema.ValidateSchemaResponse.deserialize, + ) + return self._stubs['validate_schema'] + + @property + def validate_message(self) -> Callable[ + [schema.ValidateMessageRequest], + Awaitable[schema.ValidateMessageResponse]]: + r"""Return a callable for the validate message method over gRPC. + + Validates a message against a schema. + + Returns: + Callable[[~.ValidateMessageRequest], + Awaitable[~.ValidateMessageResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'validate_message' not in self._stubs: + self._stubs['validate_message'] = self.grpc_channel.unary_unary( + '/google.pubsub.v1.SchemaService/ValidateMessage', + request_serializer=schema.ValidateMessageRequest.serialize, + response_deserializer=schema.ValidateMessageResponse.deserialize, + ) + return self._stubs['validate_message'] + + @property + def set_iam_policy( + self, + ) -> Callable[[iam_policy.SetIamPolicyRequest], Awaitable[policy.Policy]]: + r"""Return a callable for the set iam policy method over gRPC. + Sets the IAM access control policy on the specified + function. Replaces any existing policy. + Returns: + Callable[[~.SetIamPolicyRequest], + Awaitable[~.Policy]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "set_iam_policy" not in self._stubs: + self._stubs["set_iam_policy"] = self.grpc_channel.unary_unary( + "/google.iam.v1.IAMPolicy/SetIamPolicy", + request_serializer=iam_policy.SetIamPolicyRequest.SerializeToString, + response_deserializer=policy.Policy.FromString, + ) + return self._stubs["set_iam_policy"] + + @property + def get_iam_policy( + self, + ) -> Callable[[iam_policy.GetIamPolicyRequest], Awaitable[policy.Policy]]: + r"""Return a callable for the get iam policy method over gRPC. + Gets the IAM access control policy for a function. + Returns an empty policy if the function exists and does + not have a policy set. + Returns: + Callable[[~.GetIamPolicyRequest], + Awaitable[~.Policy]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_iam_policy" not in self._stubs: + self._stubs["get_iam_policy"] = self.grpc_channel.unary_unary( + "/google.iam.v1.IAMPolicy/GetIamPolicy", + request_serializer=iam_policy.GetIamPolicyRequest.SerializeToString, + response_deserializer=policy.Policy.FromString, + ) + return self._stubs["get_iam_policy"] + + @property + def test_iam_permissions( + self, + ) -> Callable[ + [iam_policy.TestIamPermissionsRequest], + Awaitable[iam_policy.TestIamPermissionsResponse], + ]: + r"""Return a callable for the test iam permissions method over gRPC. + Tests the specified permissions against the IAM access control + policy for a function. If the function does not exist, this will + return an empty set of permissions, not a NOT_FOUND error. + Returns: + Callable[[~.TestIamPermissionsRequest], + Awaitable[~.TestIamPermissionsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "test_iam_permissions" not in self._stubs: + self._stubs["test_iam_permissions"] = self.grpc_channel.unary_unary( + "/google.iam.v1.IAMPolicy/TestIamPermissions", + request_serializer=iam_policy.TestIamPermissionsRequest.SerializeToString, + response_deserializer=iam_policy.TestIamPermissionsResponse.FromString, + ) + return self._stubs["test_iam_permissions"] + + +__all__ = ( + 'SchemaServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v1/google/pubsub_v1/services/subscriber/__init__.py b/owl-bot-staging/v1/google/pubsub_v1/services/subscriber/__init__.py new file mode 100644 index 000000000..0b9bda81d --- /dev/null +++ b/owl-bot-staging/v1/google/pubsub_v1/services/subscriber/__init__.py @@ -0,0 +1,24 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from .client import SubscriberClient +from .async_client import SubscriberAsyncClient + +__all__ = ( + 'SubscriberClient', + 'SubscriberAsyncClient', +) diff --git a/owl-bot-staging/v1/google/pubsub_v1/services/subscriber/async_client.py b/owl-bot-staging/v1/google/pubsub_v1/services/subscriber/async_client.py new file mode 100644 index 000000000..326ec6d9a --- /dev/null +++ b/owl-bot-staging/v1/google/pubsub_v1/services/subscriber/async_client.py @@ -0,0 +1,1994 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from collections import OrderedDict +import functools +import re +from typing import Dict, AsyncIterable, Awaitable, AsyncIterator, Sequence, Tuple, Type, Union +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 gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import 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.pubsub_v1.services.subscriber import pagers +from google.pubsub_v1.types import pubsub + +from .transports.base import SubscriberTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import SubscriberGrpcAsyncIOTransport +from .client import SubscriberClient + + +class SubscriberAsyncClient: + """The service that an application uses to manipulate subscriptions and + to consume messages from a subscription via the ``Pull`` method or + by establishing a bi-directional stream using the ``StreamingPull`` + method. + """ + + _client: SubscriberClient + + DEFAULT_ENDPOINT = SubscriberClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = SubscriberClient.DEFAULT_MTLS_ENDPOINT + + snapshot_path = staticmethod(SubscriberClient.snapshot_path) + parse_snapshot_path = staticmethod(SubscriberClient.parse_snapshot_path) + subscription_path = staticmethod(SubscriberClient.subscription_path) + parse_subscription_path = staticmethod(SubscriberClient.parse_subscription_path) + topic_path = staticmethod(SubscriberClient.topic_path) + parse_topic_path = staticmethod(SubscriberClient.parse_topic_path) + + common_billing_account_path = staticmethod(SubscriberClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(SubscriberClient.parse_common_billing_account_path) + + common_folder_path = staticmethod(SubscriberClient.common_folder_path) + parse_common_folder_path = staticmethod(SubscriberClient.parse_common_folder_path) + + common_organization_path = staticmethod(SubscriberClient.common_organization_path) + parse_common_organization_path = staticmethod(SubscriberClient.parse_common_organization_path) + + common_project_path = staticmethod(SubscriberClient.common_project_path) + parse_common_project_path = staticmethod(SubscriberClient.parse_common_project_path) + + common_location_path = staticmethod(SubscriberClient.common_location_path) + parse_common_location_path = staticmethod(SubscriberClient.parse_common_location_path) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + SubscriberAsyncClient: The constructed client. + """ + return SubscriberClient.from_service_account_info.__func__(SubscriberAsyncClient, info, *args, **kwargs) # type: ignore + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + SubscriberAsyncClient: The constructed client. + """ + return SubscriberClient.from_service_account_file.__func__(SubscriberAsyncClient, filename, *args, **kwargs) # type: ignore + + from_service_account_json = from_service_account_file + + @property + def transport(self) -> SubscriberTransport: + """Return the transport used by the client instance. + + Returns: + SubscriberTransport: The transport used by the client instance. + """ + return self._client.transport + + get_transport_class = functools.partial(type(SubscriberClient).get_transport_class, type(SubscriberClient)) + + def __init__(self, *, + credentials: credentials.Credentials = None, + transport: Union[str, SubscriberTransport] = 'grpc_asyncio', + client_options: ClientOptions = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiate the subscriber client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, ~.SubscriberTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (ClientOptions): Custom options for the client. It + won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + """ + + self._client = SubscriberClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def create_subscription(self, + request: pubsub.Subscription = None, + *, + name: str = None, + topic: str = None, + push_config: pubsub.PushConfig = None, + ack_deadline_seconds: int = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pubsub.Subscription: + r"""Creates a subscription to a given topic. See the [resource name + rules] + (https://cloud.google.com/pubsub/docs/admin#resource_names). If + the subscription already exists, returns ``ALREADY_EXISTS``. If + the corresponding topic doesn't exist, returns ``NOT_FOUND``. + + If the name is not provided in the request, the server will + assign a random name for this subscription on the same project + as the topic, conforming to the [resource name format] + (https://cloud.google.com/pubsub/docs/admin#resource_names). The + generated name is populated in the returned Subscription object. + Note that for REST API requests, you must specify a name in the + request. + + Args: + request (:class:`google.pubsub_v1.types.Subscription`): + The request object. A subscription resource. + name (:class:`str`): + Required. The name of the subscription. It must have the + format + ``"projects/{project}/subscriptions/{subscription}"``. + ``{subscription}`` must start with a letter, and contain + only letters (``[A-Za-z]``), numbers (``[0-9]``), dashes + (``-``), underscores (``_``), periods (``.``), tildes + (``~``), plus (``+``) or percent signs (``%``). It must + be between 3 and 255 characters in length, and it must + not start with ``"goog"``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + topic (:class:`str`): + Required. The name of the topic from which this + subscription is receiving messages. Format is + ``projects/{project}/topics/{topic}``. The value of this + field will be ``_deleted-topic_`` if the topic has been + deleted. + + This corresponds to the ``topic`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + push_config (:class:`google.pubsub_v1.types.PushConfig`): + If push delivery is used with this subscription, this + field is used to configure it. An empty ``pushConfig`` + signifies that the subscriber will pull and ack messages + using API methods. + + This corresponds to the ``push_config`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + ack_deadline_seconds (:class:`int`): + The approximate amount of time (on a best-effort basis) + Pub/Sub waits for the subscriber to acknowledge receipt + before resending the message. In the interval after the + message is delivered and before it is acknowledged, it + is considered to be outstanding. During that time + period, the message will not be redelivered (on a + best-effort basis). + + For pull subscriptions, this value is used as the + initial value for the ack deadline. To override this + value for a given message, call ``ModifyAckDeadline`` + with the corresponding ``ack_id`` if using non-streaming + pull or send the ``ack_id`` in a + ``StreamingModifyAckDeadlineRequest`` if using streaming + pull. The minimum custom deadline you can specify is 10 + seconds. The maximum custom deadline you can specify is + 600 seconds (10 minutes). If this parameter is 0, a + default value of 10 seconds is used. + + For push delivery, this value is also used to set the + request timeout for the call to the push endpoint. + + If the subscriber never acknowledges the message, the + Pub/Sub system will eventually redeliver the message. + + This corresponds to the ``ack_deadline_seconds`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.pubsub_v1.types.Subscription: + A subscription resource. + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name, topic, push_config, ack_deadline_seconds]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + request = pubsub.Subscription(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if name is not None: + request.name = name + if topic is not None: + request.topic = topic + if push_config is not None: + request.push_config = push_config + if ack_deadline_seconds is not None: + request.ack_deadline_seconds = ack_deadline_seconds + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.create_subscription, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.Aborted, + exceptions.ServiceUnavailable, + exceptions.Unknown, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('name', request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_subscription(self, + request: pubsub.GetSubscriptionRequest = None, + *, + subscription: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pubsub.Subscription: + r"""Gets the configuration details of a subscription. + + Args: + request (:class:`google.pubsub_v1.types.GetSubscriptionRequest`): + The request object. Request for the GetSubscription + method. + subscription (:class:`str`): + Required. The name of the subscription to get. Format is + ``projects/{project}/subscriptions/{sub}``. + + This corresponds to the ``subscription`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.pubsub_v1.types.Subscription: + A subscription resource. + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([subscription]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + request = pubsub.GetSubscriptionRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if subscription is not None: + request.subscription = subscription + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.get_subscription, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.Aborted, + exceptions.ServiceUnavailable, + exceptions.Unknown, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('subscription', request.subscription), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def update_subscription(self, + request: pubsub.UpdateSubscriptionRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pubsub.Subscription: + r"""Updates an existing subscription. Note that certain + properties of a subscription, such as its topic, are not + modifiable. + + Args: + 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. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.pubsub_v1.types.Subscription: + A subscription resource. + """ + # Create or coerce a protobuf request object. + + request = pubsub.UpdateSubscriptionRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.update_subscription, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('subscription.name', request.subscription.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_subscriptions(self, + request: pubsub.ListSubscriptionsRequest = None, + *, + project: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListSubscriptionsAsyncPager: + r"""Lists matching subscriptions. + + Args: + request (:class:`google.pubsub_v1.types.ListSubscriptionsRequest`): + The request object. Request for the `ListSubscriptions` + method. + project (:class:`str`): + Required. The name of the project in which to list + subscriptions. Format is ``projects/{project-id}``. + + This corresponds to the ``project`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.pubsub_v1.services.subscriber.pagers.ListSubscriptionsAsyncPager: + Response for the ListSubscriptions method. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([project]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + request = pubsub.ListSubscriptionsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if project is not None: + request.project = project + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.list_subscriptions, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.Aborted, + exceptions.ServiceUnavailable, + exceptions.Unknown, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('project', request.project), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListSubscriptionsAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def delete_subscription(self, + request: pubsub.DeleteSubscriptionRequest = None, + *, + subscription: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes an existing subscription. All messages retained in the + subscription are immediately dropped. Calls to ``Pull`` after + deletion will return ``NOT_FOUND``. After a subscription is + deleted, a new one may be created with the same name, but the + new one has no association with the old subscription or its + topic unless the same topic is specified. + + Args: + request (:class:`google.pubsub_v1.types.DeleteSubscriptionRequest`): + The request object. Request for the DeleteSubscription + method. + subscription (:class:`str`): + Required. The subscription to delete. Format is + ``projects/{project}/subscriptions/{sub}``. + + This corresponds to the ``subscription`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([subscription]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + request = pubsub.DeleteSubscriptionRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if subscription is not None: + request.subscription = subscription + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.delete_subscription, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('subscription', request.subscription), + )), + ) + + # Send the request. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def modify_ack_deadline(self, + request: pubsub.ModifyAckDeadlineRequest = None, + *, + subscription: str = None, + ack_ids: Sequence[str] = None, + ack_deadline_seconds: int = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Modifies the ack deadline for a specific message. This method is + useful to indicate that more time is needed to process a message + by the subscriber, or to make the message available for + redelivery if the processing was interrupted. Note that this + does not modify the subscription-level ``ackDeadlineSeconds`` + used for subsequent messages. + + Args: + request (:class:`google.pubsub_v1.types.ModifyAckDeadlineRequest`): + The request object. Request for the ModifyAckDeadline + method. + subscription (:class:`str`): + Required. The name of the subscription. Format is + ``projects/{project}/subscriptions/{sub}``. + + This corresponds to the ``subscription`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + ack_ids (:class:`Sequence[str]`): + Required. List of acknowledgment IDs. + This corresponds to the ``ack_ids`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + ack_deadline_seconds (:class:`int`): + Required. The new ack deadline with respect to the time + this request was sent to the Pub/Sub system. For + example, if the value is 10, the new ack deadline will + expire 10 seconds after the ``ModifyAckDeadline`` call + was made. Specifying zero might immediately make the + message available for delivery to another subscriber + client. This typically results in an increase in the + rate of message redeliveries (that is, duplicates). The + minimum deadline you can specify is 0 seconds. The + maximum deadline you can specify is 600 seconds (10 + minutes). + + This corresponds to the ``ack_deadline_seconds`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([subscription, ack_ids, ack_deadline_seconds]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + request = pubsub.ModifyAckDeadlineRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if subscription is not None: + request.subscription = subscription + if ack_deadline_seconds is not None: + request.ack_deadline_seconds = ack_deadline_seconds + + if ack_ids: + request.ack_ids.extend(ack_ids) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.modify_ack_deadline, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('subscription', request.subscription), + )), + ) + + # Send the request. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def acknowledge(self, + request: pubsub.AcknowledgeRequest = None, + *, + subscription: str = None, + ack_ids: Sequence[str] = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Acknowledges the messages associated with the ``ack_ids`` in the + ``AcknowledgeRequest``. The Pub/Sub system can remove the + relevant messages from the subscription. + + Acknowledging a message whose ack deadline has expired may + succeed, but such a message may be redelivered later. + Acknowledging a message more than once will not result in an + error. + + Args: + request (:class:`google.pubsub_v1.types.AcknowledgeRequest`): + The request object. Request for the Acknowledge method. + subscription (:class:`str`): + Required. The subscription whose message is being + acknowledged. Format is + ``projects/{project}/subscriptions/{sub}``. + + This corresponds to the ``subscription`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + ack_ids (:class:`Sequence[str]`): + Required. The acknowledgment ID for the messages being + acknowledged that was returned by the Pub/Sub system in + the ``Pull`` response. Must not be empty. + + This corresponds to the ``ack_ids`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([subscription, ack_ids]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + request = pubsub.AcknowledgeRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if subscription is not None: + request.subscription = subscription + + if ack_ids: + request.ack_ids.extend(ack_ids) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.acknowledge, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('subscription', request.subscription), + )), + ) + + # Send the request. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def pull(self, + request: pubsub.PullRequest = None, + *, + subscription: str = None, + return_immediately: bool = None, + max_messages: int = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pubsub.PullResponse: + r"""Pulls messages from the server. The server may return + ``UNAVAILABLE`` if there are too many concurrent pull requests + pending for the given subscription. + + Args: + request (:class:`google.pubsub_v1.types.PullRequest`): + The request object. Request for the `Pull` method. + subscription (:class:`str`): + Required. The subscription from which messages should be + pulled. Format is + ``projects/{project}/subscriptions/{sub}``. + + This corresponds to the ``subscription`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + return_immediately (:class:`bool`): + Optional. If this field set to true, the system will + respond immediately even if it there are no messages + available to return in the ``Pull`` response. Otherwise, + the system may wait (for a bounded amount of time) until + at least one message is available, rather than returning + no messages. Warning: setting this field to ``true`` is + discouraged because it adversely impacts the performance + of ``Pull`` operations. We recommend that users do not + set this field. + + This corresponds to the ``return_immediately`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + max_messages (:class:`int`): + Required. The maximum number of + messages to return for this request. + Must be a positive integer. The Pub/Sub + system may return fewer than the number + specified. + + This corresponds to the ``max_messages`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.pubsub_v1.types.PullResponse: + Response for the Pull method. + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([subscription, return_immediately, max_messages]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + request = pubsub.PullRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if subscription is not None: + request.subscription = subscription + if return_immediately is not None: + request.return_immediately = return_immediately + if max_messages is not None: + request.max_messages = max_messages + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.pull, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.Aborted, + exceptions.ServiceUnavailable, + exceptions.Unknown, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('subscription', request.subscription), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def streaming_pull(self, + requests: AsyncIterator[pubsub.StreamingPullRequest] = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> Awaitable[AsyncIterable[pubsub.StreamingPullResponse]]: + r"""Establishes a stream with the server, which sends messages down + to the client. The client streams acknowledgements and ack + deadline modifications back to the server. The server will close + the stream and return the status on any error. The server may + close the stream with status ``UNAVAILABLE`` to reassign + server-side resources, in which case, the client should + re-establish the stream. Flow control can be achieved by + configuring the underlying RPC channel. + + Args: + requests (AsyncIterator[`google.pubsub_v1.types.StreamingPullRequest`]): + The request object AsyncIterator. Request for the `StreamingPull` + streaming RPC method. This request is used to establish + the initial stream as well as to stream acknowledgements + and ack deadline modifications from the client to the + server. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + AsyncIterable[google.pubsub_v1.types.StreamingPullResponse]: + Response for the StreamingPull method. This response is used to stream + messages from the server to the client. + + """ + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.streaming_pull, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.Aborted, + exceptions.DeadlineExceeded, + exceptions.InternalServerError, + exceptions.ResourceExhausted, + exceptions.ServiceUnavailable, + ), + deadline=900.0, + ), + default_timeout=900.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Send the request. + response = rpc( + requests, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def modify_push_config(self, + request: pubsub.ModifyPushConfigRequest = None, + *, + subscription: str = None, + push_config: pubsub.PushConfig = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Modifies the ``PushConfig`` for a specified subscription. + + This may be used to change a push subscription to a pull one + (signified by an empty ``PushConfig``) or vice versa, or change + the endpoint URL and other attributes of a push subscription. + Messages will accumulate for delivery continuously through the + call regardless of changes to the ``PushConfig``. + + Args: + request (:class:`google.pubsub_v1.types.ModifyPushConfigRequest`): + The request object. Request for the ModifyPushConfig + method. + subscription (:class:`str`): + Required. The name of the subscription. Format is + ``projects/{project}/subscriptions/{sub}``. + + This corresponds to the ``subscription`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + push_config (:class:`google.pubsub_v1.types.PushConfig`): + Required. The push configuration for future deliveries. + + An empty ``pushConfig`` indicates that the Pub/Sub + system should stop pushing messages from the given + subscription and allow messages to be pulled and + acknowledged - effectively pausing the subscription if + ``Pull`` or ``StreamingPull`` is not called. + + This corresponds to the ``push_config`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([subscription, push_config]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + request = pubsub.ModifyPushConfigRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if subscription is not None: + request.subscription = subscription + if push_config is not None: + request.push_config = push_config + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.modify_push_config, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('subscription', request.subscription), + )), + ) + + # Send the request. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def get_snapshot(self, + request: pubsub.GetSnapshotRequest = None, + *, + snapshot: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pubsub.Snapshot: + r"""Gets the configuration details of a snapshot. + Snapshots are used in Seek operations, which allow you to manage + message acknowledgments in bulk. That is, you can set + the acknowledgment state of messages in an existing + subscription to the state captured by a snapshot. + + Args: + request (:class:`google.pubsub_v1.types.GetSnapshotRequest`): + The request object. Request for the GetSnapshot method. + snapshot (:class:`str`): + Required. The name of the snapshot to get. Format is + ``projects/{project}/snapshots/{snap}``. + + This corresponds to the ``snapshot`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.pubsub_v1.types.Snapshot: + A snapshot resource. Snapshots are used in + [Seek](https://cloud.google.com/pubsub/docs/replay-overview) + operations, which allow you to manage message + acknowledgments in bulk. That is, you can set the + acknowledgment state of messages in an existing + subscription to the state captured by a snapshot. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([snapshot]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + request = pubsub.GetSnapshotRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if snapshot is not None: + request.snapshot = snapshot + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.get_snapshot, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.Aborted, + exceptions.ServiceUnavailable, + exceptions.Unknown, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('snapshot', request.snapshot), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_snapshots(self, + request: pubsub.ListSnapshotsRequest = None, + *, + project: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListSnapshotsAsyncPager: + r"""Lists the existing snapshots. Snapshots are used in + `Seek `__ + operations, which allow you to manage message acknowledgments in + bulk. That is, you can set the acknowledgment state of messages + in an existing subscription to the state captured by a snapshot. + + Args: + request (:class:`google.pubsub_v1.types.ListSnapshotsRequest`): + The request object. Request for the `ListSnapshots` + method. + project (:class:`str`): + Required. The name of the project in which to list + snapshots. Format is ``projects/{project-id}``. + + This corresponds to the ``project`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.pubsub_v1.services.subscriber.pagers.ListSnapshotsAsyncPager: + Response for the ListSnapshots method. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([project]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + request = pubsub.ListSnapshotsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if project is not None: + request.project = project + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.list_snapshots, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.Aborted, + exceptions.ServiceUnavailable, + exceptions.Unknown, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('project', request.project), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListSnapshotsAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def create_snapshot(self, + request: pubsub.CreateSnapshotRequest = None, + *, + name: str = None, + subscription: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pubsub.Snapshot: + r"""Creates a snapshot from the requested subscription. Snapshots + are used in + `Seek `__ + operations, which allow you to manage message acknowledgments in + bulk. That is, you can set the acknowledgment state of messages + in an existing subscription to the state captured by a snapshot. + If the snapshot already exists, returns ``ALREADY_EXISTS``. If + the requested subscription doesn't exist, returns ``NOT_FOUND``. + If the backlog in the subscription is too old -- and the + resulting snapshot would expire in less than 1 hour -- then + ``FAILED_PRECONDITION`` is returned. See also the + ``Snapshot.expire_time`` field. If the name is not provided in + the request, the server will assign a random name for this + snapshot on the same project as the subscription, conforming to + the [resource name format] + (https://cloud.google.com/pubsub/docs/admin#resource_names). The + generated name is populated in the returned Snapshot object. + Note that for REST API requests, you must specify a name in the + request. + + Args: + request (:class:`google.pubsub_v1.types.CreateSnapshotRequest`): + The request object. Request for the `CreateSnapshot` + method. + name (:class:`str`): + Required. User-provided name for this snapshot. If the + name is not provided in the request, the server will + assign a random name for this snapshot on the same + project as the subscription. Note that for REST API + requests, you must specify a name. See the resource name + rules. Format is + ``projects/{project}/snapshots/{snap}``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + subscription (:class:`str`): + Required. The subscription whose backlog the snapshot + retains. Specifically, the created snapshot is + guaranteed to retain: (a) The existing backlog on the + subscription. More precisely, this is defined as the + messages in the subscription's backlog that are + unacknowledged upon the successful completion of the + ``CreateSnapshot`` request; as well as: (b) Any messages + published to the subscription's topic following the + successful completion of the CreateSnapshot request. + Format is ``projects/{project}/subscriptions/{sub}``. + + This corresponds to the ``subscription`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.pubsub_v1.types.Snapshot: + A snapshot resource. Snapshots are used in + [Seek](https://cloud.google.com/pubsub/docs/replay-overview) + operations, which allow you to manage message + acknowledgments in bulk. That is, you can set the + acknowledgment state of messages in an existing + subscription to the state captured by a snapshot. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name, subscription]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + request = pubsub.CreateSnapshotRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if name is not None: + request.name = name + if subscription is not None: + request.subscription = subscription + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.create_snapshot, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('name', request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def update_snapshot(self, + request: pubsub.UpdateSnapshotRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pubsub.Snapshot: + r"""Updates an existing snapshot. Snapshots are used in + Seek operations, which allow + you to manage message acknowledgments in bulk. That is, + you can set the acknowledgment state of messages in an + existing subscription to the state captured by a + snapshot. + + Args: + 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. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.pubsub_v1.types.Snapshot: + A snapshot resource. Snapshots are used in + [Seek](https://cloud.google.com/pubsub/docs/replay-overview) + operations, which allow you to manage message + acknowledgments in bulk. That is, you can set the + acknowledgment state of messages in an existing + subscription to the state captured by a snapshot. + + """ + # Create or coerce a protobuf request object. + + request = pubsub.UpdateSnapshotRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.update_snapshot, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('snapshot.name', request.snapshot.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def delete_snapshot(self, + request: pubsub.DeleteSnapshotRequest = None, + *, + snapshot: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Removes an existing snapshot. Snapshots are used in [Seek] + (https://cloud.google.com/pubsub/docs/replay-overview) + operations, which allow you to manage message acknowledgments in + bulk. That is, you can set the acknowledgment state of messages + in an existing subscription to the state captured by a snapshot. + When the snapshot is deleted, all messages retained in the + snapshot are immediately dropped. After a snapshot is deleted, a + new one may be created with the same name, but the new one has + no association with the old snapshot or its subscription, unless + the same subscription is specified. + + Args: + request (:class:`google.pubsub_v1.types.DeleteSnapshotRequest`): + The request object. Request for the `DeleteSnapshot` + method. + snapshot (:class:`str`): + Required. The name of the snapshot to delete. Format is + ``projects/{project}/snapshots/{snap}``. + + This corresponds to the ``snapshot`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([snapshot]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + request = pubsub.DeleteSnapshotRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if snapshot is not None: + request.snapshot = snapshot + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.delete_snapshot, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('snapshot', request.snapshot), + )), + ) + + # Send the request. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def seek(self, + request: pubsub.SeekRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pubsub.SeekResponse: + r"""Seeks an existing subscription to a point in time or to a given + snapshot, whichever is provided in the request. Snapshots are + used in [Seek] + (https://cloud.google.com/pubsub/docs/replay-overview) + operations, which allow you to manage message acknowledgments in + bulk. That is, you can set the acknowledgment state of messages + in an existing subscription to the state captured by a snapshot. + Note that both the subscription and the snapshot must be on the + same topic. + + 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. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.pubsub_v1.types.SeekResponse: + Response for the Seek method (this response is empty). + """ + # Create or coerce a protobuf request object. + + request = pubsub.SeekRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.seek, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.Aborted, + exceptions.ServiceUnavailable, + exceptions.Unknown, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('subscription', request.subscription), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def set_iam_policy( + self, + request: iam_policy.SetIamPolicyRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> policy.Policy: + r"""Sets the IAM access control policy on the specified + function. Replaces any existing policy. + Args: + request (:class:`~.iam_policy.SetIamPolicyRequest`): + The request object. Request message for `SetIamPolicy` + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.policy.Policy: + Defines an Identity and Access Management (IAM) policy. + It is used to specify access control policies for Cloud + Platform resources. + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members`` to a single + ``role``. Members can be user accounts, service + accounts, Google groups, and domains (such as G Suite). + A ``role`` is a named list of permissions (defined by + IAM or configured by users). A ``binding`` can + optionally specify a ``condition``, which is a logic + expression that further constrains the role binding + based on attributes about the request and/or target + resource. + **JSON Example** + :: + { + "bindings": [ + { + "role": "roles/resourcemanager.organizationAdmin", + "members": [ + "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + }, + { + "role": "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { + "title": "expirable access", + "description": "Does not grant access after Sep 2020", + "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", + } + } + ] + } + **YAML Example** + :: + bindings: + - members: + - user:mike@example.com + - group:admins@example.com + - domain:google.com + - serviceAccount:my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin + - members: + - user:eve@example.com + role: roles/resourcemanager.organizationViewer + condition: + title: expirable access + description: Does not grant access after Sep 2020 + expression: request.time < timestamp('2020-10-01T00:00:00.000Z') + For a description of IAM and its features, see the `IAM + developer's + guide `__. + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = iam_policy.SetIamPolicyRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.set_iam_policy, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("resource", request.resource),)), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def get_iam_policy( + self, + request: iam_policy.GetIamPolicyRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> policy.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`): + The request object. Request message for `GetIamPolicy` + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.policy.Policy: + Defines an Identity and Access Management (IAM) policy. + It is used to specify access control policies for Cloud + Platform resources. + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members`` to a single + ``role``. Members can be user accounts, service + accounts, Google groups, and domains (such as G Suite). + A ``role`` is a named list of permissions (defined by + IAM or configured by users). A ``binding`` can + optionally specify a ``condition``, which is a logic + expression that further constrains the role binding + based on attributes about the request and/or target + resource. + **JSON Example** + :: + { + "bindings": [ + { + "role": "roles/resourcemanager.organizationAdmin", + "members": [ + "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + }, + { + "role": "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { + "title": "expirable access", + "description": "Does not grant access after Sep 2020", + "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", + } + } + ] + } + **YAML Example** + :: + bindings: + - members: + - user:mike@example.com + - group:admins@example.com + - domain:google.com + - serviceAccount:my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin + - members: + - user:eve@example.com + role: roles/resourcemanager.organizationViewer + condition: + title: expirable access + description: Does not grant access after Sep 2020 + expression: request.time < timestamp('2020-10-01T00:00:00.000Z') + For a description of IAM and its features, see the `IAM + developer's + guide `__. + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = iam_policy.GetIamPolicyRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.get_iam_policy, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("resource", request.resource),)), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def test_iam_permissions( + self, + request: iam_policy.TestIamPermissionsRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> iam_policy.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`): + The request object. Request message for + `TestIamPermissions` method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.iam_policy.TestIamPermissionsResponse: + Response message for ``TestIamPermissions`` method. + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = iam_policy.TestIamPermissionsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.test_iam_permissions, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("resource", request.resource),)), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + 'google-pubsub', + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + 'SubscriberAsyncClient', +) diff --git a/owl-bot-staging/v1/google/pubsub_v1/services/subscriber/client.py b/owl-bot-staging/v1/google/pubsub_v1/services/subscriber/client.py new file mode 100644 index 000000000..be3d1d5f1 --- /dev/null +++ b/owl-bot-staging/v1/google/pubsub_v1/services/subscriber/client.py @@ -0,0 +1,2032 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from collections import OrderedDict +from distutils import util +import os +import re +from typing import Callable, Dict, Optional, Iterable, Iterator, Sequence, Tuple, Type, Union +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 gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import 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.pubsub_v1.services.subscriber import pagers +from google.pubsub_v1.types import pubsub + +from .transports.base import SubscriberTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import SubscriberGrpcTransport +from .transports.grpc_asyncio import SubscriberGrpcAsyncIOTransport + + +class SubscriberClientMeta(type): + """Metaclass for the Subscriber client. + + This provides class-level methods for building and retrieving + support objects (e.g. transport) without polluting the client instance + objects. + """ + _transport_registry = OrderedDict() # type: Dict[str, Type[SubscriberTransport]] + _transport_registry['grpc'] = SubscriberGrpcTransport + _transport_registry['grpc_asyncio'] = SubscriberGrpcAsyncIOTransport + + def get_transport_class(cls, + label: str = None, + ) -> Type[SubscriberTransport]: + """Return an appropriate transport class. + + Args: + label: The name of the desired transport. If none is + provided, then the first transport in the registry is used. + + Returns: + The transport class to use. + """ + # If a specific transport is requested, return that one. + if label: + return cls._transport_registry[label] + + # No transport is requested; return the default (that is, the first one + # in the dictionary). + return next(iter(cls._transport_registry.values())) + + +class SubscriberClient(metaclass=SubscriberClientMeta): + """The service that an application uses to manipulate subscriptions and + to consume messages from a subscription via the ``Pull`` method or + by establishing a bi-directional stream using the ``StreamingPull`` + method. + """ + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint): + """Convert api endpoint to mTLS endpoint. + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to + "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + Args: + api_endpoint (Optional[str]): the api endpoint to convert. + Returns: + str: converted mTLS api endpoint. + """ + if not api_endpoint: + return api_endpoint + + mtls_endpoint_re = re.compile( + r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" + ) + + m = mtls_endpoint_re.match(api_endpoint) + name, mtls, sandbox, googledomain = m.groups() + if mtls or not googledomain: + return api_endpoint + + if sandbox: + return api_endpoint.replace( + "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" + ) + + return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + + DEFAULT_ENDPOINT = 'pubsub.googleapis.com' + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + SubscriberClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_info(info) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + SubscriberClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_file( + filename) + kwargs['credentials'] = credentials + return cls(*args, **kwargs) + + from_service_account_json = from_service_account_file + + @property + def transport(self) -> SubscriberTransport: + """Return the transport used by the client instance. + + Returns: + SubscriberTransport: The transport used by the client instance. + """ + return self._transport + + @staticmethod + def snapshot_path(project: str,snapshot: str,) -> str: + """Return 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.""" + 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.""" + 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.""" + m = re.match(r"^projects/(?P.+?)/subscriptions/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def topic_path(project: str,topic: str,) -> str: + """Return 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.""" + 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.""" + return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str,str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path(folder: str, ) -> str: + """Return a fully-qualified folder string.""" + return "folders/{folder}".format(folder=folder, ) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str,str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path(organization: str, ) -> str: + """Return a fully-qualified organization string.""" + return "organizations/{organization}".format(organization=organization, ) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str,str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path(project: str, ) -> str: + """Return a fully-qualified project string.""" + return "projects/{project}".format(project=project, ) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str,str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path(project: str, location: str, ) -> str: + """Return a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format(project=project, location=location, ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str,str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + + def __init__(self, *, + credentials: Optional[credentials.Credentials] = None, + transport: Union[str, SubscriberTransport, None] = None, + client_options: Optional[client_options_lib.ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiate the subscriber client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, SubscriberTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. It won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + if isinstance(client_options, dict): + client_options = client_options_lib.from_dict(client_options) + if client_options is None: + client_options = client_options_lib.ClientOptions() + + # Create SSL credentials for mutual TLS if needed. + use_client_cert = bool(util.strtobool(os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false"))) + + client_cert_source_func = None + is_mtls = False + if use_client_cert: + if client_options.client_cert_source: + is_mtls = True + 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 + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + else: + use_mtls_env = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_mtls_env == "never": + api_endpoint = self.DEFAULT_ENDPOINT + 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 + else: + raise MutualTLSChannelError( + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted values: never, auto, always" + ) + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + if isinstance(transport, SubscriberTransport): + # transport is a SubscriberTransport instance. + if credentials or client_options.credentials_file: + raise ValueError('When providing a transport instance, ' + 'provide its credentials directly.') + if client_options.scopes: + raise ValueError( + "When providing a transport instance, " + "provide its scopes directly." + ) + self._transport = transport + else: + Transport = type(self).get_transport_class(transport) + self._transport = Transport( + credentials=credentials, + credentials_file=client_options.credentials_file, + host=api_endpoint, + scopes=client_options.scopes, + client_cert_source_for_mtls=client_cert_source_func, + quota_project_id=client_options.quota_project_id, + client_info=client_info, + ) + + def create_subscription(self, + request: pubsub.Subscription = None, + *, + name: str = None, + topic: str = None, + push_config: pubsub.PushConfig = None, + ack_deadline_seconds: int = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pubsub.Subscription: + r"""Creates a subscription to a given topic. See the [resource name + rules] + (https://cloud.google.com/pubsub/docs/admin#resource_names). If + the subscription already exists, returns ``ALREADY_EXISTS``. If + the corresponding topic doesn't exist, returns ``NOT_FOUND``. + + If the name is not provided in the request, the server will + assign a random name for this subscription on the same project + as the topic, conforming to the [resource name format] + (https://cloud.google.com/pubsub/docs/admin#resource_names). The + generated name is populated in the returned Subscription object. + Note that for REST API requests, you must specify a name in the + request. + + Args: + request (google.pubsub_v1.types.Subscription): + The request object. A subscription resource. + name (str): + Required. The name of the subscription. It must have the + format + ``"projects/{project}/subscriptions/{subscription}"``. + ``{subscription}`` must start with a letter, and contain + only letters (``[A-Za-z]``), numbers (``[0-9]``), dashes + (``-``), underscores (``_``), periods (``.``), tildes + (``~``), plus (``+``) or percent signs (``%``). It must + be between 3 and 255 characters in length, and it must + not start with ``"goog"``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + topic (str): + Required. The name of the topic from which this + subscription is receiving messages. Format is + ``projects/{project}/topics/{topic}``. The value of this + field will be ``_deleted-topic_`` if the topic has been + deleted. + + This corresponds to the ``topic`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + push_config (google.pubsub_v1.types.PushConfig): + If push delivery is used with this subscription, this + field is used to configure it. An empty ``pushConfig`` + signifies that the subscriber will pull and ack messages + using API methods. + + This corresponds to the ``push_config`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + ack_deadline_seconds (int): + The approximate amount of time (on a best-effort basis) + Pub/Sub waits for the subscriber to acknowledge receipt + before resending the message. In the interval after the + message is delivered and before it is acknowledged, it + is considered to be outstanding. During that time + period, the message will not be redelivered (on a + best-effort basis). + + For pull subscriptions, this value is used as the + initial value for the ack deadline. To override this + value for a given message, call ``ModifyAckDeadline`` + with the corresponding ``ack_id`` if using non-streaming + pull or send the ``ack_id`` in a + ``StreamingModifyAckDeadlineRequest`` if using streaming + pull. The minimum custom deadline you can specify is 10 + seconds. The maximum custom deadline you can specify is + 600 seconds (10 minutes). If this parameter is 0, a + default value of 10 seconds is used. + + For push delivery, this value is also used to set the + request timeout for the call to the push endpoint. + + If the subscriber never acknowledges the message, the + Pub/Sub system will eventually redeliver the message. + + This corresponds to the ``ack_deadline_seconds`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.pubsub_v1.types.Subscription: + A subscription resource. + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name, topic, push_config, ack_deadline_seconds]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a pubsub.Subscription. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, pubsub.Subscription): + request = pubsub.Subscription(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if name is not None: + request.name = name + if topic is not None: + request.topic = topic + if push_config is not None: + request.push_config = push_config + if ack_deadline_seconds is not None: + request.ack_deadline_seconds = ack_deadline_seconds + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_subscription] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('name', request.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_subscription(self, + request: pubsub.GetSubscriptionRequest = None, + *, + subscription: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pubsub.Subscription: + r"""Gets the configuration details of a subscription. + + Args: + request (google.pubsub_v1.types.GetSubscriptionRequest): + The request object. Request for the GetSubscription + method. + subscription (str): + Required. The name of the subscription to get. Format is + ``projects/{project}/subscriptions/{sub}``. + + This corresponds to the ``subscription`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.pubsub_v1.types.Subscription: + A subscription resource. + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([subscription]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a pubsub.GetSubscriptionRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, pubsub.GetSubscriptionRequest): + request = pubsub.GetSubscriptionRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if subscription is not None: + request.subscription = subscription + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_subscription] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('subscription', request.subscription), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def update_subscription(self, + request: pubsub.UpdateSubscriptionRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pubsub.Subscription: + r"""Updates an existing subscription. Note that certain + properties of a subscription, such as its topic, are not + modifiable. + + Args: + 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. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.pubsub_v1.types.Subscription: + A subscription resource. + """ + # Create or coerce a protobuf request object. + + # Minor optimization to avoid making a copy if the user passes + # in a pubsub.UpdateSubscriptionRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, pubsub.UpdateSubscriptionRequest): + request = pubsub.UpdateSubscriptionRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update_subscription] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('subscription.name', request.subscription.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_subscriptions(self, + request: pubsub.ListSubscriptionsRequest = None, + *, + project: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListSubscriptionsPager: + r"""Lists matching subscriptions. + + Args: + request (google.pubsub_v1.types.ListSubscriptionsRequest): + The request object. Request for the `ListSubscriptions` + method. + project (str): + Required. The name of the project in which to list + subscriptions. Format is ``projects/{project-id}``. + + This corresponds to the ``project`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.pubsub_v1.services.subscriber.pagers.ListSubscriptionsPager: + Response for the ListSubscriptions method. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([project]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a pubsub.ListSubscriptionsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, pubsub.ListSubscriptionsRequest): + request = pubsub.ListSubscriptionsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if project is not None: + request.project = project + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_subscriptions] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('project', request.project), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListSubscriptionsPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def delete_subscription(self, + request: pubsub.DeleteSubscriptionRequest = None, + *, + subscription: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes an existing subscription. All messages retained in the + subscription are immediately dropped. Calls to ``Pull`` after + deletion will return ``NOT_FOUND``. After a subscription is + deleted, a new one may be created with the same name, but the + new one has no association with the old subscription or its + topic unless the same topic is specified. + + Args: + request (google.pubsub_v1.types.DeleteSubscriptionRequest): + The request object. Request for the DeleteSubscription + method. + subscription (str): + Required. The subscription to delete. Format is + ``projects/{project}/subscriptions/{sub}``. + + This corresponds to the ``subscription`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([subscription]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a pubsub.DeleteSubscriptionRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, pubsub.DeleteSubscriptionRequest): + request = pubsub.DeleteSubscriptionRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if subscription is not None: + request.subscription = subscription + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.delete_subscription] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('subscription', request.subscription), + )), + ) + + # Send the request. + rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + def modify_ack_deadline(self, + request: pubsub.ModifyAckDeadlineRequest = None, + *, + subscription: str = None, + ack_ids: Sequence[str] = None, + ack_deadline_seconds: int = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Modifies the ack deadline for a specific message. This method is + useful to indicate that more time is needed to process a message + by the subscriber, or to make the message available for + redelivery if the processing was interrupted. Note that this + does not modify the subscription-level ``ackDeadlineSeconds`` + used for subsequent messages. + + Args: + request (google.pubsub_v1.types.ModifyAckDeadlineRequest): + The request object. Request for the ModifyAckDeadline + method. + subscription (str): + Required. The name of the subscription. Format is + ``projects/{project}/subscriptions/{sub}``. + + This corresponds to the ``subscription`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + ack_ids (Sequence[str]): + Required. List of acknowledgment IDs. + This corresponds to the ``ack_ids`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + ack_deadline_seconds (int): + Required. The new ack deadline with respect to the time + this request was sent to the Pub/Sub system. For + example, if the value is 10, the new ack deadline will + expire 10 seconds after the ``ModifyAckDeadline`` call + was made. Specifying zero might immediately make the + message available for delivery to another subscriber + client. This typically results in an increase in the + rate of message redeliveries (that is, duplicates). The + minimum deadline you can specify is 0 seconds. The + maximum deadline you can specify is 600 seconds (10 + minutes). + + This corresponds to the ``ack_deadline_seconds`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([subscription, ack_ids, ack_deadline_seconds]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a pubsub.ModifyAckDeadlineRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, pubsub.ModifyAckDeadlineRequest): + request = pubsub.ModifyAckDeadlineRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if subscription is not None: + request.subscription = subscription + if ack_ids is not None: + request.ack_ids = ack_ids + if ack_deadline_seconds is not None: + request.ack_deadline_seconds = ack_deadline_seconds + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.modify_ack_deadline] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('subscription', request.subscription), + )), + ) + + # Send the request. + rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + def acknowledge(self, + request: pubsub.AcknowledgeRequest = None, + *, + subscription: str = None, + ack_ids: Sequence[str] = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Acknowledges the messages associated with the ``ack_ids`` in the + ``AcknowledgeRequest``. The Pub/Sub system can remove the + relevant messages from the subscription. + + Acknowledging a message whose ack deadline has expired may + succeed, but such a message may be redelivered later. + Acknowledging a message more than once will not result in an + error. + + Args: + request (google.pubsub_v1.types.AcknowledgeRequest): + The request object. Request for the Acknowledge method. + subscription (str): + Required. The subscription whose message is being + acknowledged. Format is + ``projects/{project}/subscriptions/{sub}``. + + This corresponds to the ``subscription`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + ack_ids (Sequence[str]): + Required. The acknowledgment ID for the messages being + acknowledged that was returned by the Pub/Sub system in + the ``Pull`` response. Must not be empty. + + This corresponds to the ``ack_ids`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([subscription, ack_ids]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a pubsub.AcknowledgeRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, pubsub.AcknowledgeRequest): + request = pubsub.AcknowledgeRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if subscription is not None: + request.subscription = subscription + if ack_ids is not None: + request.ack_ids = ack_ids + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.acknowledge] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('subscription', request.subscription), + )), + ) + + # Send the request. + rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + def pull(self, + request: pubsub.PullRequest = None, + *, + subscription: str = None, + return_immediately: bool = None, + max_messages: int = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pubsub.PullResponse: + r"""Pulls messages from the server. The server may return + ``UNAVAILABLE`` if there are too many concurrent pull requests + pending for the given subscription. + + Args: + request (google.pubsub_v1.types.PullRequest): + The request object. Request for the `Pull` method. + subscription (str): + Required. The subscription from which messages should be + pulled. Format is + ``projects/{project}/subscriptions/{sub}``. + + This corresponds to the ``subscription`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + return_immediately (bool): + Optional. If this field set to true, the system will + respond immediately even if it there are no messages + available to return in the ``Pull`` response. Otherwise, + the system may wait (for a bounded amount of time) until + at least one message is available, rather than returning + no messages. Warning: setting this field to ``true`` is + discouraged because it adversely impacts the performance + of ``Pull`` operations. We recommend that users do not + set this field. + + This corresponds to the ``return_immediately`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + max_messages (int): + Required. The maximum number of + messages to return for this request. + Must be a positive integer. The Pub/Sub + system may return fewer than the number + specified. + + This corresponds to the ``max_messages`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.pubsub_v1.types.PullResponse: + Response for the Pull method. + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([subscription, return_immediately, max_messages]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a pubsub.PullRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, pubsub.PullRequest): + request = pubsub.PullRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if subscription is not None: + request.subscription = subscription + if return_immediately is not None: + request.return_immediately = return_immediately + if max_messages is not None: + request.max_messages = max_messages + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.pull] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('subscription', request.subscription), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def streaming_pull(self, + requests: Iterator[pubsub.StreamingPullRequest] = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> Iterable[pubsub.StreamingPullResponse]: + r"""Establishes a stream with the server, which sends messages down + to the client. The client streams acknowledgements and ack + deadline modifications back to the server. The server will close + the stream and return the status on any error. The server may + close the stream with status ``UNAVAILABLE`` to reassign + server-side resources, in which case, the client should + re-establish the stream. Flow control can be achieved by + configuring the underlying RPC channel. + + Args: + requests (Iterator[google.pubsub_v1.types.StreamingPullRequest]): + The request object iterator. Request for the `StreamingPull` + streaming RPC method. This request is used to establish + the initial stream as well as to stream acknowledgements + and ack deadline modifications from the client to the + server. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + Iterable[google.pubsub_v1.types.StreamingPullResponse]: + Response for the StreamingPull method. This response is used to stream + messages from the server to the client. + + """ + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.streaming_pull] + + # Send the request. + response = rpc( + requests, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def modify_push_config(self, + request: pubsub.ModifyPushConfigRequest = None, + *, + subscription: str = None, + push_config: pubsub.PushConfig = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Modifies the ``PushConfig`` for a specified subscription. + + This may be used to change a push subscription to a pull one + (signified by an empty ``PushConfig``) or vice versa, or change + the endpoint URL and other attributes of a push subscription. + Messages will accumulate for delivery continuously through the + call regardless of changes to the ``PushConfig``. + + Args: + request (google.pubsub_v1.types.ModifyPushConfigRequest): + The request object. Request for the ModifyPushConfig + method. + subscription (str): + Required. The name of the subscription. Format is + ``projects/{project}/subscriptions/{sub}``. + + This corresponds to the ``subscription`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + push_config (google.pubsub_v1.types.PushConfig): + Required. The push configuration for future deliveries. + + An empty ``pushConfig`` indicates that the Pub/Sub + system should stop pushing messages from the given + subscription and allow messages to be pulled and + acknowledged - effectively pausing the subscription if + ``Pull`` or ``StreamingPull`` is not called. + + This corresponds to the ``push_config`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([subscription, push_config]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a pubsub.ModifyPushConfigRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, pubsub.ModifyPushConfigRequest): + request = pubsub.ModifyPushConfigRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if subscription is not None: + request.subscription = subscription + if push_config is not None: + request.push_config = push_config + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.modify_push_config] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('subscription', request.subscription), + )), + ) + + # Send the request. + rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + def get_snapshot(self, + request: pubsub.GetSnapshotRequest = None, + *, + snapshot: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pubsub.Snapshot: + r"""Gets the configuration details of a snapshot. + Snapshots are used in Seek operations, which allow you to manage + message acknowledgments in bulk. That is, you can set + the acknowledgment state of messages in an existing + subscription to the state captured by a snapshot. + + Args: + request (google.pubsub_v1.types.GetSnapshotRequest): + The request object. Request for the GetSnapshot method. + snapshot (str): + Required. The name of the snapshot to get. Format is + ``projects/{project}/snapshots/{snap}``. + + This corresponds to the ``snapshot`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.pubsub_v1.types.Snapshot: + A snapshot resource. Snapshots are used in + [Seek](https://cloud.google.com/pubsub/docs/replay-overview) + operations, which allow you to manage message + acknowledgments in bulk. That is, you can set the + acknowledgment state of messages in an existing + subscription to the state captured by a snapshot. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([snapshot]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a pubsub.GetSnapshotRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, pubsub.GetSnapshotRequest): + request = pubsub.GetSnapshotRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if snapshot is not None: + request.snapshot = snapshot + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_snapshot] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('snapshot', request.snapshot), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_snapshots(self, + request: pubsub.ListSnapshotsRequest = None, + *, + project: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListSnapshotsPager: + r"""Lists the existing snapshots. Snapshots are used in + `Seek `__ + operations, which allow you to manage message acknowledgments in + bulk. That is, you can set the acknowledgment state of messages + in an existing subscription to the state captured by a snapshot. + + Args: + request (google.pubsub_v1.types.ListSnapshotsRequest): + The request object. Request for the `ListSnapshots` + method. + project (str): + Required. The name of the project in which to list + snapshots. Format is ``projects/{project-id}``. + + This corresponds to the ``project`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.pubsub_v1.services.subscriber.pagers.ListSnapshotsPager: + Response for the ListSnapshots method. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([project]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a pubsub.ListSnapshotsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, pubsub.ListSnapshotsRequest): + request = pubsub.ListSnapshotsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if project is not None: + request.project = project + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_snapshots] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('project', request.project), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListSnapshotsPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def create_snapshot(self, + request: pubsub.CreateSnapshotRequest = None, + *, + name: str = None, + subscription: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pubsub.Snapshot: + r"""Creates a snapshot from the requested subscription. Snapshots + are used in + `Seek `__ + operations, which allow you to manage message acknowledgments in + bulk. That is, you can set the acknowledgment state of messages + in an existing subscription to the state captured by a snapshot. + If the snapshot already exists, returns ``ALREADY_EXISTS``. If + the requested subscription doesn't exist, returns ``NOT_FOUND``. + If the backlog in the subscription is too old -- and the + resulting snapshot would expire in less than 1 hour -- then + ``FAILED_PRECONDITION`` is returned. See also the + ``Snapshot.expire_time`` field. If the name is not provided in + the request, the server will assign a random name for this + snapshot on the same project as the subscription, conforming to + the [resource name format] + (https://cloud.google.com/pubsub/docs/admin#resource_names). The + generated name is populated in the returned Snapshot object. + Note that for REST API requests, you must specify a name in the + request. + + Args: + request (google.pubsub_v1.types.CreateSnapshotRequest): + The request object. Request for the `CreateSnapshot` + method. + name (str): + Required. User-provided name for this snapshot. If the + name is not provided in the request, the server will + assign a random name for this snapshot on the same + project as the subscription. Note that for REST API + requests, you must specify a name. See the resource name + rules. Format is + ``projects/{project}/snapshots/{snap}``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + subscription (str): + Required. The subscription whose backlog the snapshot + retains. Specifically, the created snapshot is + guaranteed to retain: (a) The existing backlog on the + subscription. More precisely, this is defined as the + messages in the subscription's backlog that are + unacknowledged upon the successful completion of the + ``CreateSnapshot`` request; as well as: (b) Any messages + published to the subscription's topic following the + successful completion of the CreateSnapshot request. + Format is ``projects/{project}/subscriptions/{sub}``. + + This corresponds to the ``subscription`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.pubsub_v1.types.Snapshot: + A snapshot resource. Snapshots are used in + [Seek](https://cloud.google.com/pubsub/docs/replay-overview) + operations, which allow you to manage message + acknowledgments in bulk. That is, you can set the + acknowledgment state of messages in an existing + subscription to the state captured by a snapshot. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name, subscription]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a pubsub.CreateSnapshotRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, pubsub.CreateSnapshotRequest): + request = pubsub.CreateSnapshotRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if name is not None: + request.name = name + if subscription is not None: + request.subscription = subscription + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_snapshot] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('name', request.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def update_snapshot(self, + request: pubsub.UpdateSnapshotRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pubsub.Snapshot: + r"""Updates an existing snapshot. Snapshots are used in + Seek operations, which allow + you to manage message acknowledgments in bulk. That is, + you can set the acknowledgment state of messages in an + existing subscription to the state captured by a + snapshot. + + Args: + 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. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.pubsub_v1.types.Snapshot: + A snapshot resource. Snapshots are used in + [Seek](https://cloud.google.com/pubsub/docs/replay-overview) + operations, which allow you to manage message + acknowledgments in bulk. That is, you can set the + acknowledgment state of messages in an existing + subscription to the state captured by a snapshot. + + """ + # Create or coerce a protobuf request object. + + # Minor optimization to avoid making a copy if the user passes + # in a pubsub.UpdateSnapshotRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, pubsub.UpdateSnapshotRequest): + request = pubsub.UpdateSnapshotRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update_snapshot] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('snapshot.name', request.snapshot.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def delete_snapshot(self, + request: pubsub.DeleteSnapshotRequest = None, + *, + snapshot: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Removes an existing snapshot. Snapshots are used in [Seek] + (https://cloud.google.com/pubsub/docs/replay-overview) + operations, which allow you to manage message acknowledgments in + bulk. That is, you can set the acknowledgment state of messages + in an existing subscription to the state captured by a snapshot. + When the snapshot is deleted, all messages retained in the + snapshot are immediately dropped. After a snapshot is deleted, a + new one may be created with the same name, but the new one has + no association with the old snapshot or its subscription, unless + the same subscription is specified. + + Args: + request (google.pubsub_v1.types.DeleteSnapshotRequest): + The request object. Request for the `DeleteSnapshot` + method. + snapshot (str): + Required. The name of the snapshot to delete. Format is + ``projects/{project}/snapshots/{snap}``. + + This corresponds to the ``snapshot`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([snapshot]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a pubsub.DeleteSnapshotRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, pubsub.DeleteSnapshotRequest): + request = pubsub.DeleteSnapshotRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if snapshot is not None: + request.snapshot = snapshot + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.delete_snapshot] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('snapshot', request.snapshot), + )), + ) + + # Send the request. + rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + def seek(self, + request: pubsub.SeekRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pubsub.SeekResponse: + r"""Seeks an existing subscription to a point in time or to a given + snapshot, whichever is provided in the request. Snapshots are + used in [Seek] + (https://cloud.google.com/pubsub/docs/replay-overview) + operations, which allow you to manage message acknowledgments in + bulk. That is, you can set the acknowledgment state of messages + in an existing subscription to the state captured by a snapshot. + Note that both the subscription and the snapshot must be on the + same topic. + + 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. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.pubsub_v1.types.SeekResponse: + Response for the Seek method (this response is empty). + """ + # Create or coerce a protobuf request object. + + # Minor optimization to avoid making a copy if the user passes + # in a pubsub.SeekRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, pubsub.SeekRequest): + request = pubsub.SeekRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.seek] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('subscription', request.subscription), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def set_iam_policy( + self, + request: iam_policy.SetIamPolicyRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> policy.Policy: + r"""Sets the IAM access control policy on the specified + function. Replaces any existing policy. + Args: + request (:class:`~.iam_policy.SetIamPolicyRequest`): + The request object. Request message for `SetIamPolicy` + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.policy.Policy: + Defines an Identity and Access Management (IAM) policy. + It is used to specify access control policies for Cloud + Platform resources. + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members`` to a single + ``role``. Members can be user accounts, service + accounts, Google groups, and domains (such as G Suite). + A ``role`` is a named list of permissions (defined by + IAM or configured by users). A ``binding`` can + optionally specify a ``condition``, which is a logic + expression that further constrains the role binding + based on attributes about the request and/or target + resource. + **JSON Example** + :: + { + "bindings": [ + { + "role": "roles/resourcemanager.organizationAdmin", + "members": [ + "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + }, + { + "role": "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { + "title": "expirable access", + "description": "Does not grant access after Sep 2020", + "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", + } + } + ] + } + **YAML Example** + :: + bindings: + - members: + - user:mike@example.com + - group:admins@example.com + - domain:google.com + - serviceAccount:my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin + - members: + - user:eve@example.com + role: roles/resourcemanager.organizationViewer + condition: + title: expirable access + description: Does not grant access after Sep 2020 + expression: request.time < timestamp('2020-10-01T00:00:00.000Z') + For a description of IAM and its features, see the `IAM + developer's + guide `__. + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = iam_policy.SetIamPolicyRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.set_iam_policy, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("resource", request.resource),)), + ) + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def get_iam_policy( + self, + request: iam_policy.GetIamPolicyRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> policy.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`): + The request object. Request message for `GetIamPolicy` + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.policy.Policy: + Defines an Identity and Access Management (IAM) policy. + It is used to specify access control policies for Cloud + Platform resources. + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members`` to a single + ``role``. Members can be user accounts, service + accounts, Google groups, and domains (such as G Suite). + A ``role`` is a named list of permissions (defined by + IAM or configured by users). A ``binding`` can + optionally specify a ``condition``, which is a logic + expression that further constrains the role binding + based on attributes about the request and/or target + resource. + **JSON Example** + :: + { + "bindings": [ + { + "role": "roles/resourcemanager.organizationAdmin", + "members": [ + "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + }, + { + "role": "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { + "title": "expirable access", + "description": "Does not grant access after Sep 2020", + "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", + } + } + ] + } + **YAML Example** + :: + bindings: + - members: + - user:mike@example.com + - group:admins@example.com + - domain:google.com + - serviceAccount:my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin + - members: + - user:eve@example.com + role: roles/resourcemanager.organizationViewer + condition: + title: expirable access + description: Does not grant access after Sep 2020 + expression: request.time < timestamp('2020-10-01T00:00:00.000Z') + For a description of IAM and its features, see the `IAM + developer's + guide `__. + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = iam_policy.GetIamPolicyRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.get_iam_policy, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("resource", request.resource),)), + ) + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def test_iam_permissions( + self, + request: iam_policy.TestIamPermissionsRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> iam_policy.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`): + The request object. Request message for + `TestIamPermissions` method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.iam_policy.TestIamPermissionsResponse: + Response message for ``TestIamPermissions`` method. + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = iam_policy.TestIamPermissionsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.test_iam_permissions, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("resource", request.resource),)), + ) + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + 'google-pubsub', + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + 'SubscriberClient', +) diff --git a/owl-bot-staging/v1/google/pubsub_v1/services/subscriber/pagers.py b/owl-bot-staging/v1/google/pubsub_v1/services/subscriber/pagers.py new file mode 100644 index 000000000..feaf40169 --- /dev/null +++ b/owl-bot-staging/v1/google/pubsub_v1/services/subscriber/pagers.py @@ -0,0 +1,264 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from typing import Any, AsyncIterable, Awaitable, Callable, Iterable, Sequence, Tuple, Optional + +from google.pubsub_v1.types import pubsub + + +class ListSubscriptionsPager: + """A pager for iterating through ``list_subscriptions`` requests. + + This class thinly wraps an initial + :class:`google.pubsub_v1.types.ListSubscriptionsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``subscriptions`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListSubscriptions`` requests and continue to iterate + through the ``subscriptions`` field on the + corresponding responses. + + All the usual :class:`google.pubsub_v1.types.ListSubscriptionsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + def __init__(self, + method: Callable[..., pubsub.ListSubscriptionsResponse], + request: pubsub.ListSubscriptionsRequest, + response: pubsub.ListSubscriptionsResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.pubsub_v1.types.ListSubscriptionsRequest): + The initial request object. + response (google.pubsub_v1.types.ListSubscriptionsResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = pubsub.ListSubscriptionsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterable[pubsub.ListSubscriptionsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterable[pubsub.Subscription]: + for page in self.pages: + yield from page.subscriptions + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListSubscriptionsAsyncPager: + """A pager for iterating through ``list_subscriptions`` requests. + + This class thinly wraps an initial + :class:`google.pubsub_v1.types.ListSubscriptionsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``subscriptions`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListSubscriptions`` requests and continue to iterate + through the ``subscriptions`` field on the + corresponding responses. + + All the usual :class:`google.pubsub_v1.types.ListSubscriptionsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + def __init__(self, + method: Callable[..., Awaitable[pubsub.ListSubscriptionsResponse]], + request: pubsub.ListSubscriptionsRequest, + response: pubsub.ListSubscriptionsResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.pubsub_v1.types.ListSubscriptionsRequest): + The initial request object. + response (google.pubsub_v1.types.ListSubscriptionsResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = pubsub.ListSubscriptionsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterable[pubsub.ListSubscriptionsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method(self._request, metadata=self._metadata) + yield self._response + + def __aiter__(self) -> AsyncIterable[pubsub.Subscription]: + async def async_generator(): + async for page in self.pages: + for response in page.subscriptions: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListSnapshotsPager: + """A pager for iterating through ``list_snapshots`` requests. + + This class thinly wraps an initial + :class:`google.pubsub_v1.types.ListSnapshotsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``snapshots`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListSnapshots`` requests and continue to iterate + through the ``snapshots`` field on the + corresponding responses. + + All the usual :class:`google.pubsub_v1.types.ListSnapshotsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + def __init__(self, + method: Callable[..., pubsub.ListSnapshotsResponse], + request: pubsub.ListSnapshotsRequest, + response: pubsub.ListSnapshotsResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.pubsub_v1.types.ListSnapshotsRequest): + The initial request object. + response (google.pubsub_v1.types.ListSnapshotsResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = pubsub.ListSnapshotsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterable[pubsub.ListSnapshotsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterable[pubsub.Snapshot]: + for page in self.pages: + yield from page.snapshots + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListSnapshotsAsyncPager: + """A pager for iterating through ``list_snapshots`` requests. + + This class thinly wraps an initial + :class:`google.pubsub_v1.types.ListSnapshotsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``snapshots`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListSnapshots`` requests and continue to iterate + through the ``snapshots`` field on the + corresponding responses. + + All the usual :class:`google.pubsub_v1.types.ListSnapshotsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + def __init__(self, + method: Callable[..., Awaitable[pubsub.ListSnapshotsResponse]], + request: pubsub.ListSnapshotsRequest, + response: pubsub.ListSnapshotsResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.pubsub_v1.types.ListSnapshotsRequest): + The initial request object. + response (google.pubsub_v1.types.ListSnapshotsResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = pubsub.ListSnapshotsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterable[pubsub.ListSnapshotsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method(self._request, metadata=self._metadata) + yield self._response + + def __aiter__(self) -> AsyncIterable[pubsub.Snapshot]: + async def async_generator(): + async for page in self.pages: + for response in page.snapshots: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) diff --git a/owl-bot-staging/v1/google/pubsub_v1/services/subscriber/transports/__init__.py b/owl-bot-staging/v1/google/pubsub_v1/services/subscriber/transports/__init__.py new file mode 100644 index 000000000..45b2d01e4 --- /dev/null +++ b/owl-bot-staging/v1/google/pubsub_v1/services/subscriber/transports/__init__.py @@ -0,0 +1,35 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from collections import OrderedDict +from typing import Dict, Type + +from .base import SubscriberTransport +from .grpc import SubscriberGrpcTransport +from .grpc_asyncio import SubscriberGrpcAsyncIOTransport + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[SubscriberTransport]] +_transport_registry['grpc'] = SubscriberGrpcTransport +_transport_registry['grpc_asyncio'] = SubscriberGrpcAsyncIOTransport + +__all__ = ( + 'SubscriberTransport', + 'SubscriberGrpcTransport', + 'SubscriberGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v1/google/pubsub_v1/services/subscriber/transports/base.py b/owl-bot-staging/v1/google/pubsub_v1/services/subscriber/transports/base.py new file mode 100644 index 000000000..ad9d8f37c --- /dev/null +++ b/owl-bot-staging/v1/google/pubsub_v1/services/subscriber/transports/base.py @@ -0,0 +1,533 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +import abc +import typing +import pkg_resources + +from google import auth # 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 +from google.auth import 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.pubsub_v1.types import pubsub + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + 'google-pubsub', + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + +class SubscriberTransport(abc.ABC): + """Abstract transport class for Subscriber.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/pubsub', + ) + + 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, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + 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): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + """ + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ':' not in host: + host += ':443' + self._host = host + + # 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("'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 + ) + + elif credentials is None: + credentials, _ = auth.default(scopes=self._scopes, quota_project_id=quota_project_id) + + # Save the credentials. + self._credentials = credentials + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.create_subscription: gapic_v1.method.wrap_method( + self.create_subscription, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.Aborted, + exceptions.ServiceUnavailable, + exceptions.Unknown, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.get_subscription: gapic_v1.method.wrap_method( + self.get_subscription, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.Aborted, + exceptions.ServiceUnavailable, + exceptions.Unknown, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.update_subscription: gapic_v1.method.wrap_method( + self.update_subscription, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.list_subscriptions: gapic_v1.method.wrap_method( + self.list_subscriptions, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.Aborted, + exceptions.ServiceUnavailable, + exceptions.Unknown, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.delete_subscription: gapic_v1.method.wrap_method( + self.delete_subscription, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.modify_ack_deadline: gapic_v1.method.wrap_method( + self.modify_ack_deadline, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.acknowledge: gapic_v1.method.wrap_method( + self.acknowledge, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.pull: gapic_v1.method.wrap_method( + self.pull, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.Aborted, + exceptions.ServiceUnavailable, + exceptions.Unknown, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.streaming_pull: gapic_v1.method.wrap_method( + self.streaming_pull, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.Aborted, + exceptions.DeadlineExceeded, + exceptions.InternalServerError, + exceptions.ResourceExhausted, + exceptions.ServiceUnavailable, + ), + deadline=900.0, + ), + default_timeout=900.0, + client_info=client_info, + ), + self.modify_push_config: gapic_v1.method.wrap_method( + self.modify_push_config, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.get_snapshot: gapic_v1.method.wrap_method( + self.get_snapshot, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.Aborted, + exceptions.ServiceUnavailable, + exceptions.Unknown, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.list_snapshots: gapic_v1.method.wrap_method( + self.list_snapshots, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.Aborted, + exceptions.ServiceUnavailable, + exceptions.Unknown, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.create_snapshot: gapic_v1.method.wrap_method( + self.create_snapshot, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.update_snapshot: gapic_v1.method.wrap_method( + self.update_snapshot, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.delete_snapshot: gapic_v1.method.wrap_method( + self.delete_snapshot, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.seek: gapic_v1.method.wrap_method( + self.seek, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.Aborted, + exceptions.ServiceUnavailable, + exceptions.Unknown, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + + } + + @property + def create_subscription(self) -> typing.Callable[ + [pubsub.Subscription], + typing.Union[ + pubsub.Subscription, + typing.Awaitable[pubsub.Subscription] + ]]: + raise NotImplementedError() + + @property + def get_subscription(self) -> typing.Callable[ + [pubsub.GetSubscriptionRequest], + typing.Union[ + pubsub.Subscription, + typing.Awaitable[pubsub.Subscription] + ]]: + raise NotImplementedError() + + @property + def update_subscription(self) -> typing.Callable[ + [pubsub.UpdateSubscriptionRequest], + typing.Union[ + pubsub.Subscription, + typing.Awaitable[pubsub.Subscription] + ]]: + raise NotImplementedError() + + @property + def list_subscriptions(self) -> typing.Callable[ + [pubsub.ListSubscriptionsRequest], + typing.Union[ + pubsub.ListSubscriptionsResponse, + typing.Awaitable[pubsub.ListSubscriptionsResponse] + ]]: + raise NotImplementedError() + + @property + def delete_subscription(self) -> typing.Callable[ + [pubsub.DeleteSubscriptionRequest], + typing.Union[ + empty.Empty, + typing.Awaitable[empty.Empty] + ]]: + raise NotImplementedError() + + @property + def modify_ack_deadline(self) -> typing.Callable[ + [pubsub.ModifyAckDeadlineRequest], + typing.Union[ + empty.Empty, + typing.Awaitable[empty.Empty] + ]]: + raise NotImplementedError() + + @property + def acknowledge(self) -> typing.Callable[ + [pubsub.AcknowledgeRequest], + typing.Union[ + empty.Empty, + typing.Awaitable[empty.Empty] + ]]: + raise NotImplementedError() + + @property + def pull(self) -> typing.Callable[ + [pubsub.PullRequest], + typing.Union[ + pubsub.PullResponse, + typing.Awaitable[pubsub.PullResponse] + ]]: + raise NotImplementedError() + + @property + def streaming_pull(self) -> typing.Callable[ + [pubsub.StreamingPullRequest], + typing.Union[ + pubsub.StreamingPullResponse, + typing.Awaitable[pubsub.StreamingPullResponse] + ]]: + raise NotImplementedError() + + @property + def modify_push_config(self) -> typing.Callable[ + [pubsub.ModifyPushConfigRequest], + typing.Union[ + empty.Empty, + typing.Awaitable[empty.Empty] + ]]: + raise NotImplementedError() + + @property + def get_snapshot(self) -> typing.Callable[ + [pubsub.GetSnapshotRequest], + typing.Union[ + pubsub.Snapshot, + typing.Awaitable[pubsub.Snapshot] + ]]: + raise NotImplementedError() + + @property + def list_snapshots(self) -> typing.Callable[ + [pubsub.ListSnapshotsRequest], + typing.Union[ + pubsub.ListSnapshotsResponse, + typing.Awaitable[pubsub.ListSnapshotsResponse] + ]]: + raise NotImplementedError() + + @property + def create_snapshot(self) -> typing.Callable[ + [pubsub.CreateSnapshotRequest], + typing.Union[ + pubsub.Snapshot, + typing.Awaitable[pubsub.Snapshot] + ]]: + raise NotImplementedError() + + @property + def update_snapshot(self) -> typing.Callable[ + [pubsub.UpdateSnapshotRequest], + typing.Union[ + pubsub.Snapshot, + typing.Awaitable[pubsub.Snapshot] + ]]: + raise NotImplementedError() + + @property + def delete_snapshot(self) -> typing.Callable[ + [pubsub.DeleteSnapshotRequest], + typing.Union[ + empty.Empty, + typing.Awaitable[empty.Empty] + ]]: + raise NotImplementedError() + + @property + def seek(self) -> typing.Callable[ + [pubsub.SeekRequest], + typing.Union[ + pubsub.SeekResponse, + typing.Awaitable[pubsub.SeekResponse] + ]]: + raise NotImplementedError() + + @property + def set_iam_policy( + self, + ) -> typing.Callable[ + [iam_policy.SetIamPolicyRequest], + typing.Union[policy.Policy, typing.Awaitable[policy.Policy]], + ]: + raise NotImplementedError() + + @property + def get_iam_policy( + self, + ) -> typing.Callable[ + [iam_policy.GetIamPolicyRequest], + typing.Union[policy.Policy, typing.Awaitable[policy.Policy]], + ]: + raise NotImplementedError() + + @property + def test_iam_permissions( + self, + ) -> typing.Callable[ + [iam_policy.TestIamPermissionsRequest], + typing.Union[ + iam_policy.TestIamPermissionsResponse, + typing.Awaitable[iam_policy.TestIamPermissionsResponse], + ], + ]: + raise NotImplementedError() + + +__all__ = ( + 'SubscriberTransport', +) diff --git a/owl-bot-staging/v1/google/pubsub_v1/services/subscriber/transports/grpc.py b/owl-bot-staging/v1/google/pubsub_v1/services/subscriber/transports/grpc.py new file mode 100644 index 000000000..c91bd85ab --- /dev/null +++ b/owl-bot-staging/v1/google/pubsub_v1/services/subscriber/transports/grpc.py @@ -0,0 +1,820 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple + +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 +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.pubsub_v1.types import pubsub + +from .base import SubscriberTransport, DEFAULT_CLIENT_INFO + + +class SubscriberGrpcTransport(SubscriberTransport): + """gRPC backend transport for Subscriber. + + The service that an application uses to manipulate subscriptions and + to consume messages from a subscription via the ``Pull`` method or + by establishing a bi-directional stream using the ``StreamingPull`` + method. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + _stubs: Dict[str, Callable] + + def __init__(self, *, + host: str = 'pubsub.googleapis.com', + credentials: credentials.Credentials = None, + credentials_file: str = None, + scopes: Sequence[str] = None, + channel: grpc.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + channel (Optional[grpc.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or applicatin default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + credentials=self._credentials, + credentials_file=credentials_file, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel(cls, + host: str = 'pubsub.googleapis.com', + credentials: credentials.Credentials = None, + credentials_file: str = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> grpc.Channel: + """Create and return a gRPC channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + grpc.Channel: A gRPC channel object. + + Raises: + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + 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, + **kwargs + ) + + @property + def grpc_channel(self) -> grpc.Channel: + """Return the channel designed to connect to this service. + """ + return self._grpc_channel + + @property + def create_subscription(self) -> Callable[ + [pubsub.Subscription], + pubsub.Subscription]: + r"""Return a callable for the create subscription method over gRPC. + + Creates a subscription to a given topic. See the [resource name + rules] + (https://cloud.google.com/pubsub/docs/admin#resource_names). If + the subscription already exists, returns ``ALREADY_EXISTS``. If + the corresponding topic doesn't exist, returns ``NOT_FOUND``. + + If the name is not provided in the request, the server will + assign a random name for this subscription on the same project + as the topic, conforming to the [resource name format] + (https://cloud.google.com/pubsub/docs/admin#resource_names). The + generated name is populated in the returned Subscription object. + Note that for REST API requests, you must specify a name in the + request. + + Returns: + Callable[[~.Subscription], + ~.Subscription]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'create_subscription' not in self._stubs: + self._stubs['create_subscription'] = self.grpc_channel.unary_unary( + '/google.pubsub.v1.Subscriber/CreateSubscription', + request_serializer=pubsub.Subscription.serialize, + response_deserializer=pubsub.Subscription.deserialize, + ) + return self._stubs['create_subscription'] + + @property + def get_subscription(self) -> Callable[ + [pubsub.GetSubscriptionRequest], + pubsub.Subscription]: + r"""Return a callable for the get subscription method over gRPC. + + Gets the configuration details of a subscription. + + Returns: + Callable[[~.GetSubscriptionRequest], + ~.Subscription]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_subscription' not in self._stubs: + self._stubs['get_subscription'] = self.grpc_channel.unary_unary( + '/google.pubsub.v1.Subscriber/GetSubscription', + request_serializer=pubsub.GetSubscriptionRequest.serialize, + response_deserializer=pubsub.Subscription.deserialize, + ) + return self._stubs['get_subscription'] + + @property + def update_subscription(self) -> Callable[ + [pubsub.UpdateSubscriptionRequest], + pubsub.Subscription]: + r"""Return a callable for the update subscription method over gRPC. + + Updates an existing subscription. Note that certain + properties of a subscription, such as its topic, are not + modifiable. + + Returns: + Callable[[~.UpdateSubscriptionRequest], + ~.Subscription]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'update_subscription' not in self._stubs: + self._stubs['update_subscription'] = self.grpc_channel.unary_unary( + '/google.pubsub.v1.Subscriber/UpdateSubscription', + request_serializer=pubsub.UpdateSubscriptionRequest.serialize, + response_deserializer=pubsub.Subscription.deserialize, + ) + return self._stubs['update_subscription'] + + @property + def list_subscriptions(self) -> Callable[ + [pubsub.ListSubscriptionsRequest], + pubsub.ListSubscriptionsResponse]: + r"""Return a callable for the list subscriptions method over gRPC. + + Lists matching subscriptions. + + Returns: + Callable[[~.ListSubscriptionsRequest], + ~.ListSubscriptionsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'list_subscriptions' not in self._stubs: + self._stubs['list_subscriptions'] = self.grpc_channel.unary_unary( + '/google.pubsub.v1.Subscriber/ListSubscriptions', + request_serializer=pubsub.ListSubscriptionsRequest.serialize, + response_deserializer=pubsub.ListSubscriptionsResponse.deserialize, + ) + return self._stubs['list_subscriptions'] + + @property + def delete_subscription(self) -> Callable[ + [pubsub.DeleteSubscriptionRequest], + empty.Empty]: + r"""Return a callable for the delete subscription method over gRPC. + + Deletes an existing subscription. All messages retained in the + subscription are immediately dropped. Calls to ``Pull`` after + deletion will return ``NOT_FOUND``. After a subscription is + deleted, a new one may be created with the same name, but the + new one has no association with the old subscription or its + topic unless the same topic is specified. + + Returns: + Callable[[~.DeleteSubscriptionRequest], + ~.Empty]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'delete_subscription' not in self._stubs: + self._stubs['delete_subscription'] = self.grpc_channel.unary_unary( + '/google.pubsub.v1.Subscriber/DeleteSubscription', + request_serializer=pubsub.DeleteSubscriptionRequest.serialize, + response_deserializer=empty.Empty.FromString, + ) + return self._stubs['delete_subscription'] + + @property + def modify_ack_deadline(self) -> Callable[ + [pubsub.ModifyAckDeadlineRequest], + empty.Empty]: + r"""Return a callable for the modify ack deadline method over gRPC. + + Modifies the ack deadline for a specific message. This method is + useful to indicate that more time is needed to process a message + by the subscriber, or to make the message available for + redelivery if the processing was interrupted. Note that this + does not modify the subscription-level ``ackDeadlineSeconds`` + used for subsequent messages. + + Returns: + Callable[[~.ModifyAckDeadlineRequest], + ~.Empty]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'modify_ack_deadline' not in self._stubs: + self._stubs['modify_ack_deadline'] = self.grpc_channel.unary_unary( + '/google.pubsub.v1.Subscriber/ModifyAckDeadline', + request_serializer=pubsub.ModifyAckDeadlineRequest.serialize, + response_deserializer=empty.Empty.FromString, + ) + return self._stubs['modify_ack_deadline'] + + @property + def acknowledge(self) -> Callable[ + [pubsub.AcknowledgeRequest], + empty.Empty]: + r"""Return a callable for the acknowledge method over gRPC. + + Acknowledges the messages associated with the ``ack_ids`` in the + ``AcknowledgeRequest``. The Pub/Sub system can remove the + relevant messages from the subscription. + + Acknowledging a message whose ack deadline has expired may + succeed, but such a message may be redelivered later. + Acknowledging a message more than once will not result in an + error. + + Returns: + Callable[[~.AcknowledgeRequest], + ~.Empty]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'acknowledge' not in self._stubs: + self._stubs['acknowledge'] = self.grpc_channel.unary_unary( + '/google.pubsub.v1.Subscriber/Acknowledge', + request_serializer=pubsub.AcknowledgeRequest.serialize, + response_deserializer=empty.Empty.FromString, + ) + return self._stubs['acknowledge'] + + @property + def pull(self) -> Callable[ + [pubsub.PullRequest], + pubsub.PullResponse]: + r"""Return a callable for the pull method over gRPC. + + Pulls messages from the server. The server may return + ``UNAVAILABLE`` if there are too many concurrent pull requests + pending for the given subscription. + + Returns: + Callable[[~.PullRequest], + ~.PullResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'pull' not in self._stubs: + self._stubs['pull'] = self.grpc_channel.unary_unary( + '/google.pubsub.v1.Subscriber/Pull', + request_serializer=pubsub.PullRequest.serialize, + response_deserializer=pubsub.PullResponse.deserialize, + ) + return self._stubs['pull'] + + @property + def streaming_pull(self) -> Callable[ + [pubsub.StreamingPullRequest], + pubsub.StreamingPullResponse]: + r"""Return a callable for the streaming pull method over gRPC. + + Establishes a stream with the server, which sends messages down + to the client. The client streams acknowledgements and ack + deadline modifications back to the server. The server will close + the stream and return the status on any error. The server may + close the stream with status ``UNAVAILABLE`` to reassign + server-side resources, in which case, the client should + re-establish the stream. Flow control can be achieved by + configuring the underlying RPC channel. + + Returns: + Callable[[~.StreamingPullRequest], + ~.StreamingPullResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'streaming_pull' not in self._stubs: + self._stubs['streaming_pull'] = self.grpc_channel.stream_stream( + '/google.pubsub.v1.Subscriber/StreamingPull', + request_serializer=pubsub.StreamingPullRequest.serialize, + response_deserializer=pubsub.StreamingPullResponse.deserialize, + ) + return self._stubs['streaming_pull'] + + @property + def modify_push_config(self) -> Callable[ + [pubsub.ModifyPushConfigRequest], + empty.Empty]: + r"""Return a callable for the modify push config method over gRPC. + + Modifies the ``PushConfig`` for a specified subscription. + + This may be used to change a push subscription to a pull one + (signified by an empty ``PushConfig``) or vice versa, or change + the endpoint URL and other attributes of a push subscription. + Messages will accumulate for delivery continuously through the + call regardless of changes to the ``PushConfig``. + + Returns: + Callable[[~.ModifyPushConfigRequest], + ~.Empty]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'modify_push_config' not in self._stubs: + self._stubs['modify_push_config'] = self.grpc_channel.unary_unary( + '/google.pubsub.v1.Subscriber/ModifyPushConfig', + request_serializer=pubsub.ModifyPushConfigRequest.serialize, + response_deserializer=empty.Empty.FromString, + ) + return self._stubs['modify_push_config'] + + @property + def get_snapshot(self) -> Callable[ + [pubsub.GetSnapshotRequest], + pubsub.Snapshot]: + r"""Return a callable for the get snapshot method over gRPC. + + Gets the configuration details of a snapshot. + Snapshots are used in Seek operations, which allow you to manage + message acknowledgments in bulk. That is, you can set + the acknowledgment state of messages in an existing + subscription to the state captured by a snapshot. + + Returns: + Callable[[~.GetSnapshotRequest], + ~.Snapshot]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_snapshot' not in self._stubs: + self._stubs['get_snapshot'] = self.grpc_channel.unary_unary( + '/google.pubsub.v1.Subscriber/GetSnapshot', + request_serializer=pubsub.GetSnapshotRequest.serialize, + response_deserializer=pubsub.Snapshot.deserialize, + ) + return self._stubs['get_snapshot'] + + @property + def list_snapshots(self) -> Callable[ + [pubsub.ListSnapshotsRequest], + pubsub.ListSnapshotsResponse]: + r"""Return a callable for the list snapshots method over gRPC. + + Lists the existing snapshots. Snapshots are used in + `Seek `__ + operations, which allow you to manage message acknowledgments in + bulk. That is, you can set the acknowledgment state of messages + in an existing subscription to the state captured by a snapshot. + + Returns: + Callable[[~.ListSnapshotsRequest], + ~.ListSnapshotsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'list_snapshots' not in self._stubs: + self._stubs['list_snapshots'] = self.grpc_channel.unary_unary( + '/google.pubsub.v1.Subscriber/ListSnapshots', + request_serializer=pubsub.ListSnapshotsRequest.serialize, + response_deserializer=pubsub.ListSnapshotsResponse.deserialize, + ) + return self._stubs['list_snapshots'] + + @property + def create_snapshot(self) -> Callable[ + [pubsub.CreateSnapshotRequest], + pubsub.Snapshot]: + r"""Return a callable for the create snapshot method over gRPC. + + Creates a snapshot from the requested subscription. Snapshots + are used in + `Seek `__ + operations, which allow you to manage message acknowledgments in + bulk. That is, you can set the acknowledgment state of messages + in an existing subscription to the state captured by a snapshot. + If the snapshot already exists, returns ``ALREADY_EXISTS``. If + the requested subscription doesn't exist, returns ``NOT_FOUND``. + If the backlog in the subscription is too old -- and the + resulting snapshot would expire in less than 1 hour -- then + ``FAILED_PRECONDITION`` is returned. See also the + ``Snapshot.expire_time`` field. If the name is not provided in + the request, the server will assign a random name for this + snapshot on the same project as the subscription, conforming to + the [resource name format] + (https://cloud.google.com/pubsub/docs/admin#resource_names). The + generated name is populated in the returned Snapshot object. + Note that for REST API requests, you must specify a name in the + request. + + Returns: + Callable[[~.CreateSnapshotRequest], + ~.Snapshot]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'create_snapshot' not in self._stubs: + self._stubs['create_snapshot'] = self.grpc_channel.unary_unary( + '/google.pubsub.v1.Subscriber/CreateSnapshot', + request_serializer=pubsub.CreateSnapshotRequest.serialize, + response_deserializer=pubsub.Snapshot.deserialize, + ) + return self._stubs['create_snapshot'] + + @property + def update_snapshot(self) -> Callable[ + [pubsub.UpdateSnapshotRequest], + pubsub.Snapshot]: + r"""Return a callable for the update snapshot method over gRPC. + + Updates an existing snapshot. Snapshots are used in + Seek operations, which allow + you to manage message acknowledgments in bulk. That is, + you can set the acknowledgment state of messages in an + existing subscription to the state captured by a + snapshot. + + Returns: + Callable[[~.UpdateSnapshotRequest], + ~.Snapshot]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'update_snapshot' not in self._stubs: + self._stubs['update_snapshot'] = self.grpc_channel.unary_unary( + '/google.pubsub.v1.Subscriber/UpdateSnapshot', + request_serializer=pubsub.UpdateSnapshotRequest.serialize, + response_deserializer=pubsub.Snapshot.deserialize, + ) + return self._stubs['update_snapshot'] + + @property + def delete_snapshot(self) -> Callable[ + [pubsub.DeleteSnapshotRequest], + empty.Empty]: + r"""Return a callable for the delete snapshot method over gRPC. + + Removes an existing snapshot. Snapshots are used in [Seek] + (https://cloud.google.com/pubsub/docs/replay-overview) + operations, which allow you to manage message acknowledgments in + bulk. That is, you can set the acknowledgment state of messages + in an existing subscription to the state captured by a snapshot. + When the snapshot is deleted, all messages retained in the + snapshot are immediately dropped. After a snapshot is deleted, a + new one may be created with the same name, but the new one has + no association with the old snapshot or its subscription, unless + the same subscription is specified. + + Returns: + Callable[[~.DeleteSnapshotRequest], + ~.Empty]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'delete_snapshot' not in self._stubs: + self._stubs['delete_snapshot'] = self.grpc_channel.unary_unary( + '/google.pubsub.v1.Subscriber/DeleteSnapshot', + request_serializer=pubsub.DeleteSnapshotRequest.serialize, + response_deserializer=empty.Empty.FromString, + ) + return self._stubs['delete_snapshot'] + + @property + def seek(self) -> Callable[ + [pubsub.SeekRequest], + pubsub.SeekResponse]: + r"""Return a callable for the seek method over gRPC. + + Seeks an existing subscription to a point in time or to a given + snapshot, whichever is provided in the request. Snapshots are + used in [Seek] + (https://cloud.google.com/pubsub/docs/replay-overview) + operations, which allow you to manage message acknowledgments in + bulk. That is, you can set the acknowledgment state of messages + in an existing subscription to the state captured by a snapshot. + Note that both the subscription and the snapshot must be on the + same topic. + + Returns: + Callable[[~.SeekRequest], + ~.SeekResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'seek' not in self._stubs: + self._stubs['seek'] = self.grpc_channel.unary_unary( + '/google.pubsub.v1.Subscriber/Seek', + request_serializer=pubsub.SeekRequest.serialize, + response_deserializer=pubsub.SeekResponse.deserialize, + ) + return self._stubs['seek'] + + @property + def set_iam_policy( + self, + ) -> Callable[[iam_policy.SetIamPolicyRequest], policy.Policy]: + r"""Return a callable for the set iam policy method over gRPC. + Sets the IAM access control policy on the specified + function. Replaces any existing policy. + Returns: + Callable[[~.SetIamPolicyRequest], + ~.Policy]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "set_iam_policy" not in self._stubs: + self._stubs["set_iam_policy"] = self.grpc_channel.unary_unary( + "/google.iam.v1.IAMPolicy/SetIamPolicy", + request_serializer=iam_policy.SetIamPolicyRequest.SerializeToString, + response_deserializer=policy.Policy.FromString, + ) + return self._stubs["set_iam_policy"] + + @property + def get_iam_policy( + self, + ) -> Callable[[iam_policy.GetIamPolicyRequest], policy.Policy]: + r"""Return a callable for the get iam policy method over gRPC. + Gets the IAM access control policy for a function. + Returns an empty policy if the function exists and does + not have a policy set. + Returns: + Callable[[~.GetIamPolicyRequest], + ~.Policy]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_iam_policy" not in self._stubs: + self._stubs["get_iam_policy"] = self.grpc_channel.unary_unary( + "/google.iam.v1.IAMPolicy/GetIamPolicy", + request_serializer=iam_policy.GetIamPolicyRequest.SerializeToString, + response_deserializer=policy.Policy.FromString, + ) + return self._stubs["get_iam_policy"] + + @property + def test_iam_permissions( + self, + ) -> Callable[ + [iam_policy.TestIamPermissionsRequest], iam_policy.TestIamPermissionsResponse + ]: + r"""Return a callable for the test iam permissions method over gRPC. + Tests the specified permissions against the IAM access control + policy for a function. If the function does not exist, this will + return an empty set of permissions, not a NOT_FOUND error. + Returns: + Callable[[~.TestIamPermissionsRequest], + ~.TestIamPermissionsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "test_iam_permissions" not in self._stubs: + self._stubs["test_iam_permissions"] = self.grpc_channel.unary_unary( + "/google.iam.v1.IAMPolicy/TestIamPermissions", + request_serializer=iam_policy.TestIamPermissionsRequest.SerializeToString, + response_deserializer=iam_policy.TestIamPermissionsResponse.FromString, + ) + return self._stubs["test_iam_permissions"] + + +__all__ = ( + 'SubscriberGrpcTransport', +) diff --git a/owl-bot-staging/v1/google/pubsub_v1/services/subscriber/transports/grpc_asyncio.py b/owl-bot-staging/v1/google/pubsub_v1/services/subscriber/transports/grpc_asyncio.py new file mode 100644 index 000000000..174d9d93d --- /dev/null +++ b/owl-bot-staging/v1/google/pubsub_v1/services/subscriber/transports/grpc_asyncio.py @@ -0,0 +1,826 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple + +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 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.pubsub_v1.types import pubsub + +from .base import SubscriberTransport, DEFAULT_CLIENT_INFO +from .grpc import SubscriberGrpcTransport + + +class SubscriberGrpcAsyncIOTransport(SubscriberTransport): + """gRPC AsyncIO backend transport for Subscriber. + + The service that an application uses to manipulate subscriptions and + to consume messages from a subscription via the ``Pull`` method or + by establishing a bi-directional stream using the ``StreamingPull`` + method. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + + _grpc_channel: aio.Channel + _stubs: Dict[str, Callable] = {} + + @classmethod + def create_channel(cls, + host: str = 'pubsub.googleapis.com', + credentials: credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + 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, + **kwargs + ) + + def __init__(self, *, + host: str = 'pubsub.googleapis.com', + credentials: credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: aio.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id=None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[aio.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or applicatin default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + credentials=self._credentials, + credentials_file=credentials_file, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def create_subscription(self) -> Callable[ + [pubsub.Subscription], + Awaitable[pubsub.Subscription]]: + r"""Return a callable for the create subscription method over gRPC. + + Creates a subscription to a given topic. See the [resource name + rules] + (https://cloud.google.com/pubsub/docs/admin#resource_names). If + the subscription already exists, returns ``ALREADY_EXISTS``. If + the corresponding topic doesn't exist, returns ``NOT_FOUND``. + + If the name is not provided in the request, the server will + assign a random name for this subscription on the same project + as the topic, conforming to the [resource name format] + (https://cloud.google.com/pubsub/docs/admin#resource_names). The + generated name is populated in the returned Subscription object. + Note that for REST API requests, you must specify a name in the + request. + + Returns: + Callable[[~.Subscription], + Awaitable[~.Subscription]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'create_subscription' not in self._stubs: + self._stubs['create_subscription'] = self.grpc_channel.unary_unary( + '/google.pubsub.v1.Subscriber/CreateSubscription', + request_serializer=pubsub.Subscription.serialize, + response_deserializer=pubsub.Subscription.deserialize, + ) + return self._stubs['create_subscription'] + + @property + def get_subscription(self) -> Callable[ + [pubsub.GetSubscriptionRequest], + Awaitable[pubsub.Subscription]]: + r"""Return a callable for the get subscription method over gRPC. + + Gets the configuration details of a subscription. + + Returns: + Callable[[~.GetSubscriptionRequest], + Awaitable[~.Subscription]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_subscription' not in self._stubs: + self._stubs['get_subscription'] = self.grpc_channel.unary_unary( + '/google.pubsub.v1.Subscriber/GetSubscription', + request_serializer=pubsub.GetSubscriptionRequest.serialize, + response_deserializer=pubsub.Subscription.deserialize, + ) + return self._stubs['get_subscription'] + + @property + def update_subscription(self) -> Callable[ + [pubsub.UpdateSubscriptionRequest], + Awaitable[pubsub.Subscription]]: + r"""Return a callable for the update subscription method over gRPC. + + Updates an existing subscription. Note that certain + properties of a subscription, such as its topic, are not + modifiable. + + Returns: + Callable[[~.UpdateSubscriptionRequest], + Awaitable[~.Subscription]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'update_subscription' not in self._stubs: + self._stubs['update_subscription'] = self.grpc_channel.unary_unary( + '/google.pubsub.v1.Subscriber/UpdateSubscription', + request_serializer=pubsub.UpdateSubscriptionRequest.serialize, + response_deserializer=pubsub.Subscription.deserialize, + ) + return self._stubs['update_subscription'] + + @property + def list_subscriptions(self) -> Callable[ + [pubsub.ListSubscriptionsRequest], + Awaitable[pubsub.ListSubscriptionsResponse]]: + r"""Return a callable for the list subscriptions method over gRPC. + + Lists matching subscriptions. + + Returns: + Callable[[~.ListSubscriptionsRequest], + Awaitable[~.ListSubscriptionsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'list_subscriptions' not in self._stubs: + self._stubs['list_subscriptions'] = self.grpc_channel.unary_unary( + '/google.pubsub.v1.Subscriber/ListSubscriptions', + request_serializer=pubsub.ListSubscriptionsRequest.serialize, + response_deserializer=pubsub.ListSubscriptionsResponse.deserialize, + ) + return self._stubs['list_subscriptions'] + + @property + def delete_subscription(self) -> Callable[ + [pubsub.DeleteSubscriptionRequest], + Awaitable[empty.Empty]]: + r"""Return a callable for the delete subscription method over gRPC. + + Deletes an existing subscription. All messages retained in the + subscription are immediately dropped. Calls to ``Pull`` after + deletion will return ``NOT_FOUND``. After a subscription is + deleted, a new one may be created with the same name, but the + new one has no association with the old subscription or its + topic unless the same topic is specified. + + Returns: + Callable[[~.DeleteSubscriptionRequest], + Awaitable[~.Empty]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'delete_subscription' not in self._stubs: + self._stubs['delete_subscription'] = self.grpc_channel.unary_unary( + '/google.pubsub.v1.Subscriber/DeleteSubscription', + request_serializer=pubsub.DeleteSubscriptionRequest.serialize, + response_deserializer=empty.Empty.FromString, + ) + return self._stubs['delete_subscription'] + + @property + def modify_ack_deadline(self) -> Callable[ + [pubsub.ModifyAckDeadlineRequest], + Awaitable[empty.Empty]]: + r"""Return a callable for the modify ack deadline method over gRPC. + + Modifies the ack deadline for a specific message. This method is + useful to indicate that more time is needed to process a message + by the subscriber, or to make the message available for + redelivery if the processing was interrupted. Note that this + does not modify the subscription-level ``ackDeadlineSeconds`` + used for subsequent messages. + + Returns: + Callable[[~.ModifyAckDeadlineRequest], + Awaitable[~.Empty]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'modify_ack_deadline' not in self._stubs: + self._stubs['modify_ack_deadline'] = self.grpc_channel.unary_unary( + '/google.pubsub.v1.Subscriber/ModifyAckDeadline', + request_serializer=pubsub.ModifyAckDeadlineRequest.serialize, + response_deserializer=empty.Empty.FromString, + ) + return self._stubs['modify_ack_deadline'] + + @property + def acknowledge(self) -> Callable[ + [pubsub.AcknowledgeRequest], + Awaitable[empty.Empty]]: + r"""Return a callable for the acknowledge method over gRPC. + + Acknowledges the messages associated with the ``ack_ids`` in the + ``AcknowledgeRequest``. The Pub/Sub system can remove the + relevant messages from the subscription. + + Acknowledging a message whose ack deadline has expired may + succeed, but such a message may be redelivered later. + Acknowledging a message more than once will not result in an + error. + + Returns: + Callable[[~.AcknowledgeRequest], + Awaitable[~.Empty]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'acknowledge' not in self._stubs: + self._stubs['acknowledge'] = self.grpc_channel.unary_unary( + '/google.pubsub.v1.Subscriber/Acknowledge', + request_serializer=pubsub.AcknowledgeRequest.serialize, + response_deserializer=empty.Empty.FromString, + ) + return self._stubs['acknowledge'] + + @property + def pull(self) -> Callable[ + [pubsub.PullRequest], + Awaitable[pubsub.PullResponse]]: + r"""Return a callable for the pull method over gRPC. + + Pulls messages from the server. The server may return + ``UNAVAILABLE`` if there are too many concurrent pull requests + pending for the given subscription. + + Returns: + Callable[[~.PullRequest], + Awaitable[~.PullResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'pull' not in self._stubs: + self._stubs['pull'] = self.grpc_channel.unary_unary( + '/google.pubsub.v1.Subscriber/Pull', + request_serializer=pubsub.PullRequest.serialize, + response_deserializer=pubsub.PullResponse.deserialize, + ) + return self._stubs['pull'] + + @property + def streaming_pull(self) -> Callable[ + [pubsub.StreamingPullRequest], + Awaitable[pubsub.StreamingPullResponse]]: + r"""Return a callable for the streaming pull method over gRPC. + + Establishes a stream with the server, which sends messages down + to the client. The client streams acknowledgements and ack + deadline modifications back to the server. The server will close + the stream and return the status on any error. The server may + close the stream with status ``UNAVAILABLE`` to reassign + server-side resources, in which case, the client should + re-establish the stream. Flow control can be achieved by + configuring the underlying RPC channel. + + Returns: + Callable[[~.StreamingPullRequest], + Awaitable[~.StreamingPullResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'streaming_pull' not in self._stubs: + self._stubs['streaming_pull'] = self.grpc_channel.stream_stream( + '/google.pubsub.v1.Subscriber/StreamingPull', + request_serializer=pubsub.StreamingPullRequest.serialize, + response_deserializer=pubsub.StreamingPullResponse.deserialize, + ) + return self._stubs['streaming_pull'] + + @property + def modify_push_config(self) -> Callable[ + [pubsub.ModifyPushConfigRequest], + Awaitable[empty.Empty]]: + r"""Return a callable for the modify push config method over gRPC. + + Modifies the ``PushConfig`` for a specified subscription. + + This may be used to change a push subscription to a pull one + (signified by an empty ``PushConfig``) or vice versa, or change + the endpoint URL and other attributes of a push subscription. + Messages will accumulate for delivery continuously through the + call regardless of changes to the ``PushConfig``. + + Returns: + Callable[[~.ModifyPushConfigRequest], + Awaitable[~.Empty]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'modify_push_config' not in self._stubs: + self._stubs['modify_push_config'] = self.grpc_channel.unary_unary( + '/google.pubsub.v1.Subscriber/ModifyPushConfig', + request_serializer=pubsub.ModifyPushConfigRequest.serialize, + response_deserializer=empty.Empty.FromString, + ) + return self._stubs['modify_push_config'] + + @property + def get_snapshot(self) -> Callable[ + [pubsub.GetSnapshotRequest], + Awaitable[pubsub.Snapshot]]: + r"""Return a callable for the get snapshot method over gRPC. + + Gets the configuration details of a snapshot. + Snapshots are used in Seek operations, which allow you to manage + message acknowledgments in bulk. That is, you can set + the acknowledgment state of messages in an existing + subscription to the state captured by a snapshot. + + Returns: + Callable[[~.GetSnapshotRequest], + Awaitable[~.Snapshot]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_snapshot' not in self._stubs: + self._stubs['get_snapshot'] = self.grpc_channel.unary_unary( + '/google.pubsub.v1.Subscriber/GetSnapshot', + request_serializer=pubsub.GetSnapshotRequest.serialize, + response_deserializer=pubsub.Snapshot.deserialize, + ) + return self._stubs['get_snapshot'] + + @property + def list_snapshots(self) -> Callable[ + [pubsub.ListSnapshotsRequest], + Awaitable[pubsub.ListSnapshotsResponse]]: + r"""Return a callable for the list snapshots method over gRPC. + + Lists the existing snapshots. Snapshots are used in + `Seek `__ + operations, which allow you to manage message acknowledgments in + bulk. That is, you can set the acknowledgment state of messages + in an existing subscription to the state captured by a snapshot. + + Returns: + Callable[[~.ListSnapshotsRequest], + Awaitable[~.ListSnapshotsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'list_snapshots' not in self._stubs: + self._stubs['list_snapshots'] = self.grpc_channel.unary_unary( + '/google.pubsub.v1.Subscriber/ListSnapshots', + request_serializer=pubsub.ListSnapshotsRequest.serialize, + response_deserializer=pubsub.ListSnapshotsResponse.deserialize, + ) + return self._stubs['list_snapshots'] + + @property + def create_snapshot(self) -> Callable[ + [pubsub.CreateSnapshotRequest], + Awaitable[pubsub.Snapshot]]: + r"""Return a callable for the create snapshot method over gRPC. + + Creates a snapshot from the requested subscription. Snapshots + are used in + `Seek `__ + operations, which allow you to manage message acknowledgments in + bulk. That is, you can set the acknowledgment state of messages + in an existing subscription to the state captured by a snapshot. + If the snapshot already exists, returns ``ALREADY_EXISTS``. If + the requested subscription doesn't exist, returns ``NOT_FOUND``. + If the backlog in the subscription is too old -- and the + resulting snapshot would expire in less than 1 hour -- then + ``FAILED_PRECONDITION`` is returned. See also the + ``Snapshot.expire_time`` field. If the name is not provided in + the request, the server will assign a random name for this + snapshot on the same project as the subscription, conforming to + the [resource name format] + (https://cloud.google.com/pubsub/docs/admin#resource_names). The + generated name is populated in the returned Snapshot object. + Note that for REST API requests, you must specify a name in the + request. + + Returns: + Callable[[~.CreateSnapshotRequest], + Awaitable[~.Snapshot]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'create_snapshot' not in self._stubs: + self._stubs['create_snapshot'] = self.grpc_channel.unary_unary( + '/google.pubsub.v1.Subscriber/CreateSnapshot', + request_serializer=pubsub.CreateSnapshotRequest.serialize, + response_deserializer=pubsub.Snapshot.deserialize, + ) + return self._stubs['create_snapshot'] + + @property + def update_snapshot(self) -> Callable[ + [pubsub.UpdateSnapshotRequest], + Awaitable[pubsub.Snapshot]]: + r"""Return a callable for the update snapshot method over gRPC. + + Updates an existing snapshot. Snapshots are used in + Seek operations, which allow + you to manage message acknowledgments in bulk. That is, + you can set the acknowledgment state of messages in an + existing subscription to the state captured by a + snapshot. + + Returns: + Callable[[~.UpdateSnapshotRequest], + Awaitable[~.Snapshot]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'update_snapshot' not in self._stubs: + self._stubs['update_snapshot'] = self.grpc_channel.unary_unary( + '/google.pubsub.v1.Subscriber/UpdateSnapshot', + request_serializer=pubsub.UpdateSnapshotRequest.serialize, + response_deserializer=pubsub.Snapshot.deserialize, + ) + return self._stubs['update_snapshot'] + + @property + def delete_snapshot(self) -> Callable[ + [pubsub.DeleteSnapshotRequest], + Awaitable[empty.Empty]]: + r"""Return a callable for the delete snapshot method over gRPC. + + Removes an existing snapshot. Snapshots are used in [Seek] + (https://cloud.google.com/pubsub/docs/replay-overview) + operations, which allow you to manage message acknowledgments in + bulk. That is, you can set the acknowledgment state of messages + in an existing subscription to the state captured by a snapshot. + When the snapshot is deleted, all messages retained in the + snapshot are immediately dropped. After a snapshot is deleted, a + new one may be created with the same name, but the new one has + no association with the old snapshot or its subscription, unless + the same subscription is specified. + + Returns: + Callable[[~.DeleteSnapshotRequest], + Awaitable[~.Empty]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'delete_snapshot' not in self._stubs: + self._stubs['delete_snapshot'] = self.grpc_channel.unary_unary( + '/google.pubsub.v1.Subscriber/DeleteSnapshot', + request_serializer=pubsub.DeleteSnapshotRequest.serialize, + response_deserializer=empty.Empty.FromString, + ) + return self._stubs['delete_snapshot'] + + @property + def seek(self) -> Callable[ + [pubsub.SeekRequest], + Awaitable[pubsub.SeekResponse]]: + r"""Return a callable for the seek method over gRPC. + + Seeks an existing subscription to a point in time or to a given + snapshot, whichever is provided in the request. Snapshots are + used in [Seek] + (https://cloud.google.com/pubsub/docs/replay-overview) + operations, which allow you to manage message acknowledgments in + bulk. That is, you can set the acknowledgment state of messages + in an existing subscription to the state captured by a snapshot. + Note that both the subscription and the snapshot must be on the + same topic. + + Returns: + Callable[[~.SeekRequest], + Awaitable[~.SeekResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'seek' not in self._stubs: + self._stubs['seek'] = self.grpc_channel.unary_unary( + '/google.pubsub.v1.Subscriber/Seek', + request_serializer=pubsub.SeekRequest.serialize, + response_deserializer=pubsub.SeekResponse.deserialize, + ) + return self._stubs['seek'] + + @property + def set_iam_policy( + self, + ) -> Callable[[iam_policy.SetIamPolicyRequest], Awaitable[policy.Policy]]: + r"""Return a callable for the set iam policy method over gRPC. + Sets the IAM access control policy on the specified + function. Replaces any existing policy. + Returns: + Callable[[~.SetIamPolicyRequest], + Awaitable[~.Policy]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "set_iam_policy" not in self._stubs: + self._stubs["set_iam_policy"] = self.grpc_channel.unary_unary( + "/google.iam.v1.IAMPolicy/SetIamPolicy", + request_serializer=iam_policy.SetIamPolicyRequest.SerializeToString, + response_deserializer=policy.Policy.FromString, + ) + return self._stubs["set_iam_policy"] + + @property + def get_iam_policy( + self, + ) -> Callable[[iam_policy.GetIamPolicyRequest], Awaitable[policy.Policy]]: + r"""Return a callable for the get iam policy method over gRPC. + Gets the IAM access control policy for a function. + Returns an empty policy if the function exists and does + not have a policy set. + Returns: + Callable[[~.GetIamPolicyRequest], + Awaitable[~.Policy]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_iam_policy" not in self._stubs: + self._stubs["get_iam_policy"] = self.grpc_channel.unary_unary( + "/google.iam.v1.IAMPolicy/GetIamPolicy", + request_serializer=iam_policy.GetIamPolicyRequest.SerializeToString, + response_deserializer=policy.Policy.FromString, + ) + return self._stubs["get_iam_policy"] + + @property + def test_iam_permissions( + self, + ) -> Callable[ + [iam_policy.TestIamPermissionsRequest], + Awaitable[iam_policy.TestIamPermissionsResponse], + ]: + r"""Return a callable for the test iam permissions method over gRPC. + Tests the specified permissions against the IAM access control + policy for a function. If the function does not exist, this will + return an empty set of permissions, not a NOT_FOUND error. + Returns: + Callable[[~.TestIamPermissionsRequest], + Awaitable[~.TestIamPermissionsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "test_iam_permissions" not in self._stubs: + self._stubs["test_iam_permissions"] = self.grpc_channel.unary_unary( + "/google.iam.v1.IAMPolicy/TestIamPermissions", + request_serializer=iam_policy.TestIamPermissionsRequest.SerializeToString, + response_deserializer=iam_policy.TestIamPermissionsResponse.FromString, + ) + return self._stubs["test_iam_permissions"] + + +__all__ = ( + 'SubscriberGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v1/google/pubsub_v1/types/__init__.py b/owl-bot-staging/v1/google/pubsub_v1/types/__init__.py new file mode 100644 index 000000000..2e91f37fa --- /dev/null +++ b/owl-bot-staging/v1/google/pubsub_v1/types/__init__.py @@ -0,0 +1,136 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from .pubsub import ( + AcknowledgeRequest, + CreateSnapshotRequest, + DeadLetterPolicy, + DeleteSnapshotRequest, + DeleteSubscriptionRequest, + DeleteTopicRequest, + DetachSubscriptionRequest, + DetachSubscriptionResponse, + ExpirationPolicy, + GetSnapshotRequest, + GetSubscriptionRequest, + GetTopicRequest, + ListSnapshotsRequest, + ListSnapshotsResponse, + ListSubscriptionsRequest, + ListSubscriptionsResponse, + ListTopicSnapshotsRequest, + ListTopicSnapshotsResponse, + ListTopicsRequest, + ListTopicsResponse, + ListTopicSubscriptionsRequest, + ListTopicSubscriptionsResponse, + MessageStoragePolicy, + ModifyAckDeadlineRequest, + ModifyPushConfigRequest, + PublishRequest, + PublishResponse, + PubsubMessage, + PullRequest, + PullResponse, + PushConfig, + ReceivedMessage, + RetryPolicy, + SchemaSettings, + SeekRequest, + SeekResponse, + Snapshot, + StreamingPullRequest, + StreamingPullResponse, + Subscription, + Topic, + UpdateSnapshotRequest, + UpdateSubscriptionRequest, + UpdateTopicRequest, +) +from .schema import ( + CreateSchemaRequest, + DeleteSchemaRequest, + GetSchemaRequest, + ListSchemasRequest, + ListSchemasResponse, + Schema, + ValidateMessageRequest, + ValidateMessageResponse, + ValidateSchemaRequest, + ValidateSchemaResponse, + Encoding, + SchemaView, +) + +__all__ = ( + 'AcknowledgeRequest', + 'CreateSnapshotRequest', + 'DeadLetterPolicy', + 'DeleteSnapshotRequest', + 'DeleteSubscriptionRequest', + 'DeleteTopicRequest', + 'DetachSubscriptionRequest', + 'DetachSubscriptionResponse', + 'ExpirationPolicy', + 'GetSnapshotRequest', + 'GetSubscriptionRequest', + 'GetTopicRequest', + 'ListSnapshotsRequest', + 'ListSnapshotsResponse', + 'ListSubscriptionsRequest', + 'ListSubscriptionsResponse', + 'ListTopicSnapshotsRequest', + 'ListTopicSnapshotsResponse', + 'ListTopicsRequest', + 'ListTopicsResponse', + 'ListTopicSubscriptionsRequest', + 'ListTopicSubscriptionsResponse', + 'MessageStoragePolicy', + 'ModifyAckDeadlineRequest', + 'ModifyPushConfigRequest', + 'PublishRequest', + 'PublishResponse', + 'PubsubMessage', + 'PullRequest', + 'PullResponse', + 'PushConfig', + 'ReceivedMessage', + 'RetryPolicy', + 'SchemaSettings', + 'SeekRequest', + 'SeekResponse', + 'Snapshot', + 'StreamingPullRequest', + 'StreamingPullResponse', + 'Subscription', + 'Topic', + 'UpdateSnapshotRequest', + 'UpdateSubscriptionRequest', + 'UpdateTopicRequest', + 'CreateSchemaRequest', + 'DeleteSchemaRequest', + 'GetSchemaRequest', + 'ListSchemasRequest', + 'ListSchemasResponse', + 'Schema', + 'ValidateMessageRequest', + 'ValidateMessageResponse', + 'ValidateSchemaRequest', + 'ValidateSchemaResponse', + 'Encoding', + 'SchemaView', +) diff --git a/owl-bot-staging/v1/google/pubsub_v1/types/pubsub.py b/owl-bot-staging/v1/google/pubsub_v1/types/pubsub.py new file mode 100644 index 000000000..eb7f3f83a --- /dev/null +++ b/owl-bot-staging/v1/google/pubsub_v1/types/pubsub.py @@ -0,0 +1,1372 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +import proto # type: ignore + + +from google.protobuf import duration_pb2 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.pubsub_v1.types import schema as gp_schema + + +__protobuf__ = proto.module( + package='google.pubsub.v1', + manifest={ + 'MessageStoragePolicy', + 'SchemaSettings', + 'Topic', + 'PubsubMessage', + 'GetTopicRequest', + 'UpdateTopicRequest', + 'PublishRequest', + 'PublishResponse', + 'ListTopicsRequest', + 'ListTopicsResponse', + 'ListTopicSubscriptionsRequest', + 'ListTopicSubscriptionsResponse', + 'ListTopicSnapshotsRequest', + 'ListTopicSnapshotsResponse', + 'DeleteTopicRequest', + 'DetachSubscriptionRequest', + 'DetachSubscriptionResponse', + 'Subscription', + 'RetryPolicy', + 'DeadLetterPolicy', + 'ExpirationPolicy', + 'PushConfig', + 'ReceivedMessage', + 'GetSubscriptionRequest', + 'UpdateSubscriptionRequest', + 'ListSubscriptionsRequest', + 'ListSubscriptionsResponse', + 'DeleteSubscriptionRequest', + 'ModifyPushConfigRequest', + 'PullRequest', + 'PullResponse', + 'ModifyAckDeadlineRequest', + 'AcknowledgeRequest', + 'StreamingPullRequest', + 'StreamingPullResponse', + 'CreateSnapshotRequest', + 'UpdateSnapshotRequest', + 'Snapshot', + 'GetSnapshotRequest', + 'ListSnapshotsRequest', + 'ListSnapshotsResponse', + 'DeleteSnapshotRequest', + 'SeekRequest', + 'SeekResponse', + }, +) + + +class MessageStoragePolicy(proto.Message): + r"""A policy constraining the storage of messages published to + the topic. + + Attributes: + allowed_persistence_regions (Sequence[str]): + A list of IDs of GCP regions where messages + that are published to the topic may be persisted + in storage. Messages published by publishers + running in non-allowed GCP regions (or running + outside of GCP altogether) will be routed for + storage in one of the allowed regions. An empty + list means that no regions are allowed, and is + not a valid configuration. + """ + + allowed_persistence_regions = proto.RepeatedField(proto.STRING, number=1) + + +class SchemaSettings(proto.Message): + r"""Settings for validating messages published against a schema. + + Attributes: + schema (str): + Required. The name of the schema that messages published + should be validated against. Format is + ``projects/{project}/schemas/{schema}``. The value of this + field will be ``_deleted-schema_`` if the schema has been + deleted. + encoding (google.pubsub_v1.types.Encoding): + The encoding of messages validated against ``schema``. + """ + + schema = proto.Field(proto.STRING, number=1) + + encoding = proto.Field(proto.ENUM, number=2, + enum=gp_schema.Encoding, + ) + + +class Topic(proto.Message): + r"""A topic resource. + + Attributes: + name (str): + Required. The name of the topic. It must have the format + ``"projects/{project}/topics/{topic}"``. ``{topic}`` must + start with a letter, and contain only letters + (``[A-Za-z]``), numbers (``[0-9]``), dashes (``-``), + underscores (``_``), periods (``.``), tildes (``~``), plus + (``+``) or percent signs (``%``). It must be between 3 and + 255 characters in length, and it must not start with + ``"goog"``. + labels (Sequence[google.pubsub_v1.types.Topic.LabelsEntry]): + See [Creating and managing labels] + (https://cloud.google.com/pubsub/docs/labels). + message_storage_policy (google.pubsub_v1.types.MessageStoragePolicy): + Policy constraining the set of Google Cloud + Platform regions where messages published to the + topic may be stored. If not present, then no + constraints are in effect. + kms_key_name (str): + The resource name of the Cloud KMS CryptoKey to be used to + protect access to messages published on this topic. + + The expected format is + ``projects/*/locations/*/keyRings/*/cryptoKeys/*``. + schema_settings (google.pubsub_v1.types.SchemaSettings): + Settings for validating messages published + against a schema. + satisfies_pzs (bool): + Reserved for future use. This field is set + only in responses from the server; it is ignored + if it is set in any requests. + """ + + name = proto.Field(proto.STRING, number=1) + + labels = proto.MapField(proto.STRING, proto.STRING, number=2) + + message_storage_policy = proto.Field(proto.MESSAGE, number=3, + message='MessageStoragePolicy', + ) + + kms_key_name = proto.Field(proto.STRING, number=5) + + schema_settings = proto.Field(proto.MESSAGE, number=6, + message='SchemaSettings', + ) + + satisfies_pzs = proto.Field(proto.BOOL, number=7) + + +class PubsubMessage(proto.Message): + r"""A message that is published by publishers and consumed by + subscribers. The message must contain either a non-empty data field + or at least one attribute. Note that client libraries represent this + object differently depending on the language. See the corresponding + `client library + documentation `__ + for more information. See [quotas and limits] + (https://cloud.google.com/pubsub/quotas) for more information about + message limits. + + Attributes: + data (bytes): + The message data field. If this field is + empty, the message must contain at least one + attribute. + attributes (Sequence[google.pubsub_v1.types.PubsubMessage.AttributesEntry]): + Attributes for this message. If this field is + empty, the message must contain non-empty data. + This can be used to filter messages on the + subscription. + message_id (str): + ID of this message, assigned by the server when the message + is published. Guaranteed to be unique within the topic. This + value may be read by a subscriber that receives a + ``PubsubMessage`` via a ``Pull`` call or a push delivery. It + must not be populated by the publisher in a ``Publish`` + call. + publish_time (google.protobuf.timestamp_pb2.Timestamp): + The time at which the message was published, populated by + the server when it receives the ``Publish`` call. It must + not be populated by the publisher in a ``Publish`` call. + ordering_key (str): + If non-empty, identifies related messages for which publish + order should be respected. If a ``Subscription`` has + ``enable_message_ordering`` set to ``true``, messages + published with the same non-empty ``ordering_key`` value + will be delivered to subscribers in the order in which they + are received by the Pub/Sub system. All ``PubsubMessage``\ s + published in a given ``PublishRequest`` must specify the + same ``ordering_key`` value. + """ + + data = proto.Field(proto.BYTES, number=1) + + attributes = proto.MapField(proto.STRING, proto.STRING, number=2) + + message_id = proto.Field(proto.STRING, number=3) + + publish_time = proto.Field(proto.MESSAGE, number=4, + message=timestamp.Timestamp, + ) + + ordering_key = proto.Field(proto.STRING, number=5) + + +class GetTopicRequest(proto.Message): + r"""Request for the GetTopic method. + + Attributes: + topic (str): + Required. The name of the topic to get. Format is + ``projects/{project}/topics/{topic}``. + """ + + topic = proto.Field(proto.STRING, number=1) + + +class UpdateTopicRequest(proto.Message): + r"""Request for the UpdateTopic method. + + Attributes: + topic (google.pubsub_v1.types.Topic): + Required. The updated topic object. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. Indicates which fields in the provided topic to + update. Must be specified and non-empty. Note that if + ``update_mask`` contains "message_storage_policy" but the + ``message_storage_policy`` is not set in the ``topic`` + provided above, then the updated value is determined by the + policy configured at the project or organization level. + """ + + topic = proto.Field(proto.MESSAGE, number=1, + message='Topic', + ) + + update_mask = proto.Field(proto.MESSAGE, number=2, + message=field_mask.FieldMask, + ) + + +class PublishRequest(proto.Message): + r"""Request for the Publish method. + + Attributes: + topic (str): + Required. The messages in the request will be published on + this topic. Format is ``projects/{project}/topics/{topic}``. + messages (Sequence[google.pubsub_v1.types.PubsubMessage]): + Required. The messages to publish. + """ + + topic = proto.Field(proto.STRING, number=1) + + messages = proto.RepeatedField(proto.MESSAGE, number=2, + message='PubsubMessage', + ) + + +class PublishResponse(proto.Message): + r"""Response for the ``Publish`` method. + + Attributes: + message_ids (Sequence[str]): + The server-assigned ID of each published + message, in the same order as the messages in + the request. IDs are guaranteed to be unique + within the topic. + """ + + message_ids = proto.RepeatedField(proto.STRING, number=1) + + +class ListTopicsRequest(proto.Message): + r"""Request for the ``ListTopics`` method. + + Attributes: + project (str): + Required. The name of the project in which to list topics. + Format is ``projects/{project-id}``. + page_size (int): + Maximum number of topics to return. + page_token (str): + The value returned by the last ``ListTopicsResponse``; + indicates that this is a continuation of a prior + ``ListTopics`` call, and that the system should return the + next page of data. + """ + + project = proto.Field(proto.STRING, number=1) + + page_size = proto.Field(proto.INT32, number=2) + + page_token = proto.Field(proto.STRING, number=3) + + +class ListTopicsResponse(proto.Message): + r"""Response for the ``ListTopics`` method. + + Attributes: + topics (Sequence[google.pubsub_v1.types.Topic]): + The resulting topics. + next_page_token (str): + If not empty, indicates that there may be more topics that + match the request; this value should be passed in a new + ``ListTopicsRequest``. + """ + + @property + def raw_page(self): + return self + + topics = proto.RepeatedField(proto.MESSAGE, number=1, + message='Topic', + ) + + next_page_token = proto.Field(proto.STRING, number=2) + + +class ListTopicSubscriptionsRequest(proto.Message): + r"""Request for the ``ListTopicSubscriptions`` method. + + Attributes: + topic (str): + Required. The name of the topic that subscriptions are + attached to. Format is + ``projects/{project}/topics/{topic}``. + page_size (int): + Maximum number of subscription names to + return. + page_token (str): + The value returned by the last + ``ListTopicSubscriptionsResponse``; indicates that this is a + continuation of a prior ``ListTopicSubscriptions`` call, and + that the system should return the next page of data. + """ + + topic = proto.Field(proto.STRING, number=1) + + page_size = proto.Field(proto.INT32, number=2) + + page_token = proto.Field(proto.STRING, number=3) + + +class ListTopicSubscriptionsResponse(proto.Message): + r"""Response for the ``ListTopicSubscriptions`` method. + + Attributes: + subscriptions (Sequence[str]): + The names of subscriptions attached to the + topic specified in the request. + next_page_token (str): + If not empty, indicates that there may be more subscriptions + that match the request; this value should be passed in a new + ``ListTopicSubscriptionsRequest`` to get more subscriptions. + """ + + @property + def raw_page(self): + return self + + subscriptions = proto.RepeatedField(proto.STRING, number=1) + + next_page_token = proto.Field(proto.STRING, number=2) + + +class ListTopicSnapshotsRequest(proto.Message): + r"""Request for the ``ListTopicSnapshots`` method. + + Attributes: + topic (str): + Required. The name of the topic that snapshots are attached + to. Format is ``projects/{project}/topics/{topic}``. + page_size (int): + Maximum number of snapshot names to return. + page_token (str): + The value returned by the last + ``ListTopicSnapshotsResponse``; indicates that this is a + continuation of a prior ``ListTopicSnapshots`` call, and + that the system should return the next page of data. + """ + + topic = proto.Field(proto.STRING, number=1) + + page_size = proto.Field(proto.INT32, number=2) + + page_token = proto.Field(proto.STRING, number=3) + + +class ListTopicSnapshotsResponse(proto.Message): + r"""Response for the ``ListTopicSnapshots`` method. + + Attributes: + snapshots (Sequence[str]): + The names of the snapshots that match the + request. + next_page_token (str): + If not empty, indicates that there may be more snapshots + that match the request; this value should be passed in a new + ``ListTopicSnapshotsRequest`` to get more snapshots. + """ + + @property + def raw_page(self): + return self + + snapshots = proto.RepeatedField(proto.STRING, number=1) + + next_page_token = proto.Field(proto.STRING, number=2) + + +class DeleteTopicRequest(proto.Message): + r"""Request for the ``DeleteTopic`` method. + + Attributes: + topic (str): + Required. Name of the topic to delete. Format is + ``projects/{project}/topics/{topic}``. + """ + + topic = proto.Field(proto.STRING, number=1) + + +class DetachSubscriptionRequest(proto.Message): + r"""Request for the DetachSubscription method. + + Attributes: + subscription (str): + Required. The subscription to detach. Format is + ``projects/{project}/subscriptions/{subscription}``. + """ + + subscription = proto.Field(proto.STRING, number=1) + + +class DetachSubscriptionResponse(proto.Message): + r"""Response for the DetachSubscription method. + Reserved for future use. + """ + + +class Subscription(proto.Message): + r"""A subscription resource. + + Attributes: + name (str): + Required. The name of the subscription. It must have the + format + ``"projects/{project}/subscriptions/{subscription}"``. + ``{subscription}`` must start with a letter, and contain + only letters (``[A-Za-z]``), numbers (``[0-9]``), dashes + (``-``), underscores (``_``), periods (``.``), tildes + (``~``), plus (``+``) or percent signs (``%``). It must be + between 3 and 255 characters in length, and it must not + start with ``"goog"``. + topic (str): + Required. The name of the topic from which this subscription + is receiving messages. Format is + ``projects/{project}/topics/{topic}``. The value of this + field will be ``_deleted-topic_`` if the topic has been + deleted. + push_config (google.pubsub_v1.types.PushConfig): + If push delivery is used with this subscription, this field + is used to configure it. An empty ``pushConfig`` signifies + that the subscriber will pull and ack messages using API + methods. + ack_deadline_seconds (int): + The approximate amount of time (on a best-effort basis) + Pub/Sub waits for the subscriber to acknowledge receipt + before resending the message. In the interval after the + message is delivered and before it is acknowledged, it is + considered to be outstanding. During that time period, the + message will not be redelivered (on a best-effort basis). + + For pull subscriptions, this value is used as the initial + value for the ack deadline. To override this value for a + given message, call ``ModifyAckDeadline`` with the + corresponding ``ack_id`` if using non-streaming pull or send + the ``ack_id`` in a ``StreamingModifyAckDeadlineRequest`` if + using streaming pull. The minimum custom deadline you can + specify is 10 seconds. The maximum custom deadline you can + specify is 600 seconds (10 minutes). If this parameter is 0, + a default value of 10 seconds is used. + + For push delivery, this value is also used to set the + request timeout for the call to the push endpoint. + + If the subscriber never acknowledges the message, the + Pub/Sub system will eventually redeliver the message. + retain_acked_messages (bool): + Indicates whether to retain acknowledged messages. If true, + then messages are not expunged from the subscription's + backlog, even if they are acknowledged, until they fall out + of the ``message_retention_duration`` window. This must be + true if you would like to [Seek to a timestamp] + (https://cloud.google.com/pubsub/docs/replay-overview#seek_to_a_time). + message_retention_duration (google.protobuf.duration_pb2.Duration): + How long to retain unacknowledged messages in the + subscription's backlog, from the moment a message is + published. If ``retain_acked_messages`` is true, then this + also configures the retention of acknowledged messages, and + thus configures how far back in time a ``Seek`` can be done. + Defaults to 7 days. Cannot be more than 7 days or less than + 10 minutes. + labels (Sequence[google.pubsub_v1.types.Subscription.LabelsEntry]): + See + Creating and managing labels. + enable_message_ordering (bool): + If true, messages published with the same ``ordering_key`` + in ``PubsubMessage`` will be delivered to the subscribers in + the order in which they are received by the Pub/Sub system. + Otherwise, they may be delivered in any order. + expiration_policy (google.pubsub_v1.types.ExpirationPolicy): + A policy that specifies the conditions for this + subscription's expiration. A subscription is considered + active as long as any connected subscriber is successfully + consuming messages from the subscription or is issuing + operations on the subscription. If ``expiration_policy`` is + not set, a *default policy* with ``ttl`` of 31 days will be + used. The minimum allowed value for + ``expiration_policy.ttl`` is 1 day. + filter (str): + An expression written in the Pub/Sub `filter + language `__. + If non-empty, then only ``PubsubMessage``\ s whose + ``attributes`` field matches the filter are delivered on + this subscription. If empty, then no messages are filtered + out. + dead_letter_policy (google.pubsub_v1.types.DeadLetterPolicy): + A policy that specifies the conditions for dead lettering + messages in this subscription. If dead_letter_policy is not + set, dead lettering is disabled. + + The Cloud Pub/Sub service account associated with this + subscriptions's parent project (i.e., + service-{project_number}@gcp-sa-pubsub.iam.gserviceaccount.com) + must have permission to Acknowledge() messages on this + subscription. + retry_policy (google.pubsub_v1.types.RetryPolicy): + A policy that specifies how Pub/Sub retries + message delivery for this subscription. + + If not set, the default retry policy is applied. + This generally implies that messages will be + retried as soon as possible for healthy + subscribers. RetryPolicy will be triggered on + NACKs or acknowledgement deadline exceeded + events for a given message. + detached (bool): + Indicates whether the subscription is detached from its + topic. Detached subscriptions don't receive messages from + their topic and don't retain any backlog. ``Pull`` and + ``StreamingPull`` requests will return FAILED_PRECONDITION. + If the subscription is a push subscription, pushes to the + endpoint will not be made. + """ + + name = proto.Field(proto.STRING, number=1) + + topic = proto.Field(proto.STRING, number=2) + + push_config = proto.Field(proto.MESSAGE, number=4, + message='PushConfig', + ) + + ack_deadline_seconds = proto.Field(proto.INT32, number=5) + + retain_acked_messages = proto.Field(proto.BOOL, number=7) + + message_retention_duration = proto.Field(proto.MESSAGE, number=8, + message=duration.Duration, + ) + + labels = proto.MapField(proto.STRING, proto.STRING, number=9) + + enable_message_ordering = proto.Field(proto.BOOL, number=10) + + expiration_policy = proto.Field(proto.MESSAGE, number=11, + message='ExpirationPolicy', + ) + + filter = proto.Field(proto.STRING, number=12) + + dead_letter_policy = proto.Field(proto.MESSAGE, number=13, + message='DeadLetterPolicy', + ) + + retry_policy = proto.Field(proto.MESSAGE, number=14, + message='RetryPolicy', + ) + + detached = proto.Field(proto.BOOL, number=15) + + +class RetryPolicy(proto.Message): + r"""A policy that specifies how Cloud Pub/Sub retries message delivery. + + Retry delay will be exponential based on provided minimum and + maximum backoffs. https://en.wikipedia.org/wiki/Exponential_backoff. + + RetryPolicy will be triggered on NACKs or acknowledgement deadline + exceeded events for a given message. + + Retry Policy is implemented on a best effort basis. At times, the + delay between consecutive deliveries may not match the + configuration. That is, delay can be more or less than configured + backoff. + + Attributes: + minimum_backoff (google.protobuf.duration_pb2.Duration): + The minimum delay between consecutive + deliveries of a given message. Value should be + between 0 and 600 seconds. Defaults to 10 + seconds. + maximum_backoff (google.protobuf.duration_pb2.Duration): + The maximum delay between consecutive + deliveries of a given message. Value should be + between 0 and 600 seconds. Defaults to 600 + seconds. + """ + + minimum_backoff = proto.Field(proto.MESSAGE, number=1, + message=duration.Duration, + ) + + maximum_backoff = proto.Field(proto.MESSAGE, number=2, + message=duration.Duration, + ) + + +class DeadLetterPolicy(proto.Message): + r"""Dead lettering is done on a best effort basis. The same + message might be dead lettered multiple times. + + If validation on any of the fields fails at subscription + creation/updation, the create/update subscription request will + fail. + + Attributes: + dead_letter_topic (str): + The name of the topic to which dead letter messages should + be published. Format is + ``projects/{project}/topics/{topic}``.The Cloud Pub/Sub + service account associated with the enclosing subscription's + parent project (i.e., + service-{project_number}@gcp-sa-pubsub.iam.gserviceaccount.com) + must have permission to Publish() to this topic. + + The operation will fail if the topic does not exist. Users + should ensure that there is a subscription attached to this + topic since messages published to a topic with no + subscriptions are lost. + max_delivery_attempts (int): + The maximum number of delivery attempts for any message. The + value must be between 5 and 100. + + The number of delivery attempts is defined as 1 + (the sum + of number of NACKs and number of times the acknowledgement + deadline has been exceeded for the message). + + A NACK is any call to ModifyAckDeadline with a 0 deadline. + Note that client libraries may automatically extend + ack_deadlines. + + This field will be honored on a best effort basis. + + If this parameter is 0, a default value of 5 is used. + """ + + dead_letter_topic = proto.Field(proto.STRING, number=1) + + max_delivery_attempts = proto.Field(proto.INT32, number=2) + + +class ExpirationPolicy(proto.Message): + r"""A policy that specifies the conditions for resource + expiration (i.e., automatic resource deletion). + + Attributes: + ttl (google.protobuf.duration_pb2.Duration): + Specifies the "time-to-live" duration for an associated + resource. The resource expires if it is not active for a + period of ``ttl``. The definition of "activity" depends on + the type of the associated resource. The minimum and maximum + allowed values for ``ttl`` depend on the type of the + associated resource, as well. If ``ttl`` is not set, the + associated resource never expires. + """ + + ttl = proto.Field(proto.MESSAGE, number=1, + message=duration.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 + pushed. For example, a Webhook endpoint might use + ``https://example.com/push``. + attributes (Sequence[google.pubsub_v1.types.PushConfig.AttributesEntry]): + Endpoint configuration attributes that can be used to + control different aspects of the message delivery. + + The only currently supported attribute is + ``x-goog-version``, which you can use to change the format + of the pushed message. This attribute indicates the version + of the data expected by the endpoint. This controls the + shape of the pushed message (i.e., its fields and metadata). + + If not present during the ``CreateSubscription`` call, it + will default to the version of the Pub/Sub API used to make + such call. If not present in a ``ModifyPushConfig`` call, + its value will not be changed. ``GetSubscription`` calls + will always return a valid version, even if the subscription + was created without this attribute. + + The only supported values for the ``x-goog-version`` + attribute are: + + - ``v1beta1``: uses the push format defined in the v1beta1 + Pub/Sub API. + - ``v1`` or ``v1beta2``: uses the push format defined in + the v1 Pub/Sub API. + + For example: + + .. raw:: html + +
attributes { "x-goog-version": "v1" } 
+ oidc_token (google.pubsub_v1.types.PushConfig.OidcToken): + If specified, Pub/Sub will generate and attach an OIDC JWT + token as an ``Authorization`` header in the HTTP request for + every pushed message. + """ + class OidcToken(proto.Message): + r"""Contains information needed for generating an `OpenID Connect + token `__. + + Attributes: + service_account_email (str): + `Service account + email `__ + to be used for generating the OIDC token. The caller (for + CreateSubscription, UpdateSubscription, and ModifyPushConfig + RPCs) must have the iam.serviceAccounts.actAs permission for + the service account. + audience (str): + Audience to be used when generating OIDC + token. The audience claim identifies the + recipients that the JWT is intended for. The + audience value is a single case-sensitive + string. Having multiple values (array) for the + audience field is not supported. More info about + the OIDC JWT token audience here: + https://tools.ietf.org/html/rfc7519#section-4.1.3 + Note: if not specified, the Push endpoint URL + will be used. + """ + + service_account_email = proto.Field(proto.STRING, number=1) + + audience = proto.Field(proto.STRING, number=2) + + push_endpoint = proto.Field(proto.STRING, number=1) + + attributes = proto.MapField(proto.STRING, proto.STRING, number=2) + + oidc_token = proto.Field(proto.MESSAGE, number=3, oneof='authentication_method', + message=OidcToken, + ) + + +class ReceivedMessage(proto.Message): + r"""A message and its corresponding acknowledgment ID. + + Attributes: + ack_id (str): + This ID can be used to acknowledge the + received message. + message (google.pubsub_v1.types.PubsubMessage): + The message. + delivery_attempt (int): + The approximate number of times that Cloud Pub/Sub has + attempted to deliver the associated message to a subscriber. + + More precisely, this is 1 + (number of NACKs) + (number of + ack_deadline exceeds) for this message. + + A NACK is any call to ModifyAckDeadline with a 0 deadline. + An ack_deadline exceeds event is whenever a message is not + acknowledged within ack_deadline. Note that ack_deadline is + initially Subscription.ackDeadlineSeconds, but may get + extended automatically by the client library. + + Upon the first delivery of a given message, + ``delivery_attempt`` will have a value of 1. The value is + calculated at best effort and is approximate. + + If a DeadLetterPolicy is not set on the subscription, this + will be 0. + """ + + ack_id = proto.Field(proto.STRING, number=1) + + message = proto.Field(proto.MESSAGE, number=2, + message='PubsubMessage', + ) + + delivery_attempt = proto.Field(proto.INT32, number=3) + + +class GetSubscriptionRequest(proto.Message): + r"""Request for the GetSubscription method. + + Attributes: + subscription (str): + Required. The name of the subscription to get. Format is + ``projects/{project}/subscriptions/{sub}``. + """ + + subscription = proto.Field(proto.STRING, number=1) + + +class UpdateSubscriptionRequest(proto.Message): + r"""Request for the UpdateSubscription method. + + Attributes: + subscription (google.pubsub_v1.types.Subscription): + Required. The updated subscription object. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. Indicates which fields in the + provided subscription to update. Must be + specified and non-empty. + """ + + subscription = proto.Field(proto.MESSAGE, number=1, + message='Subscription', + ) + + update_mask = proto.Field(proto.MESSAGE, number=2, + message=field_mask.FieldMask, + ) + + +class ListSubscriptionsRequest(proto.Message): + r"""Request for the ``ListSubscriptions`` method. + + Attributes: + project (str): + Required. The name of the project in which to list + subscriptions. Format is ``projects/{project-id}``. + page_size (int): + Maximum number of subscriptions to return. + page_token (str): + The value returned by the last + ``ListSubscriptionsResponse``; indicates that this is a + continuation of a prior ``ListSubscriptions`` call, and that + the system should return the next page of data. + """ + + project = proto.Field(proto.STRING, number=1) + + page_size = proto.Field(proto.INT32, number=2) + + page_token = proto.Field(proto.STRING, number=3) + + +class ListSubscriptionsResponse(proto.Message): + r"""Response for the ``ListSubscriptions`` method. + + Attributes: + subscriptions (Sequence[google.pubsub_v1.types.Subscription]): + The subscriptions that match the request. + next_page_token (str): + If not empty, indicates that there may be more subscriptions + that match the request; this value should be passed in a new + ``ListSubscriptionsRequest`` to get more subscriptions. + """ + + @property + def raw_page(self): + return self + + subscriptions = proto.RepeatedField(proto.MESSAGE, number=1, + message='Subscription', + ) + + next_page_token = proto.Field(proto.STRING, number=2) + + +class DeleteSubscriptionRequest(proto.Message): + r"""Request for the DeleteSubscription method. + + Attributes: + subscription (str): + Required. The subscription to delete. Format is + ``projects/{project}/subscriptions/{sub}``. + """ + + subscription = proto.Field(proto.STRING, number=1) + + +class ModifyPushConfigRequest(proto.Message): + r"""Request for the ModifyPushConfig method. + + Attributes: + subscription (str): + Required. The name of the subscription. Format is + ``projects/{project}/subscriptions/{sub}``. + push_config (google.pubsub_v1.types.PushConfig): + Required. The push configuration for future deliveries. + + An empty ``pushConfig`` indicates that the Pub/Sub system + should stop pushing messages from the given subscription and + allow messages to be pulled and acknowledged - effectively + pausing the subscription if ``Pull`` or ``StreamingPull`` is + not called. + """ + + subscription = proto.Field(proto.STRING, number=1) + + push_config = proto.Field(proto.MESSAGE, number=2, + message='PushConfig', + ) + + +class PullRequest(proto.Message): + r"""Request for the ``Pull`` method. + + Attributes: + subscription (str): + Required. The subscription from which messages should be + pulled. Format is + ``projects/{project}/subscriptions/{sub}``. + return_immediately (bool): + Optional. If this field set to true, the system will respond + immediately even if it there are no messages available to + return in the ``Pull`` response. Otherwise, the system may + wait (for a bounded amount of time) until at least one + message is available, rather than returning no messages. + Warning: setting this field to ``true`` is discouraged + because it adversely impacts the performance of ``Pull`` + operations. We recommend that users do not set this field. + max_messages (int): + Required. The maximum number of messages to + return for this request. Must be a positive + integer. The Pub/Sub system may return fewer + than the number specified. + """ + + subscription = proto.Field(proto.STRING, number=1) + + return_immediately = proto.Field(proto.BOOL, number=2) + + max_messages = proto.Field(proto.INT32, number=3) + + +class PullResponse(proto.Message): + r"""Response for the ``Pull`` method. + + Attributes: + received_messages (Sequence[google.pubsub_v1.types.ReceivedMessage]): + Received Pub/Sub messages. The list will be empty if there + are no more messages available in the backlog. For JSON, the + response can be entirely empty. The Pub/Sub system may + return fewer than the ``maxMessages`` requested even if + there are more messages available in the backlog. + """ + + received_messages = proto.RepeatedField(proto.MESSAGE, number=1, + message='ReceivedMessage', + ) + + +class ModifyAckDeadlineRequest(proto.Message): + r"""Request for the ModifyAckDeadline method. + + Attributes: + subscription (str): + Required. The name of the subscription. Format is + ``projects/{project}/subscriptions/{sub}``. + ack_ids (Sequence[str]): + Required. List of acknowledgment IDs. + ack_deadline_seconds (int): + Required. The new ack deadline with respect to the time this + request was sent to the Pub/Sub system. For example, if the + value is 10, the new ack deadline will expire 10 seconds + after the ``ModifyAckDeadline`` call was made. Specifying + zero might immediately make the message available for + delivery to another subscriber client. This typically + results in an increase in the rate of message redeliveries + (that is, duplicates). The minimum deadline you can specify + is 0 seconds. The maximum deadline you can specify is 600 + seconds (10 minutes). + """ + + subscription = proto.Field(proto.STRING, number=1) + + ack_ids = proto.RepeatedField(proto.STRING, number=4) + + ack_deadline_seconds = proto.Field(proto.INT32, number=3) + + +class AcknowledgeRequest(proto.Message): + r"""Request for the Acknowledge method. + + Attributes: + subscription (str): + Required. The subscription whose message is being + acknowledged. Format is + ``projects/{project}/subscriptions/{sub}``. + ack_ids (Sequence[str]): + Required. The acknowledgment ID for the messages being + acknowledged that was returned by the Pub/Sub system in the + ``Pull`` response. Must not be empty. + """ + + subscription = proto.Field(proto.STRING, number=1) + + ack_ids = proto.RepeatedField(proto.STRING, number=2) + + +class StreamingPullRequest(proto.Message): + r"""Request for the ``StreamingPull`` streaming RPC method. This request + is used to establish the initial stream as well as to stream + acknowledgements and ack deadline modifications from the client to + the server. + + Attributes: + subscription (str): + Required. The subscription for which to initialize the new + stream. This must be provided in the first request on the + stream, and must not be set in subsequent requests from + client to server. Format is + ``projects/{project}/subscriptions/{sub}``. + ack_ids (Sequence[str]): + List of acknowledgement IDs for acknowledging previously + received messages (received on this stream or a different + stream). If an ack ID has expired, the corresponding message + may be redelivered later. Acknowledging a message more than + once will not result in an error. If the acknowledgement ID + is malformed, the stream will be aborted with status + ``INVALID_ARGUMENT``. + modify_deadline_seconds (Sequence[int]): + The list of new ack deadlines for the IDs listed in + ``modify_deadline_ack_ids``. The size of this list must be + the same as the size of ``modify_deadline_ack_ids``. If it + differs the stream will be aborted with + ``INVALID_ARGUMENT``. Each element in this list is applied + to the element in the same position in + ``modify_deadline_ack_ids``. The new ack deadline is with + respect to the time this request was sent to the Pub/Sub + system. Must be >= 0. For example, if the value is 10, the + new ack deadline will expire 10 seconds after this request + is received. If the value is 0, the message is immediately + made available for another streaming or non-streaming pull + request. If the value is < 0 (an error), the stream will be + aborted with status ``INVALID_ARGUMENT``. + modify_deadline_ack_ids (Sequence[str]): + List of acknowledgement IDs whose deadline will be modified + based on the corresponding element in + ``modify_deadline_seconds``. This field can be used to + indicate that more time is needed to process a message by + the subscriber, or to make the message available for + redelivery if the processing was interrupted. + stream_ack_deadline_seconds (int): + Required. The ack deadline to use for the + stream. This must be provided in the first + request on the stream, but it can also be + updated on subsequent requests from client to + server. The minimum deadline you can specify is + 10 seconds. The maximum deadline you can specify + is 600 seconds (10 minutes). + client_id (str): + A unique identifier that is used to distinguish client + instances from each other. Only needs to be provided on the + initial request. When a stream disconnects and reconnects + for the same stream, the client_id should be set to the same + value so that state associated with the old stream can be + transferred to the new stream. The same client_id should not + be used for different client instances. + max_outstanding_messages (int): + Flow control settings for the maximum number of outstanding + messages. When there are ``max_outstanding_messages`` or + more currently sent to the streaming pull client that have + not yet been acked or nacked, the server stops sending more + messages. The sending of messages resumes once the number of + outstanding messages is less than this value. If the value + is <= 0, there is no limit to the number of outstanding + messages. This property can only be set on the initial + StreamingPullRequest. If it is set on a subsequent request, + the stream will be aborted with status ``INVALID_ARGUMENT``. + max_outstanding_bytes (int): + Flow control settings for the maximum number of outstanding + bytes. When there are ``max_outstanding_bytes`` or more + worth of messages currently sent to the streaming pull + client that have not yet been acked or nacked, the server + will stop sending more messages. The sending of messages + resumes once the number of outstanding bytes is less than + this value. If the value is <= 0, there is no limit to the + number of outstanding bytes. This property can only be set + on the initial StreamingPullRequest. If it is set on a + subsequent request, the stream will be aborted with status + ``INVALID_ARGUMENT``. + """ + + subscription = proto.Field(proto.STRING, number=1) + + ack_ids = proto.RepeatedField(proto.STRING, number=2) + + modify_deadline_seconds = proto.RepeatedField(proto.INT32, number=3) + + modify_deadline_ack_ids = proto.RepeatedField(proto.STRING, number=4) + + stream_ack_deadline_seconds = proto.Field(proto.INT32, number=5) + + client_id = proto.Field(proto.STRING, number=6) + + max_outstanding_messages = proto.Field(proto.INT64, number=7) + + max_outstanding_bytes = proto.Field(proto.INT64, number=8) + + +class StreamingPullResponse(proto.Message): + r"""Response for the ``StreamingPull`` method. This response is used to + stream messages from the server to the client. + + Attributes: + received_messages (Sequence[google.pubsub_v1.types.ReceivedMessage]): + Received Pub/Sub messages. This will not be + empty. + """ + + received_messages = proto.RepeatedField(proto.MESSAGE, number=1, + message='ReceivedMessage', + ) + + +class CreateSnapshotRequest(proto.Message): + r"""Request for the ``CreateSnapshot`` method. + + Attributes: + name (str): + Required. User-provided name for this snapshot. If the name + is not provided in the request, the server will assign a + random name for this snapshot on the same project as the + subscription. Note that for REST API requests, you must + specify a name. See the resource name rules. Format is + ``projects/{project}/snapshots/{snap}``. + subscription (str): + Required. The subscription whose backlog the snapshot + retains. Specifically, the created snapshot is guaranteed to + retain: (a) The existing backlog on the subscription. More + precisely, this is defined as the messages in the + subscription's backlog that are unacknowledged upon the + successful completion of the ``CreateSnapshot`` request; as + well as: (b) Any messages published to the subscription's + topic following the successful completion of the + CreateSnapshot request. Format is + ``projects/{project}/subscriptions/{sub}``. + labels (Sequence[google.pubsub_v1.types.CreateSnapshotRequest.LabelsEntry]): + See + Creating and managing labels. + """ + + name = proto.Field(proto.STRING, number=1) + + subscription = proto.Field(proto.STRING, number=2) + + labels = proto.MapField(proto.STRING, proto.STRING, number=3) + + +class UpdateSnapshotRequest(proto.Message): + r"""Request for the UpdateSnapshot method. + + Attributes: + snapshot (google.pubsub_v1.types.Snapshot): + Required. The updated snapshot object. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. Indicates which fields in the + provided snapshot to update. Must be specified + and non-empty. + """ + + snapshot = proto.Field(proto.MESSAGE, number=1, + message='Snapshot', + ) + + update_mask = proto.Field(proto.MESSAGE, number=2, + message=field_mask.FieldMask, + ) + + +class Snapshot(proto.Message): + r"""A snapshot resource. Snapshots are used in + `Seek `__ + operations, which allow you to manage message acknowledgments in + bulk. That is, you can set the acknowledgment state of messages in + an existing subscription to the state captured by a snapshot. + + Attributes: + name (str): + The name of the snapshot. + topic (str): + The name of the topic from which this + snapshot is retaining messages. + expire_time (google.protobuf.timestamp_pb2.Timestamp): + The snapshot is guaranteed to exist up until this time. A + newly-created snapshot expires no later than 7 days from the + time of its creation. Its exact lifetime is determined at + creation by the existing backlog in the source subscription. + Specifically, the lifetime of the snapshot is + ``7 days - (age of oldest unacked message in the subscription)``. + For example, consider a subscription whose oldest unacked + message is 3 days old. If a snapshot is created from this + subscription, the snapshot -- which will always capture this + 3-day-old backlog as long as the snapshot exists -- will + expire in 4 days. The service will refuse to create a + snapshot that would expire in less than 1 hour after + creation. + labels (Sequence[google.pubsub_v1.types.Snapshot.LabelsEntry]): + See [Creating and managing labels] + (https://cloud.google.com/pubsub/docs/labels). + """ + + name = proto.Field(proto.STRING, number=1) + + topic = proto.Field(proto.STRING, number=2) + + expire_time = proto.Field(proto.MESSAGE, number=3, + message=timestamp.Timestamp, + ) + + labels = proto.MapField(proto.STRING, proto.STRING, number=4) + + +class GetSnapshotRequest(proto.Message): + r"""Request for the GetSnapshot method. + + Attributes: + snapshot (str): + Required. The name of the snapshot to get. Format is + ``projects/{project}/snapshots/{snap}``. + """ + + snapshot = proto.Field(proto.STRING, number=1) + + +class ListSnapshotsRequest(proto.Message): + r"""Request for the ``ListSnapshots`` method. + + Attributes: + project (str): + Required. The name of the project in which to list + snapshots. Format is ``projects/{project-id}``. + page_size (int): + Maximum number of snapshots to return. + page_token (str): + The value returned by the last ``ListSnapshotsResponse``; + indicates that this is a continuation of a prior + ``ListSnapshots`` call, and that the system should return + the next page of data. + """ + + project = proto.Field(proto.STRING, number=1) + + page_size = proto.Field(proto.INT32, number=2) + + page_token = proto.Field(proto.STRING, number=3) + + +class ListSnapshotsResponse(proto.Message): + r"""Response for the ``ListSnapshots`` method. + + Attributes: + snapshots (Sequence[google.pubsub_v1.types.Snapshot]): + The resulting snapshots. + next_page_token (str): + If not empty, indicates that there may be more snapshot that + match the request; this value should be passed in a new + ``ListSnapshotsRequest``. + """ + + @property + def raw_page(self): + return self + + snapshots = proto.RepeatedField(proto.MESSAGE, number=1, + message='Snapshot', + ) + + next_page_token = proto.Field(proto.STRING, number=2) + + +class DeleteSnapshotRequest(proto.Message): + r"""Request for the ``DeleteSnapshot`` method. + + Attributes: + snapshot (str): + Required. The name of the snapshot to delete. Format is + ``projects/{project}/snapshots/{snap}``. + """ + + snapshot = proto.Field(proto.STRING, number=1) + + +class SeekRequest(proto.Message): + r"""Request for the ``Seek`` method. + + Attributes: + subscription (str): + Required. The subscription to affect. + time (google.protobuf.timestamp_pb2.Timestamp): + The time to seek to. Messages retained in the subscription + that were published before this time are marked as + acknowledged, and messages retained in the subscription that + were published after this time are marked as unacknowledged. + Note that this operation affects only those messages + retained in the subscription (configured by the combination + of ``message_retention_duration`` and + ``retain_acked_messages``). For example, if ``time`` + corresponds to a point before the message retention window + (or to a point before the system's notion of the + subscription creation time), only retained messages will be + marked as unacknowledged, and already-expunged messages will + not be restored. + snapshot (str): + The snapshot to seek to. The snapshot's topic must be the + same as that of the provided subscription. Format is + ``projects/{project}/snapshots/{snap}``. + """ + + 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') + + +class SeekResponse(proto.Message): + r"""Response for the ``Seek`` method (this response is empty).""" + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1/google/pubsub_v1/types/schema.py b/owl-bot-staging/v1/google/pubsub_v1/types/schema.py new file mode 100644 index 000000000..aae04e48d --- /dev/null +++ b/owl-bot-staging/v1/google/pubsub_v1/types/schema.py @@ -0,0 +1,262 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +import proto # type: ignore + + +__protobuf__ = proto.module( + package='google.pubsub.v1', + manifest={ + 'SchemaView', + 'Encoding', + 'Schema', + 'CreateSchemaRequest', + 'GetSchemaRequest', + 'ListSchemasRequest', + 'ListSchemasResponse', + 'DeleteSchemaRequest', + 'ValidateSchemaRequest', + 'ValidateSchemaResponse', + 'ValidateMessageRequest', + 'ValidateMessageResponse', + }, +) + + +class SchemaView(proto.Enum): + r"""View of Schema object fields to be returned by GetSchema and + ListSchemas. + """ + SCHEMA_VIEW_UNSPECIFIED = 0 + BASIC = 1 + FULL = 2 + + +class Encoding(proto.Enum): + r"""Possible encoding types for messages.""" + ENCODING_UNSPECIFIED = 0 + JSON = 1 + BINARY = 2 + + +class Schema(proto.Message): + r"""A schema resource. + + Attributes: + name (str): + Required. Name of the schema. Format is + ``projects/{project}/schemas/{schema}``. + type_ (google.pubsub_v1.types.Schema.Type): + The type of the schema definition. + definition (str): + The definition of the schema. This should contain a string + representing the full definition of the schema that is a + valid schema definition of the type specified in ``type``. + """ + class Type(proto.Enum): + r"""Possible schema definition types.""" + TYPE_UNSPECIFIED = 0 + PROTOCOL_BUFFER = 1 + AVRO = 2 + + name = proto.Field(proto.STRING, number=1) + + type_ = proto.Field(proto.ENUM, number=2, + enum=Type, + ) + + definition = proto.Field(proto.STRING, number=3) + + +class CreateSchemaRequest(proto.Message): + r"""Request for the CreateSchema method. + + Attributes: + parent (str): + Required. The name of the project in which to create the + schema. Format is ``projects/{project-id}``. + schema (google.pubsub_v1.types.Schema): + Required. The schema object to create. + + This schema's ``name`` parameter is ignored. The schema + object returned by CreateSchema will have a ``name`` made + using the given ``parent`` and ``schema_id``. + schema_id (str): + The ID to use for the schema, which will become the final + component of the schema's resource name. + + See + https://cloud.google.com/pubsub/docs/admin#resource_names + for resource name constraints. + """ + + parent = proto.Field(proto.STRING, number=1) + + schema = proto.Field(proto.MESSAGE, number=2, + message='Schema', + ) + + schema_id = proto.Field(proto.STRING, number=3) + + +class GetSchemaRequest(proto.Message): + r"""Request for the GetSchema method. + + Attributes: + name (str): + Required. The name of the schema to get. Format is + ``projects/{project}/schemas/{schema}``. + view (google.pubsub_v1.types.SchemaView): + The set of fields to return in the response. If not set, + returns a Schema with ``name`` and ``type``, but not + ``definition``. Set to ``FULL`` to retrieve all fields. + """ + + name = proto.Field(proto.STRING, number=1) + + view = proto.Field(proto.ENUM, number=2, + enum='SchemaView', + ) + + +class ListSchemasRequest(proto.Message): + r"""Request for the ``ListSchemas`` method. + + Attributes: + parent (str): + Required. The name of the project in which to list schemas. + Format is ``projects/{project-id}``. + view (google.pubsub_v1.types.SchemaView): + The set of Schema fields to return in the response. If not + set, returns Schemas with ``name`` and ``type``, but not + ``definition``. Set to ``FULL`` to retrieve all fields. + page_size (int): + Maximum number of schemas to return. + page_token (str): + The value returned by the last ``ListSchemasResponse``; + indicates that this is a continuation of a prior + ``ListSchemas`` call, and that the system should return the + next page of data. + """ + + parent = proto.Field(proto.STRING, number=1) + + view = proto.Field(proto.ENUM, number=2, + enum='SchemaView', + ) + + page_size = proto.Field(proto.INT32, number=3) + + page_token = proto.Field(proto.STRING, number=4) + + +class ListSchemasResponse(proto.Message): + r"""Response for the ``ListSchemas`` method. + + Attributes: + schemas (Sequence[google.pubsub_v1.types.Schema]): + The resulting schemas. + next_page_token (str): + If not empty, indicates that there may be more schemas that + match the request; this value should be passed in a new + ``ListSchemasRequest``. + """ + + @property + def raw_page(self): + return self + + schemas = proto.RepeatedField(proto.MESSAGE, number=1, + message='Schema', + ) + + next_page_token = proto.Field(proto.STRING, number=2) + + +class DeleteSchemaRequest(proto.Message): + r"""Request for the ``DeleteSchema`` method. + + Attributes: + name (str): + Required. Name of the schema to delete. Format is + ``projects/{project}/schemas/{schema}``. + """ + + name = proto.Field(proto.STRING, number=1) + + +class ValidateSchemaRequest(proto.Message): + r"""Request for the ``ValidateSchema`` method. + + Attributes: + parent (str): + Required. The name of the project in which to validate + schemas. Format is ``projects/{project-id}``. + schema (google.pubsub_v1.types.Schema): + Required. The schema object to validate. + """ + + parent = proto.Field(proto.STRING, number=1) + + schema = proto.Field(proto.MESSAGE, number=2, + message='Schema', + ) + + +class ValidateSchemaResponse(proto.Message): + r"""Response for the ``ValidateSchema`` method.""" + + +class ValidateMessageRequest(proto.Message): + r"""Request for the ``ValidateMessage`` method. + + Attributes: + parent (str): + Required. The name of the project in which to validate + schemas. Format is ``projects/{project-id}``. + name (str): + Name of the schema against which to validate. + + Format is ``projects/{project}/schemas/{schema}``. + schema (google.pubsub_v1.types.Schema): + Ad-hoc schema against which to validate + message (bytes): + Message to validate against the provided ``schema_spec``. + encoding (google.pubsub_v1.types.Encoding): + The encoding expected for messages + """ + + parent = proto.Field(proto.STRING, number=1) + + name = proto.Field(proto.STRING, number=2, oneof='schema_spec') + + schema = proto.Field(proto.MESSAGE, number=3, oneof='schema_spec', + message='Schema', + ) + + message = proto.Field(proto.BYTES, number=4) + + encoding = proto.Field(proto.ENUM, number=5, + enum='Encoding', + ) + + +class ValidateMessageResponse(proto.Message): + r"""Response for the ``ValidateMessage`` method.""" + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1/mypy.ini b/owl-bot-staging/v1/mypy.ini new file mode 100644 index 000000000..4505b4854 --- /dev/null +++ b/owl-bot-staging/v1/mypy.ini @@ -0,0 +1,3 @@ +[mypy] +python_version = 3.6 +namespace_packages = True diff --git a/owl-bot-staging/v1/noxfile.py b/owl-bot-staging/v1/noxfile.py new file mode 100644 index 000000000..06898353b --- /dev/null +++ b/owl-bot-staging/v1/noxfile.py @@ -0,0 +1,72 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +import os +import shutil + +import nox # type: ignore + + +@nox.session(python=['3.6', '3.7', '3.8', '3.9']) +def unit(session): + """Run the unit test suite.""" + + session.install('coverage', 'pytest', 'pytest-cov', 'asyncmock', 'pytest-asyncio') + session.install('-e', '.') + + session.run( + 'py.test', + '--quiet', + '--cov=google/pubsub_v1/', + '--cov-config=.coveragerc', + '--cov-report=term', + '--cov-report=html', + os.path.join('tests', 'unit', ''.join(session.posargs)) + ) + + +@nox.session(python=['3.6', '3.7']) +def mypy(session): + """Run the type checker.""" + session.install('mypy') + session.install('.') + session.run( + 'mypy', + '--explicit-package-bases', + 'google', + ) + +@nox.session(python='3.6') +def docs(session): + """Build the docs for this library.""" + + session.install("-e", ".") + session.install("sphinx<3.0.0", "alabaster", "recommonmark") + + shutil.rmtree(os.path.join("docs", "_build"), ignore_errors=True) + session.run( + "sphinx-build", + "-W", # warnings as errors + "-T", # show full traceback on exception + "-N", # no colors + "-b", + "html", + "-d", + os.path.join("docs", "_build", "doctrees", ""), + os.path.join("docs", ""), + os.path.join("docs", "_build", "html", ""), + ) diff --git a/owl-bot-staging/v1/scripts/fixup_pubsub_v1_keywords.py b/owl-bot-staging/v1/scripts/fixup_pubsub_v1_keywords.py new file mode 100644 index 000000000..071e3665f --- /dev/null +++ b/owl-bot-staging/v1/scripts/fixup_pubsub_v1_keywords.py @@ -0,0 +1,213 @@ +#! /usr/bin/env python3 +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +import argparse +import os +import libcst as cst +import pathlib +import sys +from typing import (Any, Callable, Dict, List, Sequence, Tuple) + + +def partition( + predicate: Callable[[Any], bool], + iterator: Sequence[Any] +) -> Tuple[List[Any], List[Any]]: + """A stable, out-of-place partition.""" + results = ([], []) + + for i in iterator: + results[int(predicate(i))].append(i) + + # Returns trueList, falseList + return results[1], results[0] + + +class pubsubCallTransformer(cst.CSTTransformer): + CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') + METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { + 'acknowledge': ('subscription', 'ack_ids', ), + 'create_schema': ('parent', 'schema', 'schema_id', ), + 'create_snapshot': ('name', 'subscription', 'labels', ), + 'create_subscription': ('name', 'topic', 'push_config', 'ack_deadline_seconds', 'retain_acked_messages', 'message_retention_duration', 'labels', 'enable_message_ordering', 'expiration_policy', 'filter', 'dead_letter_policy', 'retry_policy', 'detached', ), + '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: + try: + key = original.func.attr.value + kword_params = self.METHOD_TO_PARAMS[key] + except (AttributeError, KeyError): + # Either not a method from the API or too convoluted to be sure. + return updated + + # If the existing code is valid, keyword args come after positional args. + # Therefore, all positional args must map to the first parameters. + args, kwargs = partition(lambda a: not bool(a.keyword), updated.args) + if any(k.keyword.value == "request" for k in kwargs): + # We've already fixed this file, don't fix it again. + return updated + + kwargs, ctrl_kwargs = partition( + lambda a: not a.keyword.value in self.CTRL_PARAMS, + kwargs + ) + + args, ctrl_args = args[:len(kword_params)], args[len(kword_params):] + ctrl_kwargs.extend(cst.Arg(value=a.value, keyword=cst.Name(value=ctrl)) + for a, ctrl in zip(ctrl_args, self.CTRL_PARAMS)) + + request_arg = cst.Arg( + value=cst.Dict([ + cst.DictElement( + cst.SimpleString("'{}'".format(name)), + cst.Element(value=arg.value) + ) + # Note: the args + kwargs looks silly, but keep in mind that + # the control parameters had to be stripped out, and that + # those could have been passed positionally or by keyword. + for name, arg in zip(kword_params, args + kwargs)]), + keyword=cst.Name("request") + ) + + return updated.with_changes( + args=[request_arg] + ctrl_kwargs + ) + + +def fix_files( + in_dir: pathlib.Path, + out_dir: pathlib.Path, + *, + transformer=pubsubCallTransformer(), +): + """Duplicate the input dir to the output dir, fixing file method calls. + + Preconditions: + * in_dir is a real directory + * out_dir is a real, empty directory + """ + pyfile_gen = ( + pathlib.Path(os.path.join(root, f)) + for root, _, files in os.walk(in_dir) + for f in files if os.path.splitext(f)[1] == ".py" + ) + + for fpath in pyfile_gen: + with open(fpath, 'r') as f: + src = f.read() + + # Parse the code and insert method call fixes. + tree = cst.parse_module(src) + updated = tree.visit(transformer) + + # Create the path and directory structure for the new file. + updated_path = out_dir.joinpath(fpath.relative_to(in_dir)) + updated_path.parent.mkdir(parents=True, exist_ok=True) + + # Generate the updated source file at the corresponding path. + with open(updated_path, 'w') as f: + f.write(updated.code) + + +if __name__ == '__main__': + parser = argparse.ArgumentParser( + description="""Fix up source that uses the pubsub client library. + +The existing sources are NOT overwritten but are copied to output_dir with changes made. + +Note: This tool operates at a best-effort level at converting positional + parameters in client method calls to keyword based parameters. + Cases where it WILL FAIL include + A) * or ** expansion in a method call. + B) Calls via function or method alias (includes free function calls) + C) Indirect or dispatched calls (e.g. the method is looked up dynamically) + + These all constitute false negatives. The tool will also detect false + positives when an API method shares a name with another method. +""") + parser.add_argument( + '-d', + '--input-directory', + required=True, + dest='input_dir', + help='the input directory to walk for python files to fix up', + ) + parser.add_argument( + '-o', + '--output-directory', + required=True, + dest='output_dir', + help='the directory to output files fixed via un-flattening', + ) + args = parser.parse_args() + input_dir = pathlib.Path(args.input_dir) + output_dir = pathlib.Path(args.output_dir) + if not input_dir.is_dir(): + print( + f"input directory '{input_dir}' does not exist or is not a directory", + file=sys.stderr, + ) + sys.exit(-1) + + if not output_dir.is_dir(): + print( + f"output directory '{output_dir}' does not exist or is not a directory", + file=sys.stderr, + ) + sys.exit(-1) + + if os.listdir(output_dir): + print( + f"output directory '{output_dir}' is not empty", + file=sys.stderr, + ) + sys.exit(-1) + + fix_files(input_dir, output_dir) diff --git a/owl-bot-staging/v1/setup.py b/owl-bot-staging/v1/setup.py new file mode 100644 index 000000000..82bb43639 --- /dev/null +++ b/owl-bot-staging/v1/setup.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +import io +import os +import setuptools # type: ignore + +version = '0.1.0' + +package_root = os.path.abspath(os.path.dirname(__file__)) + +readme_filename = os.path.join(package_root, 'README.rst') +with io.open(readme_filename, encoding='utf-8') as readme_file: + readme = readme_file.read() + +setuptools.setup( + name='google-pubsub', + version=version, + long_description=readme, + packages=setuptools.PEP420PackageFinder.find(), + namespace_packages=('google',), + platforms='Posix; MacOS X; Windows', + include_package_data=True, + install_requires=( + 'google-api-core[grpc] >= 1.22.2, < 2.0.0dev', + 'libcst >= 0.2.5', + 'proto-plus >= 1.15.0', + 'grpc-google-iam-v1', + ), + python_requires='>=3.6', + classifiers=[ + 'Development Status :: 3 - Alpha', + 'Intended Audience :: Developers', + 'Operating System :: OS Independent', + 'Programming Language :: Python :: 3.6', + 'Programming Language :: Python :: 3.7', + 'Programming Language :: Python :: 3.8', + 'Topic :: Internet', + 'Topic :: Software Development :: Libraries :: Python Modules', + ], + zip_safe=False, +) diff --git a/owl-bot-staging/v1/tests/unit/gapic/pubsub_v1/__init__.py b/owl-bot-staging/v1/tests/unit/gapic/pubsub_v1/__init__.py new file mode 100644 index 000000000..6a7301536 --- /dev/null +++ b/owl-bot-staging/v1/tests/unit/gapic/pubsub_v1/__init__.py @@ -0,0 +1,17 @@ + +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/owl-bot-staging/v1/tests/unit/gapic/pubsub_v1/test_publisher.py b/owl-bot-staging/v1/tests/unit/gapic/pubsub_v1/test_publisher.py new file mode 100644 index 000000000..6324e48ec --- /dev/null +++ b/owl-bot-staging/v1/tests/unit/gapic/pubsub_v1/test_publisher.py @@ -0,0 +1,3983 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +import os +import mock + +import grpc +from grpc.experimental import aio +import math +import pytest +from proto.marshal.rules.dates import DurationRule, TimestampRule + +from google import auth +from google.api_core import client_options +from google.api_core import 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.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.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.pubsub_v1.services.publisher import PublisherAsyncClient +from google.pubsub_v1.services.publisher import PublisherClient +from google.pubsub_v1.services.publisher import pagers +from google.pubsub_v1.services.publisher import transports +from google.pubsub_v1.types import pubsub +from google.pubsub_v1.types import schema + + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + + assert PublisherClient._get_default_mtls_endpoint(None) is None + assert PublisherClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert PublisherClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert PublisherClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert PublisherClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert PublisherClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + + +@pytest.mark.parametrize("client_class", [ + PublisherClient, + PublisherAsyncClient, +]) +def test_publisher_client_from_service_account_info(client_class): + creds = credentials.AnonymousCredentials() + with mock.patch.object(service_account.Credentials, 'from_service_account_info') as factory: + factory.return_value = creds + info = {"valid": True} + client = client_class.from_service_account_info(info) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == 'pubsub.googleapis.com:443' + + +@pytest.mark.parametrize("client_class", [ + PublisherClient, + PublisherAsyncClient, +]) +def test_publisher_client_from_service_account_file(client_class): + creds = credentials.AnonymousCredentials() + with mock.patch.object(service_account.Credentials, 'from_service_account_file') as factory: + factory.return_value = creds + client = client_class.from_service_account_file("dummy/file/path.json") + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + client = client_class.from_service_account_json("dummy/file/path.json") + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == 'pubsub.googleapis.com:443' + + +def test_publisher_client_get_transport_class(): + transport = PublisherClient.get_transport_class() + available_transports = [ + transports.PublisherGrpcTransport, + ] + assert transport in available_transports + + transport = PublisherClient.get_transport_class("grpc") + assert transport == transports.PublisherGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (PublisherClient, transports.PublisherGrpcTransport, "grpc"), + (PublisherAsyncClient, transports.PublisherGrpcAsyncIOTransport, "grpc_asyncio"), +]) +@mock.patch.object(PublisherClient, "DEFAULT_ENDPOINT", modify_default_endpoint(PublisherClient)) +@mock.patch.object(PublisherAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(PublisherAsyncClient)) +def test_publisher_client_client_options(client_class, transport_class, transport_name): + # Check that if channel is provided we won't create a new one. + with mock.patch.object(PublisherClient, 'get_transport_class') as gtc: + transport = transport_class( + credentials=credentials.AnonymousCredentials() + ) + client = client_class(transport=transport) + gtc.assert_not_called() + + # Check that if channel is provided via str we will create a new one. + with mock.patch.object(PublisherClient, 'get_transport_class') as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check the case api_endpoint is provided. + options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError): + client = client_class() + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError): + client = client_class() + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ + + (PublisherClient, transports.PublisherGrpcTransport, "grpc", "true"), + (PublisherAsyncClient, transports.PublisherGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (PublisherClient, transports.PublisherGrpcTransport, "grpc", "false"), + (PublisherAsyncClient, transports.PublisherGrpcAsyncIOTransport, "grpc_asyncio", "false"), + +]) +@mock.patch.object(PublisherClient, "DEFAULT_ENDPOINT", modify_default_endpoint(PublisherClient)) +@mock.patch.object(PublisherAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(PublisherAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_publisher_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): + # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default + # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. + + # Check the case client_cert_source is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options) + + if use_client_cert_env == "false": + expected_client_cert_source = None + expected_host = client.DEFAULT_ENDPOINT + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): + if use_client_cert_env == "false": + expected_host = client.DEFAULT_ENDPOINT + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (PublisherClient, transports.PublisherGrpcTransport, "grpc"), + (PublisherAsyncClient, transports.PublisherGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_publisher_client_client_options_scopes(client_class, transport_class, transport_name): + # Check the case scopes are provided. + options = client_options.ClientOptions( + scopes=["1", "2"], + ) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=["1", "2"], + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (PublisherClient, transports.PublisherGrpcTransport, "grpc"), + (PublisherAsyncClient, transports.PublisherGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_publisher_client_client_options_credentials_file(client_class, transport_class, transport_name): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + +def test_publisher_client_client_options_from_dict(): + with mock.patch('google.pubsub_v1.services.publisher.transports.PublisherGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = PublisherClient( + client_options={'api_endpoint': 'squid.clam.whelk'} + ) + grpc_transport.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + +def test_create_topic(transport: str = 'grpc', request_type=pubsub.Topic): + client = PublisherClient( + credentials=credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_topic), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = pubsub.Topic( + name='name_value', + + kms_key_name='kms_key_name_value', + + satisfies_pzs=True, + + ) + + response = client.create_topic(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == pubsub.Topic() + + # Establish that the response is the type that we expect. + + assert isinstance(response, pubsub.Topic) + + assert response.name == 'name_value' + + assert response.kms_key_name == 'kms_key_name_value' + + assert response.satisfies_pzs is True + + +def test_create_topic_from_dict(): + test_create_topic(request_type=dict) + + +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', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_topic), + '__call__') as call: + client.create_topic() + call.assert_called() + _, args, _ = call.mock_calls[0] + + assert args[0] == pubsub.Topic() + +@pytest.mark.asyncio +async def test_create_topic_async(transport: str = 'grpc_asyncio', request_type=pubsub.Topic): + client = PublisherAsyncClient( + credentials=credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_topic), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(pubsub.Topic( + name='name_value', + kms_key_name='kms_key_name_value', + satisfies_pzs=True, + )) + + response = await client.create_topic(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == pubsub.Topic() + + # Establish that the response is the type that we expect. + assert isinstance(response, pubsub.Topic) + + assert response.name == 'name_value' + + assert response.kms_key_name == 'kms_key_name_value' + + assert response.satisfies_pzs is True + + +@pytest.mark.asyncio +async def test_create_topic_async_from_dict(): + await test_create_topic_async(request_type=dict) + + +def test_create_topic_field_headers(): + client = PublisherClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = pubsub.Topic() + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_topic), + '__call__') as call: + call.return_value = pubsub.Topic() + + client.create_topic(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name/value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_create_topic_field_headers_async(): + client = PublisherAsyncClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = pubsub.Topic() + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_topic), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(pubsub.Topic()) + + await client.create_topic(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name/value', + ) in kw['metadata'] + + +def test_create_topic_flattened(): + client = PublisherClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_topic), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = pubsub.Topic() + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_topic( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0].name == 'name_value' + + +def test_create_topic_flattened_error(): + client = PublisherClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.create_topic( + pubsub.Topic(), + name='name_value', + ) + + +@pytest.mark.asyncio +async def test_create_topic_flattened_async(): + client = PublisherAsyncClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_topic), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = pubsub.Topic() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(pubsub.Topic()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_topic( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0].name == 'name_value' + + +@pytest.mark.asyncio +async def test_create_topic_flattened_error_async(): + client = PublisherAsyncClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.create_topic( + pubsub.Topic(), + name='name_value', + ) + + +def test_update_topic(transport: str = 'grpc', request_type=pubsub.UpdateTopicRequest): + client = PublisherClient( + credentials=credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_topic), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = pubsub.Topic( + name='name_value', + + kms_key_name='kms_key_name_value', + + satisfies_pzs=True, + + ) + + response = client.update_topic(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == pubsub.UpdateTopicRequest() + + # Establish that the response is the type that we expect. + + assert isinstance(response, pubsub.Topic) + + assert response.name == 'name_value' + + assert response.kms_key_name == 'kms_key_name_value' + + assert response.satisfies_pzs is True + + +def test_update_topic_from_dict(): + test_update_topic(request_type=dict) + + +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', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_topic), + '__call__') as call: + client.update_topic() + call.assert_called() + _, args, _ = call.mock_calls[0] + + assert args[0] == pubsub.UpdateTopicRequest() + +@pytest.mark.asyncio +async def test_update_topic_async(transport: str = 'grpc_asyncio', request_type=pubsub.UpdateTopicRequest): + client = PublisherAsyncClient( + credentials=credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_topic), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(pubsub.Topic( + name='name_value', + kms_key_name='kms_key_name_value', + satisfies_pzs=True, + )) + + response = await client.update_topic(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == pubsub.UpdateTopicRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pubsub.Topic) + + assert response.name == 'name_value' + + assert response.kms_key_name == 'kms_key_name_value' + + assert response.satisfies_pzs is True + + +@pytest.mark.asyncio +async def test_update_topic_async_from_dict(): + await test_update_topic_async(request_type=dict) + + +def test_update_topic_field_headers(): + client = PublisherClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = pubsub.UpdateTopicRequest() + request.topic.name = 'topic.name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_topic), + '__call__') as call: + call.return_value = pubsub.Topic() + + client.update_topic(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'topic.name=topic.name/value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_topic_field_headers_async(): + client = PublisherAsyncClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = pubsub.UpdateTopicRequest() + request.topic.name = 'topic.name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_topic), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(pubsub.Topic()) + + await client.update_topic(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'topic.name=topic.name/value', + ) in kw['metadata'] + + +def test_publish(transport: str = 'grpc', request_type=pubsub.PublishRequest): + client = PublisherClient( + credentials=credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.publish), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = pubsub.PublishResponse( + message_ids=['message_ids_value'], + + ) + + response = client.publish(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == pubsub.PublishRequest() + + # Establish that the response is the type that we expect. + + assert isinstance(response, pubsub.PublishResponse) + + assert response.message_ids == ['message_ids_value'] + + +def test_publish_from_dict(): + test_publish(request_type=dict) + + +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', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.publish), + '__call__') as call: + client.publish() + call.assert_called() + _, args, _ = call.mock_calls[0] + + assert args[0] == pubsub.PublishRequest() + +@pytest.mark.asyncio +async def test_publish_async(transport: str = 'grpc_asyncio', request_type=pubsub.PublishRequest): + client = PublisherAsyncClient( + credentials=credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.publish), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(pubsub.PublishResponse( + message_ids=['message_ids_value'], + )) + + response = await client.publish(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == pubsub.PublishRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pubsub.PublishResponse) + + assert response.message_ids == ['message_ids_value'] + + +@pytest.mark.asyncio +async def test_publish_async_from_dict(): + await test_publish_async(request_type=dict) + + +def test_publish_field_headers(): + client = PublisherClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = pubsub.PublishRequest() + request.topic = 'topic/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.publish), + '__call__') as call: + call.return_value = pubsub.PublishResponse() + + client.publish(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'topic=topic/value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_publish_field_headers_async(): + client = PublisherAsyncClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = pubsub.PublishRequest() + request.topic = 'topic/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.publish), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(pubsub.PublishResponse()) + + await client.publish(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'topic=topic/value', + ) in kw['metadata'] + + +def test_publish_flattened(): + client = PublisherClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.publish), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = pubsub.PublishResponse() + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.publish( + topic='topic_value', + messages=[pubsub.PubsubMessage(data=b'data_blob')], + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + 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(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.publish( + pubsub.PublishRequest(), + topic='topic_value', + messages=[pubsub.PubsubMessage(data=b'data_blob')], + ) + + +@pytest.mark.asyncio +async def test_publish_flattened_async(): + client = PublisherAsyncClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.publish), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = pubsub.PublishResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(pubsub.PublishResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.publish( + topic='topic_value', + messages=[pubsub.PubsubMessage(data=b'data_blob')], + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + 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(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.publish( + pubsub.PublishRequest(), + topic='topic_value', + messages=[pubsub.PubsubMessage(data=b'data_blob')], + ) + + +def test_get_topic(transport: str = 'grpc', request_type=pubsub.GetTopicRequest): + client = PublisherClient( + credentials=credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_topic), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = pubsub.Topic( + name='name_value', + + kms_key_name='kms_key_name_value', + + satisfies_pzs=True, + + ) + + response = client.get_topic(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == pubsub.GetTopicRequest() + + # Establish that the response is the type that we expect. + + assert isinstance(response, pubsub.Topic) + + assert response.name == 'name_value' + + assert response.kms_key_name == 'kms_key_name_value' + + assert response.satisfies_pzs is True + + +def test_get_topic_from_dict(): + test_get_topic(request_type=dict) + + +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', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_topic), + '__call__') as call: + client.get_topic() + call.assert_called() + _, args, _ = call.mock_calls[0] + + assert args[0] == pubsub.GetTopicRequest() + +@pytest.mark.asyncio +async def test_get_topic_async(transport: str = 'grpc_asyncio', request_type=pubsub.GetTopicRequest): + client = PublisherAsyncClient( + credentials=credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_topic), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(pubsub.Topic( + name='name_value', + kms_key_name='kms_key_name_value', + satisfies_pzs=True, + )) + + response = await client.get_topic(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == pubsub.GetTopicRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pubsub.Topic) + + assert response.name == 'name_value' + + assert response.kms_key_name == 'kms_key_name_value' + + assert response.satisfies_pzs is True + + +@pytest.mark.asyncio +async def test_get_topic_async_from_dict(): + await test_get_topic_async(request_type=dict) + + +def test_get_topic_field_headers(): + client = PublisherClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = pubsub.GetTopicRequest() + request.topic = 'topic/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_topic), + '__call__') as call: + call.return_value = pubsub.Topic() + + client.get_topic(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'topic=topic/value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_get_topic_field_headers_async(): + client = PublisherAsyncClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = pubsub.GetTopicRequest() + request.topic = 'topic/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_topic), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(pubsub.Topic()) + + await client.get_topic(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'topic=topic/value', + ) in kw['metadata'] + + +def test_get_topic_flattened(): + client = PublisherClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_topic), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = pubsub.Topic() + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_topic( + topic='topic_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0].topic == 'topic_value' + + +def test_get_topic_flattened_error(): + client = PublisherClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_topic( + pubsub.GetTopicRequest(), + topic='topic_value', + ) + + +@pytest.mark.asyncio +async def test_get_topic_flattened_async(): + client = PublisherAsyncClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_topic), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = pubsub.Topic() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(pubsub.Topic()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_topic( + topic='topic_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0].topic == 'topic_value' + + +@pytest.mark.asyncio +async def test_get_topic_flattened_error_async(): + client = PublisherAsyncClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_topic( + pubsub.GetTopicRequest(), + topic='topic_value', + ) + + +def test_list_topics(transport: str = 'grpc', request_type=pubsub.ListTopicsRequest): + client = PublisherClient( + credentials=credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_topics), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = pubsub.ListTopicsResponse( + next_page_token='next_page_token_value', + + ) + + response = client.list_topics(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == pubsub.ListTopicsRequest() + + # Establish that the response is the type that we expect. + + assert isinstance(response, pagers.ListTopicsPager) + + assert response.next_page_token == 'next_page_token_value' + + +def test_list_topics_from_dict(): + test_list_topics(request_type=dict) + + +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', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_topics), + '__call__') as call: + client.list_topics() + call.assert_called() + _, args, _ = call.mock_calls[0] + + assert args[0] == pubsub.ListTopicsRequest() + +@pytest.mark.asyncio +async def test_list_topics_async(transport: str = 'grpc_asyncio', request_type=pubsub.ListTopicsRequest): + client = PublisherAsyncClient( + credentials=credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_topics), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(pubsub.ListTopicsResponse( + next_page_token='next_page_token_value', + )) + + response = await client.list_topics(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == pubsub.ListTopicsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListTopicsAsyncPager) + + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_topics_async_from_dict(): + await test_list_topics_async(request_type=dict) + + +def test_list_topics_field_headers(): + client = PublisherClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = pubsub.ListTopicsRequest() + request.project = 'project/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_topics), + '__call__') as call: + call.return_value = pubsub.ListTopicsResponse() + + client.list_topics(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'project=project/value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_list_topics_field_headers_async(): + client = PublisherAsyncClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = pubsub.ListTopicsRequest() + request.project = 'project/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_topics), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(pubsub.ListTopicsResponse()) + + await client.list_topics(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'project=project/value', + ) in kw['metadata'] + + +def test_list_topics_flattened(): + client = PublisherClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_topics), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = pubsub.ListTopicsResponse() + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_topics( + project='project_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0].project == 'project_value' + + +def test_list_topics_flattened_error(): + client = PublisherClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_topics( + pubsub.ListTopicsRequest(), + project='project_value', + ) + + +@pytest.mark.asyncio +async def test_list_topics_flattened_async(): + client = PublisherAsyncClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_topics), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = pubsub.ListTopicsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(pubsub.ListTopicsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_topics( + project='project_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0].project == 'project_value' + + +@pytest.mark.asyncio +async def test_list_topics_flattened_error_async(): + client = PublisherAsyncClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_topics( + pubsub.ListTopicsRequest(), + project='project_value', + ) + + +def test_list_topics_pager(): + client = PublisherClient( + credentials=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: + # Set the response to a series of pages. + call.side_effect = ( + pubsub.ListTopicsResponse( + topics=[ + pubsub.Topic(), + pubsub.Topic(), + pubsub.Topic(), + ], + next_page_token='abc', + ), + pubsub.ListTopicsResponse( + topics=[], + next_page_token='def', + ), + pubsub.ListTopicsResponse( + topics=[ + pubsub.Topic(), + ], + next_page_token='ghi', + ), + pubsub.ListTopicsResponse( + topics=[ + pubsub.Topic(), + pubsub.Topic(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('project', ''), + )), + ) + pager = client.list_topics(request={}) + + assert pager._metadata == metadata + + results = [i for i in pager] + assert len(results) == 6 + assert all(isinstance(i, pubsub.Topic) + for i in results) + +def test_list_topics_pages(): + client = PublisherClient( + credentials=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: + # Set the response to a series of pages. + call.side_effect = ( + pubsub.ListTopicsResponse( + topics=[ + pubsub.Topic(), + pubsub.Topic(), + pubsub.Topic(), + ], + next_page_token='abc', + ), + pubsub.ListTopicsResponse( + topics=[], + next_page_token='def', + ), + pubsub.ListTopicsResponse( + topics=[ + pubsub.Topic(), + ], + next_page_token='ghi', + ), + pubsub.ListTopicsResponse( + topics=[ + pubsub.Topic(), + pubsub.Topic(), + ], + ), + RuntimeError, + ) + pages = list(client.list_topics(request={}).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +@pytest.mark.asyncio +async def test_list_topics_async_pager(): + client = PublisherAsyncClient( + credentials=credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_topics), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + pubsub.ListTopicsResponse( + topics=[ + pubsub.Topic(), + pubsub.Topic(), + pubsub.Topic(), + ], + next_page_token='abc', + ), + pubsub.ListTopicsResponse( + topics=[], + next_page_token='def', + ), + pubsub.ListTopicsResponse( + topics=[ + pubsub.Topic(), + ], + next_page_token='ghi', + ), + pubsub.ListTopicsResponse( + topics=[ + pubsub.Topic(), + pubsub.Topic(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_topics(request={},) + assert async_pager.next_page_token == 'abc' + responses = [] + async for response in async_pager: + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, pubsub.Topic) + for i in responses) + +@pytest.mark.asyncio +async def test_list_topics_async_pages(): + client = PublisherAsyncClient( + credentials=credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_topics), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + pubsub.ListTopicsResponse( + topics=[ + pubsub.Topic(), + pubsub.Topic(), + pubsub.Topic(), + ], + next_page_token='abc', + ), + pubsub.ListTopicsResponse( + topics=[], + next_page_token='def', + ), + pubsub.ListTopicsResponse( + topics=[ + pubsub.Topic(), + ], + next_page_token='ghi', + ), + pubsub.ListTopicsResponse( + topics=[ + pubsub.Topic(), + pubsub.Topic(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.list_topics(request={})).pages: + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +def test_list_topic_subscriptions(transport: str = 'grpc', request_type=pubsub.ListTopicSubscriptionsRequest): + client = PublisherClient( + credentials=credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_topic_subscriptions), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = pubsub.ListTopicSubscriptionsResponse( + subscriptions=['subscriptions_value'], + + next_page_token='next_page_token_value', + + ) + + response = client.list_topic_subscriptions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == pubsub.ListTopicSubscriptionsRequest() + + # Establish that the response is the type that we expect. + + assert isinstance(response, pagers.ListTopicSubscriptionsPager) + + assert response.subscriptions == ['subscriptions_value'] + + assert response.next_page_token == 'next_page_token_value' + + +def test_list_topic_subscriptions_from_dict(): + test_list_topic_subscriptions(request_type=dict) + + +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', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_topic_subscriptions), + '__call__') as call: + client.list_topic_subscriptions() + call.assert_called() + _, args, _ = call.mock_calls[0] + + assert args[0] == pubsub.ListTopicSubscriptionsRequest() + +@pytest.mark.asyncio +async def test_list_topic_subscriptions_async(transport: str = 'grpc_asyncio', request_type=pubsub.ListTopicSubscriptionsRequest): + client = PublisherAsyncClient( + credentials=credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_topic_subscriptions), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(pubsub.ListTopicSubscriptionsResponse( + subscriptions=['subscriptions_value'], + next_page_token='next_page_token_value', + )) + + response = await client.list_topic_subscriptions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == pubsub.ListTopicSubscriptionsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListTopicSubscriptionsAsyncPager) + + assert response.subscriptions == ['subscriptions_value'] + + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_topic_subscriptions_async_from_dict(): + await test_list_topic_subscriptions_async(request_type=dict) + + +def test_list_topic_subscriptions_field_headers(): + client = PublisherClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = pubsub.ListTopicSubscriptionsRequest() + request.topic = 'topic/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_topic_subscriptions), + '__call__') as call: + call.return_value = pubsub.ListTopicSubscriptionsResponse() + + client.list_topic_subscriptions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'topic=topic/value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_list_topic_subscriptions_field_headers_async(): + client = PublisherAsyncClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = pubsub.ListTopicSubscriptionsRequest() + request.topic = 'topic/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_topic_subscriptions), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(pubsub.ListTopicSubscriptionsResponse()) + + await client.list_topic_subscriptions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'topic=topic/value', + ) in kw['metadata'] + + +def test_list_topic_subscriptions_flattened(): + client = PublisherClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_topic_subscriptions), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = pubsub.ListTopicSubscriptionsResponse() + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_topic_subscriptions( + topic='topic_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0].topic == 'topic_value' + + +def test_list_topic_subscriptions_flattened_error(): + client = PublisherClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_topic_subscriptions( + pubsub.ListTopicSubscriptionsRequest(), + topic='topic_value', + ) + + +@pytest.mark.asyncio +async def test_list_topic_subscriptions_flattened_async(): + client = PublisherAsyncClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_topic_subscriptions), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = pubsub.ListTopicSubscriptionsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(pubsub.ListTopicSubscriptionsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_topic_subscriptions( + topic='topic_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0].topic == 'topic_value' + + +@pytest.mark.asyncio +async def test_list_topic_subscriptions_flattened_error_async(): + client = PublisherAsyncClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_topic_subscriptions( + pubsub.ListTopicSubscriptionsRequest(), + topic='topic_value', + ) + + +def test_list_topic_subscriptions_pager(): + client = PublisherClient( + credentials=credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_topic_subscriptions), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + pubsub.ListTopicSubscriptionsResponse( + subscriptions=[ + str(), + str(), + str(), + ], + next_page_token='abc', + ), + pubsub.ListTopicSubscriptionsResponse( + subscriptions=[], + next_page_token='def', + ), + pubsub.ListTopicSubscriptionsResponse( + subscriptions=[ + str(), + ], + next_page_token='ghi', + ), + pubsub.ListTopicSubscriptionsResponse( + subscriptions=[ + str(), + str(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('topic', ''), + )), + ) + pager = client.list_topic_subscriptions(request={}) + + assert pager._metadata == metadata + + results = [i for i in pager] + assert len(results) == 6 + assert all(isinstance(i, str) + for i in results) + +def test_list_topic_subscriptions_pages(): + client = PublisherClient( + credentials=credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_topic_subscriptions), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + pubsub.ListTopicSubscriptionsResponse( + subscriptions=[ + str(), + str(), + str(), + ], + next_page_token='abc', + ), + pubsub.ListTopicSubscriptionsResponse( + subscriptions=[], + next_page_token='def', + ), + pubsub.ListTopicSubscriptionsResponse( + subscriptions=[ + str(), + ], + next_page_token='ghi', + ), + pubsub.ListTopicSubscriptionsResponse( + subscriptions=[ + str(), + str(), + ], + ), + RuntimeError, + ) + pages = list(client.list_topic_subscriptions(request={}).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +@pytest.mark.asyncio +async def test_list_topic_subscriptions_async_pager(): + client = PublisherAsyncClient( + credentials=credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_topic_subscriptions), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + pubsub.ListTopicSubscriptionsResponse( + subscriptions=[ + str(), + str(), + str(), + ], + next_page_token='abc', + ), + pubsub.ListTopicSubscriptionsResponse( + subscriptions=[], + next_page_token='def', + ), + pubsub.ListTopicSubscriptionsResponse( + subscriptions=[ + str(), + ], + next_page_token='ghi', + ), + pubsub.ListTopicSubscriptionsResponse( + subscriptions=[ + str(), + str(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_topic_subscriptions(request={},) + assert async_pager.next_page_token == 'abc' + responses = [] + async for response in async_pager: + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, str) + for i in responses) + +@pytest.mark.asyncio +async def test_list_topic_subscriptions_async_pages(): + client = PublisherAsyncClient( + credentials=credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_topic_subscriptions), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + pubsub.ListTopicSubscriptionsResponse( + subscriptions=[ + str(), + str(), + str(), + ], + next_page_token='abc', + ), + pubsub.ListTopicSubscriptionsResponse( + subscriptions=[], + next_page_token='def', + ), + pubsub.ListTopicSubscriptionsResponse( + subscriptions=[ + str(), + ], + next_page_token='ghi', + ), + pubsub.ListTopicSubscriptionsResponse( + subscriptions=[ + str(), + str(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.list_topic_subscriptions(request={})).pages: + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +def test_list_topic_snapshots(transport: str = 'grpc', request_type=pubsub.ListTopicSnapshotsRequest): + client = PublisherClient( + credentials=credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_topic_snapshots), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = pubsub.ListTopicSnapshotsResponse( + snapshots=['snapshots_value'], + + next_page_token='next_page_token_value', + + ) + + response = client.list_topic_snapshots(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == pubsub.ListTopicSnapshotsRequest() + + # Establish that the response is the type that we expect. + + assert isinstance(response, pagers.ListTopicSnapshotsPager) + + assert response.snapshots == ['snapshots_value'] + + assert response.next_page_token == 'next_page_token_value' + + +def test_list_topic_snapshots_from_dict(): + test_list_topic_snapshots(request_type=dict) + + +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', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_topic_snapshots), + '__call__') as call: + client.list_topic_snapshots() + call.assert_called() + _, args, _ = call.mock_calls[0] + + assert args[0] == pubsub.ListTopicSnapshotsRequest() + +@pytest.mark.asyncio +async def test_list_topic_snapshots_async(transport: str = 'grpc_asyncio', request_type=pubsub.ListTopicSnapshotsRequest): + client = PublisherAsyncClient( + credentials=credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_topic_snapshots), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(pubsub.ListTopicSnapshotsResponse( + snapshots=['snapshots_value'], + next_page_token='next_page_token_value', + )) + + response = await client.list_topic_snapshots(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == pubsub.ListTopicSnapshotsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListTopicSnapshotsAsyncPager) + + assert response.snapshots == ['snapshots_value'] + + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_topic_snapshots_async_from_dict(): + await test_list_topic_snapshots_async(request_type=dict) + + +def test_list_topic_snapshots_field_headers(): + client = PublisherClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = pubsub.ListTopicSnapshotsRequest() + request.topic = 'topic/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_topic_snapshots), + '__call__') as call: + call.return_value = pubsub.ListTopicSnapshotsResponse() + + client.list_topic_snapshots(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'topic=topic/value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_list_topic_snapshots_field_headers_async(): + client = PublisherAsyncClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = pubsub.ListTopicSnapshotsRequest() + request.topic = 'topic/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_topic_snapshots), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(pubsub.ListTopicSnapshotsResponse()) + + await client.list_topic_snapshots(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'topic=topic/value', + ) in kw['metadata'] + + +def test_list_topic_snapshots_flattened(): + client = PublisherClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_topic_snapshots), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = pubsub.ListTopicSnapshotsResponse() + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_topic_snapshots( + topic='topic_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0].topic == 'topic_value' + + +def test_list_topic_snapshots_flattened_error(): + client = PublisherClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_topic_snapshots( + pubsub.ListTopicSnapshotsRequest(), + topic='topic_value', + ) + + +@pytest.mark.asyncio +async def test_list_topic_snapshots_flattened_async(): + client = PublisherAsyncClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_topic_snapshots), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = pubsub.ListTopicSnapshotsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(pubsub.ListTopicSnapshotsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_topic_snapshots( + topic='topic_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0].topic == 'topic_value' + + +@pytest.mark.asyncio +async def test_list_topic_snapshots_flattened_error_async(): + client = PublisherAsyncClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_topic_snapshots( + pubsub.ListTopicSnapshotsRequest(), + topic='topic_value', + ) + + +def test_list_topic_snapshots_pager(): + client = PublisherClient( + credentials=credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_topic_snapshots), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + pubsub.ListTopicSnapshotsResponse( + snapshots=[ + str(), + str(), + str(), + ], + next_page_token='abc', + ), + pubsub.ListTopicSnapshotsResponse( + snapshots=[], + next_page_token='def', + ), + pubsub.ListTopicSnapshotsResponse( + snapshots=[ + str(), + ], + next_page_token='ghi', + ), + pubsub.ListTopicSnapshotsResponse( + snapshots=[ + str(), + str(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('topic', ''), + )), + ) + pager = client.list_topic_snapshots(request={}) + + assert pager._metadata == metadata + + results = [i for i in pager] + assert len(results) == 6 + assert all(isinstance(i, str) + for i in results) + +def test_list_topic_snapshots_pages(): + client = PublisherClient( + credentials=credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_topic_snapshots), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + pubsub.ListTopicSnapshotsResponse( + snapshots=[ + str(), + str(), + str(), + ], + next_page_token='abc', + ), + pubsub.ListTopicSnapshotsResponse( + snapshots=[], + next_page_token='def', + ), + pubsub.ListTopicSnapshotsResponse( + snapshots=[ + str(), + ], + next_page_token='ghi', + ), + pubsub.ListTopicSnapshotsResponse( + snapshots=[ + str(), + str(), + ], + ), + RuntimeError, + ) + pages = list(client.list_topic_snapshots(request={}).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +@pytest.mark.asyncio +async def test_list_topic_snapshots_async_pager(): + client = PublisherAsyncClient( + credentials=credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_topic_snapshots), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + pubsub.ListTopicSnapshotsResponse( + snapshots=[ + str(), + str(), + str(), + ], + next_page_token='abc', + ), + pubsub.ListTopicSnapshotsResponse( + snapshots=[], + next_page_token='def', + ), + pubsub.ListTopicSnapshotsResponse( + snapshots=[ + str(), + ], + next_page_token='ghi', + ), + pubsub.ListTopicSnapshotsResponse( + snapshots=[ + str(), + str(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_topic_snapshots(request={},) + assert async_pager.next_page_token == 'abc' + responses = [] + async for response in async_pager: + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, str) + for i in responses) + +@pytest.mark.asyncio +async def test_list_topic_snapshots_async_pages(): + client = PublisherAsyncClient( + credentials=credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_topic_snapshots), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + pubsub.ListTopicSnapshotsResponse( + snapshots=[ + str(), + str(), + str(), + ], + next_page_token='abc', + ), + pubsub.ListTopicSnapshotsResponse( + snapshots=[], + next_page_token='def', + ), + pubsub.ListTopicSnapshotsResponse( + snapshots=[ + str(), + ], + next_page_token='ghi', + ), + pubsub.ListTopicSnapshotsResponse( + snapshots=[ + str(), + str(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.list_topic_snapshots(request={})).pages: + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +def test_delete_topic(transport: str = 'grpc', request_type=pubsub.DeleteTopicRequest): + client = PublisherClient( + credentials=credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_topic), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + + response = client.delete_topic(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == pubsub.DeleteTopicRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_topic_from_dict(): + test_delete_topic(request_type=dict) + + +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', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_topic), + '__call__') as call: + client.delete_topic() + call.assert_called() + _, args, _ = call.mock_calls[0] + + assert args[0] == pubsub.DeleteTopicRequest() + +@pytest.mark.asyncio +async def test_delete_topic_async(transport: str = 'grpc_asyncio', request_type=pubsub.DeleteTopicRequest): + client = PublisherAsyncClient( + credentials=credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_topic), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + + response = await client.delete_topic(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == pubsub.DeleteTopicRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.asyncio +async def test_delete_topic_async_from_dict(): + await test_delete_topic_async(request_type=dict) + + +def test_delete_topic_field_headers(): + client = PublisherClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = pubsub.DeleteTopicRequest() + request.topic = 'topic/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_topic), + '__call__') as call: + call.return_value = None + + client.delete_topic(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'topic=topic/value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_delete_topic_field_headers_async(): + client = PublisherAsyncClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = pubsub.DeleteTopicRequest() + request.topic = 'topic/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_topic), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + + await client.delete_topic(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'topic=topic/value', + ) in kw['metadata'] + + +def test_delete_topic_flattened(): + client = PublisherClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_topic), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.delete_topic( + topic='topic_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0].topic == 'topic_value' + + +def test_delete_topic_flattened_error(): + client = PublisherClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_topic( + pubsub.DeleteTopicRequest(), + topic='topic_value', + ) + + +@pytest.mark.asyncio +async def test_delete_topic_flattened_async(): + client = PublisherAsyncClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_topic), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.delete_topic( + topic='topic_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0].topic == 'topic_value' + + +@pytest.mark.asyncio +async def test_delete_topic_flattened_error_async(): + client = PublisherAsyncClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.delete_topic( + pubsub.DeleteTopicRequest(), + topic='topic_value', + ) + + +def test_detach_subscription(transport: str = 'grpc', request_type=pubsub.DetachSubscriptionRequest): + client = PublisherClient( + credentials=credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.detach_subscription), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = pubsub.DetachSubscriptionResponse( + ) + + response = client.detach_subscription(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == pubsub.DetachSubscriptionRequest() + + # Establish that the response is the type that we expect. + + assert isinstance(response, pubsub.DetachSubscriptionResponse) + + +def test_detach_subscription_from_dict(): + test_detach_subscription(request_type=dict) + + +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', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.detach_subscription), + '__call__') as call: + client.detach_subscription() + call.assert_called() + _, args, _ = call.mock_calls[0] + + assert args[0] == pubsub.DetachSubscriptionRequest() + +@pytest.mark.asyncio +async def test_detach_subscription_async(transport: str = 'grpc_asyncio', request_type=pubsub.DetachSubscriptionRequest): + client = PublisherAsyncClient( + credentials=credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.detach_subscription), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(pubsub.DetachSubscriptionResponse( + )) + + response = await client.detach_subscription(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == pubsub.DetachSubscriptionRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pubsub.DetachSubscriptionResponse) + + +@pytest.mark.asyncio +async def test_detach_subscription_async_from_dict(): + await test_detach_subscription_async(request_type=dict) + + +def test_detach_subscription_field_headers(): + client = PublisherClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = pubsub.DetachSubscriptionRequest() + request.subscription = 'subscription/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.detach_subscription), + '__call__') as call: + call.return_value = pubsub.DetachSubscriptionResponse() + + client.detach_subscription(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'subscription=subscription/value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_detach_subscription_field_headers_async(): + client = PublisherAsyncClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = pubsub.DetachSubscriptionRequest() + request.subscription = 'subscription/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.detach_subscription), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(pubsub.DetachSubscriptionResponse()) + + await client.detach_subscription(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'subscription=subscription/value', + ) in kw['metadata'] + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.PublisherGrpcTransport( + credentials=credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = PublisherClient( + credentials=credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.PublisherGrpcTransport( + credentials=credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = PublisherClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.PublisherGrpcTransport( + credentials=credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = PublisherClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.PublisherGrpcTransport( + credentials=credentials.AnonymousCredentials(), + ) + client = PublisherClient(transport=transport) + assert client.transport is transport + + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.PublisherGrpcTransport( + credentials=credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.PublisherGrpcAsyncIOTransport( + credentials=credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + +@pytest.mark.parametrize("transport_class", [ + transports.PublisherGrpcTransport, + transports.PublisherGrpcAsyncIOTransport, +]) +def test_transport_adc(transport_class): + # Test default credentials are used if not provided. + with mock.patch.object(auth, 'default') as adc: + adc.return_value = (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(), + ) + 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): + transport = transports.PublisherTransport( + credentials=credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_publisher_base_transport(): + # Instantiate the base transport. + with mock.patch('google.pubsub_v1.services.publisher.transports.PublisherTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.PublisherTransport( + credentials=credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'create_topic', + 'update_topic', + 'publish', + 'get_topic', + 'list_topics', + 'list_topic_subscriptions', + 'list_topic_snapshots', + 'delete_topic', + 'detach_subscription', + 'set_iam_policy', + 'get_iam_policy', + 'test_iam_permissions', + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + +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') 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=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/pubsub', + ), + quota_project_id="octopus", + ) + + +def test_publisher_base_transport_with_adc(): + # Test the default credentials are used if credentials and credentials_file are None. + with mock.patch.object(auth, 'default') 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) + transport = transports.PublisherTransport() + adc.assert_called_once() + + +def test_publisher_auth_adc(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(auth, 'default') as adc: + adc.return_value = (credentials.AnonymousCredentials(), None) + PublisherClient() + adc.assert_called_once_with(scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/pubsub',), + quota_project_id=None, + ) + + +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') as adc: + adc.return_value = (credentials.AnonymousCredentials(), None) + transports.PublisherGrpcTransport(host="squid.clam.whelk", quota_project_id="octopus") + adc.assert_called_once_with(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]) +def test_publisher_grpc_transport_client_cert_source_for_mtls( + transport_class +): + cred = credentials.AnonymousCredentials() + + # Check ssl_channel_credentials is used if provided. + with mock.patch.object(transport_class, "create_channel") as mock_create_channel: + mock_ssl_channel_creds = mock.Mock() + transport_class( + host="squid.clam.whelk", + credentials=cred, + ssl_channel_credentials=mock_ssl_channel_creds + ) + mock_create_channel.assert_called_once_with( + "squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/pubsub', + ), + ssl_credentials=mock_ssl_channel_creds, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls + # is used. + with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): + with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: + transport_class( + credentials=cred, + client_cert_source_for_mtls=client_cert_source_callback + ) + expected_cert, expected_key = client_cert_source_callback() + mock_ssl_cred.assert_called_once_with( + certificate_chain=expected_cert, + private_key=expected_key + ) + + +def test_publisher_host_no_port(): + client = PublisherClient( + credentials=credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='pubsub.googleapis.com'), + ) + assert client.transport._host == 'pubsub.googleapis.com:443' + + +def test_publisher_host_with_port(): + client = PublisherClient( + credentials=credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='pubsub.googleapis.com:8000'), + ) + assert client.transport._host == 'pubsub.googleapis.com:8000' + + +def test_publisher_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.PublisherGrpcTransport( + host="squid.clam.whelk", + channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert transport._ssl_channel_credentials == None + + +def test_publisher_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.PublisherGrpcAsyncIOTransport( + host="squid.clam.whelk", + channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert transport._ssl_channel_credentials == None + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize("transport_class", [transports.PublisherGrpcTransport, transports.PublisherGrpcAsyncIOTransport]) +def test_publisher_transport_channel_mtls_with_client_cert_source( + transport_class +): + with mock.patch("grpc.ssl_channel_credentials", autospec=True) as grpc_ssl_channel_cred: + with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: + mock_ssl_cred = mock.Mock() + grpc_ssl_channel_cred.return_value = mock_ssl_cred + + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + + cred = credentials.AnonymousCredentials() + with pytest.warns(DeprecationWarning): + with mock.patch.object(auth, 'default') as adc: + adc.return_value = (cred, None) + transport = transport_class( + host="squid.clam.whelk", + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=client_cert_source_callback, + ) + adc.assert_called_once() + + grpc_ssl_channel_cred.assert_called_once_with( + certificate_chain=b"cert bytes", private_key=b"key bytes" + ) + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/pubsub', + ), + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + assert transport._ssl_channel_credentials == mock_ssl_cred + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize("transport_class", [transports.PublisherGrpcTransport, transports.PublisherGrpcAsyncIOTransport]) +def test_publisher_transport_channel_mtls_with_adc( + transport_class +): + mock_ssl_cred = mock.Mock() + with mock.patch.multiple( + "google.auth.transport.grpc.SslCredentials", + __init__=mock.Mock(return_value=None), + ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), + ): + with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + mock_cred = mock.Mock() + + with pytest.warns(DeprecationWarning): + transport = transport_class( + host="squid.clam.whelk", + credentials=mock_cred, + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=None, + ) + + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=mock_cred, + credentials_file=None, + scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/pubsub', + ), + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + + +def test_schema_path(): + project = "squid" + schema = "clam" + + expected = "projects/{project}/schemas/{schema}".format(project=project, schema=schema, ) + actual = PublisherClient.schema_path(project, schema) + assert expected == actual + + +def test_parse_schema_path(): + expected = { + "project": "whelk", + "schema": "octopus", + + } + path = PublisherClient.schema_path(**expected) + + # Check that the path construction is reversible. + actual = PublisherClient.parse_schema_path(path) + assert expected == actual + +def test_subscription_path(): + project = "oyster" + subscription = "nudibranch" + + expected = "projects/{project}/subscriptions/{subscription}".format(project=project, subscription=subscription, ) + actual = PublisherClient.subscription_path(project, subscription) + assert expected == actual + + +def test_parse_subscription_path(): + expected = { + "project": "cuttlefish", + "subscription": "mussel", + + } + path = PublisherClient.subscription_path(**expected) + + # Check that the path construction is reversible. + actual = PublisherClient.parse_subscription_path(path) + assert expected == actual + +def test_topic_path(): + project = "winkle" + topic = "nautilus" + + expected = "projects/{project}/topics/{topic}".format(project=project, topic=topic, ) + actual = PublisherClient.topic_path(project, topic) + assert expected == actual + + +def test_parse_topic_path(): + expected = { + "project": "scallop", + "topic": "abalone", + + } + path = PublisherClient.topic_path(**expected) + + # Check that the path construction is reversible. + actual = PublisherClient.parse_topic_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "squid" + + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = PublisherClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "clam", + + } + path = PublisherClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = PublisherClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "whelk" + + expected = "folders/{folder}".format(folder=folder, ) + actual = PublisherClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "octopus", + + } + path = PublisherClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = PublisherClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "oyster" + + expected = "organizations/{organization}".format(organization=organization, ) + actual = PublisherClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "nudibranch", + + } + path = PublisherClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = PublisherClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "cuttlefish" + + expected = "projects/{project}".format(project=project, ) + actual = PublisherClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "mussel", + + } + path = PublisherClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = PublisherClient.parse_common_project_path(path) + assert expected == actual + +def test_common_location_path(): + project = "winkle" + location = "nautilus" + + expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) + actual = PublisherClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "scallop", + "location": "abalone", + + } + path = PublisherClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = PublisherClient.parse_common_location_path(path) + assert expected == actual + + +def test_client_withDEFAULT_CLIENT_INFO(): + client_info = gapic_v1.client_info.ClientInfo() + + with mock.patch.object(transports.PublisherTransport, '_prep_wrapped_messages') as prep: + client = PublisherClient( + credentials=credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.PublisherTransport, '_prep_wrapped_messages') as prep: + transport_class = PublisherClient.get_transport_class() + transport = transport_class( + credentials=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, + ) + + # Everything is optional 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() + + # 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",) + + response = client.set_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, policy.Policy) + + assert response.version == 774 + + assert response.etag == b"etag_blob" + + +@pytest.mark.asyncio +async def test_set_iam_policy_async(transport: str = "grpc_asyncio"): + client = PublisherAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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() + + # 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",) + ) + + response = await client.set_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, policy.Policy) + + assert response.version == 774 + + assert response.etag == b"etag_blob" + + +def test_set_iam_policy_field_headers(): + client = PublisherClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Any value 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.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() + + client.set_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_set_iam_policy_field_headers_async(): + client = PublisherAsyncClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Any value 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.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()) + + await client.set_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] + + +def test_set_iam_policy_from_dict(): + client = PublisherClient( + credentials=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() + + response = client.set_iam_policy( + request={ + "resource": "resource_value", + "policy": policy.Policy(version=774), + } + ) + call.assert_called() + + +@pytest.mark.asyncio +async def test_set_iam_policy_from_dict_async(): + client = PublisherAsyncClient( + credentials=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() + ) + + response = await client.set_iam_policy( + request={ + "resource": "resource_value", + "policy": policy.Policy(version=774), + } + ) + call.assert_called() + + +def test_get_iam_policy(transport: str = "grpc"): + client = PublisherClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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() + + # 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",) + + response = client.get_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, policy.Policy) + + assert response.version == 774 + + assert response.etag == b"etag_blob" + + +@pytest.mark.asyncio +async def test_get_iam_policy_async(transport: str = "grpc_asyncio"): + client = PublisherAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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() + + # 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",) + ) + + response = await client.get_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, policy.Policy) + + assert response.version == 774 + + assert response.etag == b"etag_blob" + + +def test_get_iam_policy_field_headers(): + client = PublisherClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Any value 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.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() + + client.get_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_get_iam_policy_field_headers_async(): + client = PublisherAsyncClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Any value 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.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()) + + await client.get_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] + + +def test_get_iam_policy_from_dict(): + client = PublisherClient( + credentials=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() + + response = client.get_iam_policy( + request={ + "resource": "resource_value", + "options": options.GetPolicyOptions(requested_policy_version=2598), + } + ) + call.assert_called() + +@pytest.mark.asyncio +async def test_get_iam_policy_from_dict_async(): + client = PublisherAsyncClient( + credentials=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() + ) + + response = await client.get_iam_policy( + request={ + "resource": "resource_value", + "options": options.GetPolicyOptions(requested_policy_version=2598), + } + ) + call.assert_called() + + +def test_test_iam_permissions(transport: str = "grpc"): + client = PublisherClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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() + + # 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( + permissions=["permissions_value"], + ) + + response = client.test_iam_permissions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, iam_policy.TestIamPermissionsResponse) + + assert response.permissions == ["permissions_value"] + + +@pytest.mark.asyncio +async def test_test_iam_permissions_async(transport: str = "grpc_asyncio"): + client = PublisherAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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() + + # 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(permissions=["permissions_value"],) + ) + + response = await client.test_iam_permissions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, iam_policy.TestIamPermissionsResponse) + + assert response.permissions == ["permissions_value"] + + +def test_test_iam_permissions_field_headers(): + client = PublisherClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Any value 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.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() + + client.test_iam_permissions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_test_iam_permissions_field_headers_async(): + client = PublisherAsyncClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Any value 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.resource = "resource/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + iam_policy.TestIamPermissionsResponse() + ) + + await client.test_iam_permissions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] + + +def test_test_iam_permissions_from_dict(): + client = PublisherClient( + credentials=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() + + response = client.test_iam_permissions( + request={ + "resource": "resource_value", + "permissions": ["permissions_value"], + } + ) + call.assert_called() + +@pytest.mark.asyncio +async def test_test_iam_permissions_from_dict_async(): + client = PublisherAsyncClient( + credentials=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() + ) + + response = await client.test_iam_permissions( + request={ + "resource": "resource_value", + "permissions": ["permissions_value"], + } + ) + call.assert_called() diff --git a/owl-bot-staging/v1/tests/unit/gapic/pubsub_v1/test_schema_service.py b/owl-bot-staging/v1/tests/unit/gapic/pubsub_v1/test_schema_service.py new file mode 100644 index 000000000..400aa87f6 --- /dev/null +++ b/owl-bot-staging/v1/tests/unit/gapic/pubsub_v1/test_schema_service.py @@ -0,0 +1,2900 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +import os +import mock + +import grpc +from grpc.experimental import aio +import math +import pytest +from proto.marshal.rules.dates import DurationRule, TimestampRule + +from google import auth +from google.api_core import client_options +from google.api_core import 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.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.oauth2 import service_account +from google.pubsub_v1.services.schema_service import SchemaServiceAsyncClient +from google.pubsub_v1.services.schema_service import SchemaServiceClient +from google.pubsub_v1.services.schema_service import pagers +from google.pubsub_v1.services.schema_service import transports +from google.pubsub_v1.types import schema +from google.pubsub_v1.types import schema as gp_schema + + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + + assert SchemaServiceClient._get_default_mtls_endpoint(None) is None + assert SchemaServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert SchemaServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert SchemaServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert SchemaServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert SchemaServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + + +@pytest.mark.parametrize("client_class", [ + SchemaServiceClient, + SchemaServiceAsyncClient, +]) +def test_schema_service_client_from_service_account_info(client_class): + creds = credentials.AnonymousCredentials() + with mock.patch.object(service_account.Credentials, 'from_service_account_info') as factory: + factory.return_value = creds + info = {"valid": True} + client = client_class.from_service_account_info(info) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == 'pubsub.googleapis.com:443' + + +@pytest.mark.parametrize("client_class", [ + SchemaServiceClient, + SchemaServiceAsyncClient, +]) +def test_schema_service_client_from_service_account_file(client_class): + creds = credentials.AnonymousCredentials() + with mock.patch.object(service_account.Credentials, 'from_service_account_file') as factory: + factory.return_value = creds + client = client_class.from_service_account_file("dummy/file/path.json") + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + client = client_class.from_service_account_json("dummy/file/path.json") + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == 'pubsub.googleapis.com:443' + + +def test_schema_service_client_get_transport_class(): + transport = SchemaServiceClient.get_transport_class() + available_transports = [ + transports.SchemaServiceGrpcTransport, + ] + assert transport in available_transports + + transport = SchemaServiceClient.get_transport_class("grpc") + assert transport == transports.SchemaServiceGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (SchemaServiceClient, transports.SchemaServiceGrpcTransport, "grpc"), + (SchemaServiceAsyncClient, transports.SchemaServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +@mock.patch.object(SchemaServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SchemaServiceClient)) +@mock.patch.object(SchemaServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SchemaServiceAsyncClient)) +def test_schema_service_client_client_options(client_class, transport_class, transport_name): + # Check that if channel is provided we won't create a new one. + with mock.patch.object(SchemaServiceClient, 'get_transport_class') as gtc: + transport = transport_class( + credentials=credentials.AnonymousCredentials() + ) + client = client_class(transport=transport) + gtc.assert_not_called() + + # Check that if channel is provided via str we will create a new one. + with mock.patch.object(SchemaServiceClient, 'get_transport_class') as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check the case api_endpoint is provided. + options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError): + client = client_class() + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError): + client = client_class() + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ + + (SchemaServiceClient, transports.SchemaServiceGrpcTransport, "grpc", "true"), + (SchemaServiceAsyncClient, transports.SchemaServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (SchemaServiceClient, transports.SchemaServiceGrpcTransport, "grpc", "false"), + (SchemaServiceAsyncClient, transports.SchemaServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), + +]) +@mock.patch.object(SchemaServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SchemaServiceClient)) +@mock.patch.object(SchemaServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SchemaServiceAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_schema_service_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): + # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default + # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. + + # Check the case client_cert_source is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options) + + if use_client_cert_env == "false": + expected_client_cert_source = None + expected_host = client.DEFAULT_ENDPOINT + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): + if use_client_cert_env == "false": + expected_host = client.DEFAULT_ENDPOINT + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (SchemaServiceClient, transports.SchemaServiceGrpcTransport, "grpc"), + (SchemaServiceAsyncClient, transports.SchemaServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_schema_service_client_client_options_scopes(client_class, transport_class, transport_name): + # Check the case scopes are provided. + options = client_options.ClientOptions( + scopes=["1", "2"], + ) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=["1", "2"], + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (SchemaServiceClient, transports.SchemaServiceGrpcTransport, "grpc"), + (SchemaServiceAsyncClient, transports.SchemaServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_schema_service_client_client_options_credentials_file(client_class, transport_class, transport_name): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + +def test_schema_service_client_client_options_from_dict(): + with mock.patch('google.pubsub_v1.services.schema_service.transports.SchemaServiceGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = SchemaServiceClient( + client_options={'api_endpoint': 'squid.clam.whelk'} + ) + grpc_transport.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + +def test_create_schema(transport: str = 'grpc', request_type=gp_schema.CreateSchemaRequest): + client = SchemaServiceClient( + credentials=credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_schema), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gp_schema.Schema( + name='name_value', + + type_=gp_schema.Schema.Type.PROTOCOL_BUFFER, + + definition='definition_value', + + ) + + response = client.create_schema(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == gp_schema.CreateSchemaRequest() + + # Establish that the response is the type that we expect. + + assert isinstance(response, gp_schema.Schema) + + assert response.name == 'name_value' + + assert response.type_ == gp_schema.Schema.Type.PROTOCOL_BUFFER + + assert response.definition == 'definition_value' + + +def test_create_schema_from_dict(): + test_create_schema(request_type=dict) + + +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', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_schema), + '__call__') as call: + client.create_schema() + call.assert_called() + _, args, _ = call.mock_calls[0] + + assert args[0] == gp_schema.CreateSchemaRequest() + +@pytest.mark.asyncio +async def test_create_schema_async(transport: str = 'grpc_asyncio', request_type=gp_schema.CreateSchemaRequest): + client = SchemaServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_schema), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gp_schema.Schema( + name='name_value', + type_=gp_schema.Schema.Type.PROTOCOL_BUFFER, + definition='definition_value', + )) + + response = await client.create_schema(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == gp_schema.CreateSchemaRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gp_schema.Schema) + + assert response.name == 'name_value' + + assert response.type_ == gp_schema.Schema.Type.PROTOCOL_BUFFER + + assert response.definition == 'definition_value' + + +@pytest.mark.asyncio +async def test_create_schema_async_from_dict(): + await test_create_schema_async(request_type=dict) + + +def test_create_schema_field_headers(): + client = SchemaServiceClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gp_schema.CreateSchemaRequest() + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_schema), + '__call__') as call: + call.return_value = gp_schema.Schema() + + client.create_schema(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent/value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_create_schema_field_headers_async(): + client = SchemaServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gp_schema.CreateSchemaRequest() + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_schema), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gp_schema.Schema()) + + await client.create_schema(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent/value', + ) in kw['metadata'] + + +def test_create_schema_flattened(): + client = SchemaServiceClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_schema), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gp_schema.Schema() + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_schema( + parent='parent_value', + schema=gp_schema.Schema(name='name_value'), + schema_id='schema_id_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + 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(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.create_schema( + gp_schema.CreateSchemaRequest(), + parent='parent_value', + schema=gp_schema.Schema(name='name_value'), + schema_id='schema_id_value', + ) + + +@pytest.mark.asyncio +async def test_create_schema_flattened_async(): + client = SchemaServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_schema), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gp_schema.Schema() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gp_schema.Schema()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_schema( + parent='parent_value', + schema=gp_schema.Schema(name='name_value'), + schema_id='schema_id_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + 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(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.create_schema( + gp_schema.CreateSchemaRequest(), + parent='parent_value', + schema=gp_schema.Schema(name='name_value'), + schema_id='schema_id_value', + ) + + +def test_get_schema(transport: str = 'grpc', request_type=schema.GetSchemaRequest): + client = SchemaServiceClient( + credentials=credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_schema), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = schema.Schema( + name='name_value', + + type_=schema.Schema.Type.PROTOCOL_BUFFER, + + definition='definition_value', + + ) + + response = client.get_schema(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == schema.GetSchemaRequest() + + # Establish that the response is the type that we expect. + + assert isinstance(response, schema.Schema) + + assert response.name == 'name_value' + + assert response.type_ == schema.Schema.Type.PROTOCOL_BUFFER + + assert response.definition == 'definition_value' + + +def test_get_schema_from_dict(): + test_get_schema(request_type=dict) + + +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', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_schema), + '__call__') as call: + client.get_schema() + call.assert_called() + _, args, _ = call.mock_calls[0] + + assert args[0] == schema.GetSchemaRequest() + +@pytest.mark.asyncio +async def test_get_schema_async(transport: str = 'grpc_asyncio', request_type=schema.GetSchemaRequest): + client = SchemaServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_schema), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(schema.Schema( + name='name_value', + type_=schema.Schema.Type.PROTOCOL_BUFFER, + definition='definition_value', + )) + + response = await client.get_schema(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == schema.GetSchemaRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, schema.Schema) + + assert response.name == 'name_value' + + assert response.type_ == schema.Schema.Type.PROTOCOL_BUFFER + + assert response.definition == 'definition_value' + + +@pytest.mark.asyncio +async def test_get_schema_async_from_dict(): + await test_get_schema_async(request_type=dict) + + +def test_get_schema_field_headers(): + client = SchemaServiceClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = schema.GetSchemaRequest() + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_schema), + '__call__') as call: + call.return_value = schema.Schema() + + client.get_schema(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name/value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_get_schema_field_headers_async(): + client = SchemaServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = schema.GetSchemaRequest() + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_schema), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(schema.Schema()) + + await client.get_schema(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name/value', + ) in kw['metadata'] + + +def test_get_schema_flattened(): + client = SchemaServiceClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_schema), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = schema.Schema() + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_schema( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0].name == 'name_value' + + +def test_get_schema_flattened_error(): + client = SchemaServiceClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_schema( + schema.GetSchemaRequest(), + name='name_value', + ) + + +@pytest.mark.asyncio +async def test_get_schema_flattened_async(): + client = SchemaServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_schema), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = schema.Schema() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(schema.Schema()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_schema( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0].name == 'name_value' + + +@pytest.mark.asyncio +async def test_get_schema_flattened_error_async(): + client = SchemaServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_schema( + schema.GetSchemaRequest(), + name='name_value', + ) + + +def test_list_schemas(transport: str = 'grpc', request_type=schema.ListSchemasRequest): + client = SchemaServiceClient( + credentials=credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_schemas), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = schema.ListSchemasResponse( + next_page_token='next_page_token_value', + + ) + + response = client.list_schemas(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == schema.ListSchemasRequest() + + # Establish that the response is the type that we expect. + + assert isinstance(response, pagers.ListSchemasPager) + + assert response.next_page_token == 'next_page_token_value' + + +def test_list_schemas_from_dict(): + test_list_schemas(request_type=dict) + + +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', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_schemas), + '__call__') as call: + client.list_schemas() + call.assert_called() + _, args, _ = call.mock_calls[0] + + assert args[0] == schema.ListSchemasRequest() + +@pytest.mark.asyncio +async def test_list_schemas_async(transport: str = 'grpc_asyncio', request_type=schema.ListSchemasRequest): + client = SchemaServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_schemas), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(schema.ListSchemasResponse( + next_page_token='next_page_token_value', + )) + + response = await client.list_schemas(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == schema.ListSchemasRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListSchemasAsyncPager) + + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_schemas_async_from_dict(): + await test_list_schemas_async(request_type=dict) + + +def test_list_schemas_field_headers(): + client = SchemaServiceClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = schema.ListSchemasRequest() + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_schemas), + '__call__') as call: + call.return_value = schema.ListSchemasResponse() + + client.list_schemas(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent/value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_list_schemas_field_headers_async(): + client = SchemaServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = schema.ListSchemasRequest() + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_schemas), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(schema.ListSchemasResponse()) + + await client.list_schemas(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent/value', + ) in kw['metadata'] + + +def test_list_schemas_flattened(): + client = SchemaServiceClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_schemas), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = schema.ListSchemasResponse() + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_schemas( + parent='parent_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0].parent == 'parent_value' + + +def test_list_schemas_flattened_error(): + client = SchemaServiceClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_schemas( + schema.ListSchemasRequest(), + parent='parent_value', + ) + + +@pytest.mark.asyncio +async def test_list_schemas_flattened_async(): + client = SchemaServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_schemas), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = schema.ListSchemasResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(schema.ListSchemasResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_schemas( + parent='parent_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0].parent == 'parent_value' + + +@pytest.mark.asyncio +async def test_list_schemas_flattened_error_async(): + client = SchemaServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_schemas( + schema.ListSchemasRequest(), + parent='parent_value', + ) + + +def test_list_schemas_pager(): + client = SchemaServiceClient( + credentials=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: + # Set the response to a series of pages. + call.side_effect = ( + schema.ListSchemasResponse( + schemas=[ + schema.Schema(), + schema.Schema(), + schema.Schema(), + ], + next_page_token='abc', + ), + schema.ListSchemasResponse( + schemas=[], + next_page_token='def', + ), + schema.ListSchemasResponse( + schemas=[ + schema.Schema(), + ], + next_page_token='ghi', + ), + schema.ListSchemasResponse( + schemas=[ + schema.Schema(), + schema.Schema(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_schemas(request={}) + + assert pager._metadata == metadata + + results = [i for i in pager] + assert len(results) == 6 + assert all(isinstance(i, schema.Schema) + for i in results) + +def test_list_schemas_pages(): + client = SchemaServiceClient( + credentials=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: + # Set the response to a series of pages. + call.side_effect = ( + schema.ListSchemasResponse( + schemas=[ + schema.Schema(), + schema.Schema(), + schema.Schema(), + ], + next_page_token='abc', + ), + schema.ListSchemasResponse( + schemas=[], + next_page_token='def', + ), + schema.ListSchemasResponse( + schemas=[ + schema.Schema(), + ], + next_page_token='ghi', + ), + schema.ListSchemasResponse( + schemas=[ + schema.Schema(), + schema.Schema(), + ], + ), + RuntimeError, + ) + pages = list(client.list_schemas(request={}).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +@pytest.mark.asyncio +async def test_list_schemas_async_pager(): + client = SchemaServiceAsyncClient( + credentials=credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_schemas), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + schema.ListSchemasResponse( + schemas=[ + schema.Schema(), + schema.Schema(), + schema.Schema(), + ], + next_page_token='abc', + ), + schema.ListSchemasResponse( + schemas=[], + next_page_token='def', + ), + schema.ListSchemasResponse( + schemas=[ + schema.Schema(), + ], + next_page_token='ghi', + ), + schema.ListSchemasResponse( + schemas=[ + schema.Schema(), + schema.Schema(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_schemas(request={},) + assert async_pager.next_page_token == 'abc' + responses = [] + async for response in async_pager: + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, schema.Schema) + for i in responses) + +@pytest.mark.asyncio +async def test_list_schemas_async_pages(): + client = SchemaServiceAsyncClient( + credentials=credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_schemas), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + schema.ListSchemasResponse( + schemas=[ + schema.Schema(), + schema.Schema(), + schema.Schema(), + ], + next_page_token='abc', + ), + schema.ListSchemasResponse( + schemas=[], + next_page_token='def', + ), + schema.ListSchemasResponse( + schemas=[ + schema.Schema(), + ], + next_page_token='ghi', + ), + schema.ListSchemasResponse( + schemas=[ + schema.Schema(), + schema.Schema(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.list_schemas(request={})).pages: + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +def test_delete_schema(transport: str = 'grpc', request_type=schema.DeleteSchemaRequest): + client = SchemaServiceClient( + credentials=credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_schema), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + + response = client.delete_schema(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == schema.DeleteSchemaRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_schema_from_dict(): + test_delete_schema(request_type=dict) + + +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', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_schema), + '__call__') as call: + client.delete_schema() + call.assert_called() + _, args, _ = call.mock_calls[0] + + assert args[0] == schema.DeleteSchemaRequest() + +@pytest.mark.asyncio +async def test_delete_schema_async(transport: str = 'grpc_asyncio', request_type=schema.DeleteSchemaRequest): + client = SchemaServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_schema), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + + response = await client.delete_schema(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == schema.DeleteSchemaRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.asyncio +async def test_delete_schema_async_from_dict(): + await test_delete_schema_async(request_type=dict) + + +def test_delete_schema_field_headers(): + client = SchemaServiceClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = schema.DeleteSchemaRequest() + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_schema), + '__call__') as call: + call.return_value = None + + client.delete_schema(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name/value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_delete_schema_field_headers_async(): + client = SchemaServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = schema.DeleteSchemaRequest() + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_schema), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + + await client.delete_schema(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name/value', + ) in kw['metadata'] + + +def test_delete_schema_flattened(): + client = SchemaServiceClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_schema), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.delete_schema( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0].name == 'name_value' + + +def test_delete_schema_flattened_error(): + client = SchemaServiceClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_schema( + schema.DeleteSchemaRequest(), + name='name_value', + ) + + +@pytest.mark.asyncio +async def test_delete_schema_flattened_async(): + client = SchemaServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_schema), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.delete_schema( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0].name == 'name_value' + + +@pytest.mark.asyncio +async def test_delete_schema_flattened_error_async(): + client = SchemaServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.delete_schema( + schema.DeleteSchemaRequest(), + name='name_value', + ) + + +def test_validate_schema(transport: str = 'grpc', request_type=gp_schema.ValidateSchemaRequest): + client = SchemaServiceClient( + credentials=credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.validate_schema), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gp_schema.ValidateSchemaResponse( + ) + + response = client.validate_schema(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == gp_schema.ValidateSchemaRequest() + + # Establish that the response is the type that we expect. + + assert isinstance(response, gp_schema.ValidateSchemaResponse) + + +def test_validate_schema_from_dict(): + test_validate_schema(request_type=dict) + + +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', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.validate_schema), + '__call__') as call: + client.validate_schema() + call.assert_called() + _, args, _ = call.mock_calls[0] + + assert args[0] == gp_schema.ValidateSchemaRequest() + +@pytest.mark.asyncio +async def test_validate_schema_async(transport: str = 'grpc_asyncio', request_type=gp_schema.ValidateSchemaRequest): + client = SchemaServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.validate_schema), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gp_schema.ValidateSchemaResponse( + )) + + response = await client.validate_schema(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == gp_schema.ValidateSchemaRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gp_schema.ValidateSchemaResponse) + + +@pytest.mark.asyncio +async def test_validate_schema_async_from_dict(): + await test_validate_schema_async(request_type=dict) + + +def test_validate_schema_field_headers(): + client = SchemaServiceClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gp_schema.ValidateSchemaRequest() + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.validate_schema), + '__call__') as call: + call.return_value = gp_schema.ValidateSchemaResponse() + + client.validate_schema(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent/value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_validate_schema_field_headers_async(): + client = SchemaServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gp_schema.ValidateSchemaRequest() + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.validate_schema), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gp_schema.ValidateSchemaResponse()) + + await client.validate_schema(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent/value', + ) in kw['metadata'] + + +def test_validate_schema_flattened(): + client = SchemaServiceClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.validate_schema), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gp_schema.ValidateSchemaResponse() + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.validate_schema( + parent='parent_value', + schema=gp_schema.Schema(name='name_value'), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + 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(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.validate_schema( + gp_schema.ValidateSchemaRequest(), + parent='parent_value', + schema=gp_schema.Schema(name='name_value'), + ) + + +@pytest.mark.asyncio +async def test_validate_schema_flattened_async(): + client = SchemaServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.validate_schema), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gp_schema.ValidateSchemaResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gp_schema.ValidateSchemaResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.validate_schema( + parent='parent_value', + schema=gp_schema.Schema(name='name_value'), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + 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(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.validate_schema( + gp_schema.ValidateSchemaRequest(), + parent='parent_value', + schema=gp_schema.Schema(name='name_value'), + ) + + +def test_validate_message(transport: str = 'grpc', request_type=schema.ValidateMessageRequest): + client = SchemaServiceClient( + credentials=credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.validate_message), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = schema.ValidateMessageResponse( + ) + + response = client.validate_message(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == schema.ValidateMessageRequest() + + # Establish that the response is the type that we expect. + + assert isinstance(response, schema.ValidateMessageResponse) + + +def test_validate_message_from_dict(): + test_validate_message(request_type=dict) + + +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', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.validate_message), + '__call__') as call: + client.validate_message() + call.assert_called() + _, args, _ = call.mock_calls[0] + + assert args[0] == schema.ValidateMessageRequest() + +@pytest.mark.asyncio +async def test_validate_message_async(transport: str = 'grpc_asyncio', request_type=schema.ValidateMessageRequest): + client = SchemaServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.validate_message), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(schema.ValidateMessageResponse( + )) + + response = await client.validate_message(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == schema.ValidateMessageRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, schema.ValidateMessageResponse) + + +@pytest.mark.asyncio +async def test_validate_message_async_from_dict(): + await test_validate_message_async(request_type=dict) + + +def test_validate_message_field_headers(): + client = SchemaServiceClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = schema.ValidateMessageRequest() + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.validate_message), + '__call__') as call: + call.return_value = schema.ValidateMessageResponse() + + client.validate_message(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent/value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_validate_message_field_headers_async(): + client = SchemaServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = schema.ValidateMessageRequest() + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.validate_message), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(schema.ValidateMessageResponse()) + + await client.validate_message(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent/value', + ) in kw['metadata'] + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.SchemaServiceGrpcTransport( + credentials=credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = SchemaServiceClient( + credentials=credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.SchemaServiceGrpcTransport( + credentials=credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = SchemaServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.SchemaServiceGrpcTransport( + credentials=credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = SchemaServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.SchemaServiceGrpcTransport( + credentials=credentials.AnonymousCredentials(), + ) + client = SchemaServiceClient(transport=transport) + assert client.transport is transport + + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.SchemaServiceGrpcTransport( + credentials=credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.SchemaServiceGrpcAsyncIOTransport( + credentials=credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + +@pytest.mark.parametrize("transport_class", [ + transports.SchemaServiceGrpcTransport, + transports.SchemaServiceGrpcAsyncIOTransport, +]) +def test_transport_adc(transport_class): + # Test default credentials are used if not provided. + with mock.patch.object(auth, 'default') as adc: + adc.return_value = (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(), + ) + 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): + transport = transports.SchemaServiceTransport( + credentials=credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_schema_service_base_transport(): + # Instantiate the base transport. + with mock.patch('google.pubsub_v1.services.schema_service.transports.SchemaServiceTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.SchemaServiceTransport( + credentials=credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'create_schema', + 'get_schema', + 'list_schemas', + 'delete_schema', + 'validate_schema', + 'validate_message', + 'set_iam_policy', + 'get_iam_policy', + 'test_iam_permissions', + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + +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') 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=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/pubsub', + ), + quota_project_id="octopus", + ) + + +def test_schema_service_base_transport_with_adc(): + # Test the default credentials are used if credentials and credentials_file are None. + with mock.patch.object(auth, 'default') 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) + transport = transports.SchemaServiceTransport() + adc.assert_called_once() + + +def test_schema_service_auth_adc(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(auth, 'default') as adc: + adc.return_value = (credentials.AnonymousCredentials(), None) + SchemaServiceClient() + adc.assert_called_once_with(scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/pubsub',), + quota_project_id=None, + ) + + +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') as adc: + adc.return_value = (credentials.AnonymousCredentials(), None) + transports.SchemaServiceGrpcTransport(host="squid.clam.whelk", quota_project_id="octopus") + adc.assert_called_once_with(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]) +def test_schema_service_grpc_transport_client_cert_source_for_mtls( + transport_class +): + cred = credentials.AnonymousCredentials() + + # Check ssl_channel_credentials is used if provided. + with mock.patch.object(transport_class, "create_channel") as mock_create_channel: + mock_ssl_channel_creds = mock.Mock() + transport_class( + host="squid.clam.whelk", + credentials=cred, + ssl_channel_credentials=mock_ssl_channel_creds + ) + mock_create_channel.assert_called_once_with( + "squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/pubsub', + ), + ssl_credentials=mock_ssl_channel_creds, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls + # is used. + with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): + with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: + transport_class( + credentials=cred, + client_cert_source_for_mtls=client_cert_source_callback + ) + expected_cert, expected_key = client_cert_source_callback() + mock_ssl_cred.assert_called_once_with( + certificate_chain=expected_cert, + private_key=expected_key + ) + + +def test_schema_service_host_no_port(): + client = SchemaServiceClient( + credentials=credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='pubsub.googleapis.com'), + ) + assert client.transport._host == 'pubsub.googleapis.com:443' + + +def test_schema_service_host_with_port(): + client = SchemaServiceClient( + credentials=credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='pubsub.googleapis.com:8000'), + ) + assert client.transport._host == 'pubsub.googleapis.com:8000' + + +def test_schema_service_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.SchemaServiceGrpcTransport( + host="squid.clam.whelk", + channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert transport._ssl_channel_credentials == None + + +def test_schema_service_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.SchemaServiceGrpcAsyncIOTransport( + host="squid.clam.whelk", + channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert transport._ssl_channel_credentials == None + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize("transport_class", [transports.SchemaServiceGrpcTransport, transports.SchemaServiceGrpcAsyncIOTransport]) +def test_schema_service_transport_channel_mtls_with_client_cert_source( + transport_class +): + with mock.patch("grpc.ssl_channel_credentials", autospec=True) as grpc_ssl_channel_cred: + with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: + mock_ssl_cred = mock.Mock() + grpc_ssl_channel_cred.return_value = mock_ssl_cred + + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + + cred = credentials.AnonymousCredentials() + with pytest.warns(DeprecationWarning): + with mock.patch.object(auth, 'default') as adc: + adc.return_value = (cred, None) + transport = transport_class( + host="squid.clam.whelk", + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=client_cert_source_callback, + ) + adc.assert_called_once() + + grpc_ssl_channel_cred.assert_called_once_with( + certificate_chain=b"cert bytes", private_key=b"key bytes" + ) + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/pubsub', + ), + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + assert transport._ssl_channel_credentials == mock_ssl_cred + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize("transport_class", [transports.SchemaServiceGrpcTransport, transports.SchemaServiceGrpcAsyncIOTransport]) +def test_schema_service_transport_channel_mtls_with_adc( + transport_class +): + mock_ssl_cred = mock.Mock() + with mock.patch.multiple( + "google.auth.transport.grpc.SslCredentials", + __init__=mock.Mock(return_value=None), + ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), + ): + with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + mock_cred = mock.Mock() + + with pytest.warns(DeprecationWarning): + transport = transport_class( + host="squid.clam.whelk", + credentials=mock_cred, + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=None, + ) + + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=mock_cred, + credentials_file=None, + scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/pubsub', + ), + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + + +def test_schema_path(): + project = "squid" + schema = "clam" + + expected = "projects/{project}/schemas/{schema}".format(project=project, schema=schema, ) + actual = SchemaServiceClient.schema_path(project, schema) + assert expected == actual + + +def test_parse_schema_path(): + expected = { + "project": "whelk", + "schema": "octopus", + + } + path = SchemaServiceClient.schema_path(**expected) + + # Check that the path construction is reversible. + actual = SchemaServiceClient.parse_schema_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "oyster" + + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = SchemaServiceClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "nudibranch", + + } + path = SchemaServiceClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = SchemaServiceClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "cuttlefish" + + expected = "folders/{folder}".format(folder=folder, ) + actual = SchemaServiceClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "mussel", + + } + path = SchemaServiceClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = SchemaServiceClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "winkle" + + expected = "organizations/{organization}".format(organization=organization, ) + actual = SchemaServiceClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "nautilus", + + } + path = SchemaServiceClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = SchemaServiceClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "scallop" + + expected = "projects/{project}".format(project=project, ) + actual = SchemaServiceClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "abalone", + + } + path = SchemaServiceClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = SchemaServiceClient.parse_common_project_path(path) + assert expected == actual + +def test_common_location_path(): + project = "squid" + location = "clam" + + expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) + actual = SchemaServiceClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "whelk", + "location": "octopus", + + } + path = SchemaServiceClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = SchemaServiceClient.parse_common_location_path(path) + assert expected == actual + + +def test_client_withDEFAULT_CLIENT_INFO(): + client_info = gapic_v1.client_info.ClientInfo() + + with mock.patch.object(transports.SchemaServiceTransport, '_prep_wrapped_messages') as prep: + client = SchemaServiceClient( + credentials=credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.SchemaServiceTransport, '_prep_wrapped_messages') as prep: + transport_class = SchemaServiceClient.get_transport_class() + transport = transport_class( + credentials=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, + ) + + # Everything is optional 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() + + # 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",) + + response = client.set_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, policy.Policy) + + assert response.version == 774 + + assert response.etag == b"etag_blob" + + +@pytest.mark.asyncio +async def test_set_iam_policy_async(transport: str = "grpc_asyncio"): + client = SchemaServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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() + + # 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",) + ) + + response = await client.set_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, policy.Policy) + + assert response.version == 774 + + assert response.etag == b"etag_blob" + + +def test_set_iam_policy_field_headers(): + client = SchemaServiceClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Any value 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.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() + + client.set_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_set_iam_policy_field_headers_async(): + client = SchemaServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Any value 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.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()) + + await client.set_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] + + +def test_set_iam_policy_from_dict(): + client = SchemaServiceClient( + credentials=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() + + response = client.set_iam_policy( + request={ + "resource": "resource_value", + "policy": policy.Policy(version=774), + } + ) + call.assert_called() + + +@pytest.mark.asyncio +async def test_set_iam_policy_from_dict_async(): + client = SchemaServiceAsyncClient( + credentials=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() + ) + + response = await client.set_iam_policy( + request={ + "resource": "resource_value", + "policy": policy.Policy(version=774), + } + ) + call.assert_called() + + +def test_get_iam_policy(transport: str = "grpc"): + client = SchemaServiceClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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() + + # 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",) + + response = client.get_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, policy.Policy) + + assert response.version == 774 + + assert response.etag == b"etag_blob" + + +@pytest.mark.asyncio +async def test_get_iam_policy_async(transport: str = "grpc_asyncio"): + client = SchemaServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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() + + # 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",) + ) + + response = await client.get_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, policy.Policy) + + assert response.version == 774 + + assert response.etag == b"etag_blob" + + +def test_get_iam_policy_field_headers(): + client = SchemaServiceClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Any value 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.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() + + client.get_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_get_iam_policy_field_headers_async(): + client = SchemaServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Any value 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.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()) + + await client.get_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] + + +def test_get_iam_policy_from_dict(): + client = SchemaServiceClient( + credentials=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() + + response = client.get_iam_policy( + request={ + "resource": "resource_value", + "options": options.GetPolicyOptions(requested_policy_version=2598), + } + ) + call.assert_called() + +@pytest.mark.asyncio +async def test_get_iam_policy_from_dict_async(): + client = SchemaServiceAsyncClient( + credentials=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() + ) + + response = await client.get_iam_policy( + request={ + "resource": "resource_value", + "options": options.GetPolicyOptions(requested_policy_version=2598), + } + ) + call.assert_called() + + +def test_test_iam_permissions(transport: str = "grpc"): + client = SchemaServiceClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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() + + # 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( + permissions=["permissions_value"], + ) + + response = client.test_iam_permissions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, iam_policy.TestIamPermissionsResponse) + + assert response.permissions == ["permissions_value"] + + +@pytest.mark.asyncio +async def test_test_iam_permissions_async(transport: str = "grpc_asyncio"): + client = SchemaServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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() + + # 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(permissions=["permissions_value"],) + ) + + response = await client.test_iam_permissions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, iam_policy.TestIamPermissionsResponse) + + assert response.permissions == ["permissions_value"] + + +def test_test_iam_permissions_field_headers(): + client = SchemaServiceClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Any value 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.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() + + client.test_iam_permissions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_test_iam_permissions_field_headers_async(): + client = SchemaServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Any value 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.resource = "resource/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + iam_policy.TestIamPermissionsResponse() + ) + + await client.test_iam_permissions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] + + +def test_test_iam_permissions_from_dict(): + client = SchemaServiceClient( + credentials=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() + + response = client.test_iam_permissions( + request={ + "resource": "resource_value", + "permissions": ["permissions_value"], + } + ) + call.assert_called() + +@pytest.mark.asyncio +async def test_test_iam_permissions_from_dict_async(): + client = SchemaServiceAsyncClient( + credentials=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() + ) + + response = await client.test_iam_permissions( + request={ + "resource": "resource_value", + "permissions": ["permissions_value"], + } + ) + call.assert_called() diff --git a/owl-bot-staging/v1/tests/unit/gapic/pubsub_v1/test_subscriber.py b/owl-bot-staging/v1/tests/unit/gapic/pubsub_v1/test_subscriber.py new file mode 100644 index 000000000..08b27b565 --- /dev/null +++ b/owl-bot-staging/v1/tests/unit/gapic/pubsub_v1/test_subscriber.py @@ -0,0 +1,5363 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +import os +import mock + +import grpc +from grpc.experimental import aio +import math +import pytest +from proto.marshal.rules.dates import DurationRule, TimestampRule + +from google import auth +from google.api_core import client_options +from google.api_core import 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.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.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.pubsub_v1.services.subscriber import SubscriberAsyncClient +from google.pubsub_v1.services.subscriber import SubscriberClient +from google.pubsub_v1.services.subscriber import pagers +from google.pubsub_v1.services.subscriber import transports +from google.pubsub_v1.types import pubsub + + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + + assert SubscriberClient._get_default_mtls_endpoint(None) is None + assert SubscriberClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert SubscriberClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert SubscriberClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert SubscriberClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert SubscriberClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + + +@pytest.mark.parametrize("client_class", [ + SubscriberClient, + SubscriberAsyncClient, +]) +def test_subscriber_client_from_service_account_info(client_class): + creds = credentials.AnonymousCredentials() + with mock.patch.object(service_account.Credentials, 'from_service_account_info') as factory: + factory.return_value = creds + info = {"valid": True} + client = client_class.from_service_account_info(info) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == 'pubsub.googleapis.com:443' + + +@pytest.mark.parametrize("client_class", [ + SubscriberClient, + SubscriberAsyncClient, +]) +def test_subscriber_client_from_service_account_file(client_class): + creds = credentials.AnonymousCredentials() + with mock.patch.object(service_account.Credentials, 'from_service_account_file') as factory: + factory.return_value = creds + client = client_class.from_service_account_file("dummy/file/path.json") + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + client = client_class.from_service_account_json("dummy/file/path.json") + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == 'pubsub.googleapis.com:443' + + +def test_subscriber_client_get_transport_class(): + transport = SubscriberClient.get_transport_class() + available_transports = [ + transports.SubscriberGrpcTransport, + ] + assert transport in available_transports + + transport = SubscriberClient.get_transport_class("grpc") + assert transport == transports.SubscriberGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (SubscriberClient, transports.SubscriberGrpcTransport, "grpc"), + (SubscriberAsyncClient, transports.SubscriberGrpcAsyncIOTransport, "grpc_asyncio"), +]) +@mock.patch.object(SubscriberClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SubscriberClient)) +@mock.patch.object(SubscriberAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SubscriberAsyncClient)) +def test_subscriber_client_client_options(client_class, transport_class, transport_name): + # Check that if channel is provided we won't create a new one. + with mock.patch.object(SubscriberClient, 'get_transport_class') as gtc: + transport = transport_class( + credentials=credentials.AnonymousCredentials() + ) + client = client_class(transport=transport) + gtc.assert_not_called() + + # Check that if channel is provided via str we will create a new one. + with mock.patch.object(SubscriberClient, 'get_transport_class') as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check the case api_endpoint is provided. + options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError): + client = client_class() + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError): + client = client_class() + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ + + (SubscriberClient, transports.SubscriberGrpcTransport, "grpc", "true"), + (SubscriberAsyncClient, transports.SubscriberGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (SubscriberClient, transports.SubscriberGrpcTransport, "grpc", "false"), + (SubscriberAsyncClient, transports.SubscriberGrpcAsyncIOTransport, "grpc_asyncio", "false"), + +]) +@mock.patch.object(SubscriberClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SubscriberClient)) +@mock.patch.object(SubscriberAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SubscriberAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_subscriber_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): + # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default + # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. + + # Check the case client_cert_source is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options) + + if use_client_cert_env == "false": + expected_client_cert_source = None + expected_host = client.DEFAULT_ENDPOINT + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): + if use_client_cert_env == "false": + expected_host = client.DEFAULT_ENDPOINT + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (SubscriberClient, transports.SubscriberGrpcTransport, "grpc"), + (SubscriberAsyncClient, transports.SubscriberGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_subscriber_client_client_options_scopes(client_class, transport_class, transport_name): + # Check the case scopes are provided. + options = client_options.ClientOptions( + scopes=["1", "2"], + ) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=["1", "2"], + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (SubscriberClient, transports.SubscriberGrpcTransport, "grpc"), + (SubscriberAsyncClient, transports.SubscriberGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_subscriber_client_client_options_credentials_file(client_class, transport_class, transport_name): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + +def test_subscriber_client_client_options_from_dict(): + with mock.patch('google.pubsub_v1.services.subscriber.transports.SubscriberGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = SubscriberClient( + client_options={'api_endpoint': 'squid.clam.whelk'} + ) + grpc_transport.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + +def test_create_subscription(transport: str = 'grpc', request_type=pubsub.Subscription): + client = SubscriberClient( + credentials=credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_subscription), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = pubsub.Subscription( + name='name_value', + + topic='topic_value', + + ack_deadline_seconds=2066, + + retain_acked_messages=True, + + enable_message_ordering=True, + + filter='filter_value', + + detached=True, + + ) + + 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 + + +def test_create_subscription_from_dict(): + test_create_subscription(request_type=dict) + + +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', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_subscription), + '__call__') as call: + client.create_subscription() + call.assert_called() + _, args, _ = call.mock_calls[0] + + assert args[0] == pubsub.Subscription() + +@pytest.mark.asyncio +async def test_create_subscription_async(transport: str = 'grpc_asyncio', request_type=pubsub.Subscription): + client = SubscriberAsyncClient( + credentials=credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_subscription), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(pubsub.Subscription( + name='name_value', + topic='topic_value', + ack_deadline_seconds=2066, + retain_acked_messages=True, + enable_message_ordering=True, + filter='filter_value', + detached=True, + )) + + 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 + + +@pytest.mark.asyncio +async def test_create_subscription_async_from_dict(): + await test_create_subscription_async(request_type=dict) + + +def test_create_subscription_field_headers(): + client = SubscriberClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = pubsub.Subscription() + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_subscription), + '__call__') as call: + call.return_value = pubsub.Subscription() + + client.create_subscription(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name/value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_create_subscription_field_headers_async(): + client = SubscriberAsyncClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = pubsub.Subscription() + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_subscription), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(pubsub.Subscription()) + + await client.create_subscription(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name/value', + ) in kw['metadata'] + + +def test_create_subscription_flattened(): + client = SubscriberClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_subscription), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = pubsub.Subscription() + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_subscription( + name='name_value', + topic='topic_value', + push_config=pubsub.PushConfig(push_endpoint='push_endpoint_value'), + ack_deadline_seconds=2066, + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + 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(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.create_subscription( + pubsub.Subscription(), + name='name_value', + topic='topic_value', + push_config=pubsub.PushConfig(push_endpoint='push_endpoint_value'), + ack_deadline_seconds=2066, + ) + + +@pytest.mark.asyncio +async def test_create_subscription_flattened_async(): + client = SubscriberAsyncClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_subscription), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = pubsub.Subscription() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(pubsub.Subscription()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_subscription( + name='name_value', + topic='topic_value', + push_config=pubsub.PushConfig(push_endpoint='push_endpoint_value'), + ack_deadline_seconds=2066, + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + 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(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.create_subscription( + pubsub.Subscription(), + name='name_value', + topic='topic_value', + push_config=pubsub.PushConfig(push_endpoint='push_endpoint_value'), + ack_deadline_seconds=2066, + ) + + +def test_get_subscription(transport: str = 'grpc', request_type=pubsub.GetSubscriptionRequest): + client = SubscriberClient( + credentials=credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_subscription), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = pubsub.Subscription( + name='name_value', + + topic='topic_value', + + ack_deadline_seconds=2066, + + retain_acked_messages=True, + + enable_message_ordering=True, + + filter='filter_value', + + detached=True, + + ) + + 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 + + +def test_get_subscription_from_dict(): + test_get_subscription(request_type=dict) + + +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', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_subscription), + '__call__') as call: + client.get_subscription() + call.assert_called() + _, args, _ = call.mock_calls[0] + + assert args[0] == pubsub.GetSubscriptionRequest() + +@pytest.mark.asyncio +async def test_get_subscription_async(transport: str = 'grpc_asyncio', request_type=pubsub.GetSubscriptionRequest): + client = SubscriberAsyncClient( + credentials=credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_subscription), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(pubsub.Subscription( + name='name_value', + topic='topic_value', + ack_deadline_seconds=2066, + retain_acked_messages=True, + enable_message_ordering=True, + filter='filter_value', + detached=True, + )) + + 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 + + +@pytest.mark.asyncio +async def test_get_subscription_async_from_dict(): + await test_get_subscription_async(request_type=dict) + + +def test_get_subscription_field_headers(): + client = SubscriberClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = pubsub.GetSubscriptionRequest() + request.subscription = 'subscription/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_subscription), + '__call__') as call: + call.return_value = pubsub.Subscription() + + client.get_subscription(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'subscription=subscription/value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_get_subscription_field_headers_async(): + client = SubscriberAsyncClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = pubsub.GetSubscriptionRequest() + request.subscription = 'subscription/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_subscription), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(pubsub.Subscription()) + + await client.get_subscription(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'subscription=subscription/value', + ) in kw['metadata'] + + +def test_get_subscription_flattened(): + client = SubscriberClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_subscription), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = pubsub.Subscription() + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_subscription( + subscription='subscription_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0].subscription == 'subscription_value' + + +def test_get_subscription_flattened_error(): + client = SubscriberClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_subscription( + pubsub.GetSubscriptionRequest(), + subscription='subscription_value', + ) + + +@pytest.mark.asyncio +async def test_get_subscription_flattened_async(): + client = SubscriberAsyncClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_subscription), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = pubsub.Subscription() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(pubsub.Subscription()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_subscription( + subscription='subscription_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0].subscription == 'subscription_value' + + +@pytest.mark.asyncio +async def test_get_subscription_flattened_error_async(): + client = SubscriberAsyncClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_subscription( + pubsub.GetSubscriptionRequest(), + subscription='subscription_value', + ) + + +def test_update_subscription(transport: str = 'grpc', request_type=pubsub.UpdateSubscriptionRequest): + client = SubscriberClient( + credentials=credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_subscription), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = pubsub.Subscription( + name='name_value', + + topic='topic_value', + + ack_deadline_seconds=2066, + + retain_acked_messages=True, + + enable_message_ordering=True, + + filter='filter_value', + + detached=True, + + ) + + 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 + + +def test_update_subscription_from_dict(): + test_update_subscription(request_type=dict) + + +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', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_subscription), + '__call__') as call: + client.update_subscription() + call.assert_called() + _, args, _ = call.mock_calls[0] + + assert args[0] == pubsub.UpdateSubscriptionRequest() + +@pytest.mark.asyncio +async def test_update_subscription_async(transport: str = 'grpc_asyncio', request_type=pubsub.UpdateSubscriptionRequest): + client = SubscriberAsyncClient( + credentials=credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_subscription), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(pubsub.Subscription( + name='name_value', + topic='topic_value', + ack_deadline_seconds=2066, + retain_acked_messages=True, + enable_message_ordering=True, + filter='filter_value', + detached=True, + )) + + 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 + + +@pytest.mark.asyncio +async def test_update_subscription_async_from_dict(): + await test_update_subscription_async(request_type=dict) + + +def test_update_subscription_field_headers(): + client = SubscriberClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = pubsub.UpdateSubscriptionRequest() + request.subscription.name = 'subscription.name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_subscription), + '__call__') as call: + call.return_value = pubsub.Subscription() + + client.update_subscription(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'subscription.name=subscription.name/value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_subscription_field_headers_async(): + client = SubscriberAsyncClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = pubsub.UpdateSubscriptionRequest() + request.subscription.name = 'subscription.name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_subscription), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(pubsub.Subscription()) + + await client.update_subscription(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'subscription.name=subscription.name/value', + ) in kw['metadata'] + + +def test_list_subscriptions(transport: str = 'grpc', request_type=pubsub.ListSubscriptionsRequest): + client = SubscriberClient( + credentials=credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_subscriptions), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = pubsub.ListSubscriptionsResponse( + next_page_token='next_page_token_value', + + ) + + response = client.list_subscriptions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == pubsub.ListSubscriptionsRequest() + + # Establish that the response is the type that we expect. + + assert isinstance(response, pagers.ListSubscriptionsPager) + + assert response.next_page_token == 'next_page_token_value' + + +def test_list_subscriptions_from_dict(): + test_list_subscriptions(request_type=dict) + + +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', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_subscriptions), + '__call__') as call: + client.list_subscriptions() + call.assert_called() + _, args, _ = call.mock_calls[0] + + assert args[0] == pubsub.ListSubscriptionsRequest() + +@pytest.mark.asyncio +async def test_list_subscriptions_async(transport: str = 'grpc_asyncio', request_type=pubsub.ListSubscriptionsRequest): + client = SubscriberAsyncClient( + credentials=credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_subscriptions), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(pubsub.ListSubscriptionsResponse( + next_page_token='next_page_token_value', + )) + + response = await client.list_subscriptions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == pubsub.ListSubscriptionsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListSubscriptionsAsyncPager) + + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_subscriptions_async_from_dict(): + await test_list_subscriptions_async(request_type=dict) + + +def test_list_subscriptions_field_headers(): + client = SubscriberClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = pubsub.ListSubscriptionsRequest() + request.project = 'project/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_subscriptions), + '__call__') as call: + call.return_value = pubsub.ListSubscriptionsResponse() + + client.list_subscriptions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'project=project/value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_list_subscriptions_field_headers_async(): + client = SubscriberAsyncClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = pubsub.ListSubscriptionsRequest() + request.project = 'project/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_subscriptions), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(pubsub.ListSubscriptionsResponse()) + + await client.list_subscriptions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'project=project/value', + ) in kw['metadata'] + + +def test_list_subscriptions_flattened(): + client = SubscriberClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_subscriptions), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = pubsub.ListSubscriptionsResponse() + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_subscriptions( + project='project_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0].project == 'project_value' + + +def test_list_subscriptions_flattened_error(): + client = SubscriberClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_subscriptions( + pubsub.ListSubscriptionsRequest(), + project='project_value', + ) + + +@pytest.mark.asyncio +async def test_list_subscriptions_flattened_async(): + client = SubscriberAsyncClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_subscriptions), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = pubsub.ListSubscriptionsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(pubsub.ListSubscriptionsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_subscriptions( + project='project_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0].project == 'project_value' + + +@pytest.mark.asyncio +async def test_list_subscriptions_flattened_error_async(): + client = SubscriberAsyncClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_subscriptions( + pubsub.ListSubscriptionsRequest(), + project='project_value', + ) + + +def test_list_subscriptions_pager(): + client = SubscriberClient( + credentials=credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_subscriptions), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + pubsub.ListSubscriptionsResponse( + subscriptions=[ + pubsub.Subscription(), + pubsub.Subscription(), + pubsub.Subscription(), + ], + next_page_token='abc', + ), + pubsub.ListSubscriptionsResponse( + subscriptions=[], + next_page_token='def', + ), + pubsub.ListSubscriptionsResponse( + subscriptions=[ + pubsub.Subscription(), + ], + next_page_token='ghi', + ), + pubsub.ListSubscriptionsResponse( + subscriptions=[ + pubsub.Subscription(), + pubsub.Subscription(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('project', ''), + )), + ) + pager = client.list_subscriptions(request={}) + + assert pager._metadata == metadata + + results = [i for i in pager] + assert len(results) == 6 + assert all(isinstance(i, pubsub.Subscription) + for i in results) + +def test_list_subscriptions_pages(): + client = SubscriberClient( + credentials=credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_subscriptions), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + pubsub.ListSubscriptionsResponse( + subscriptions=[ + pubsub.Subscription(), + pubsub.Subscription(), + pubsub.Subscription(), + ], + next_page_token='abc', + ), + pubsub.ListSubscriptionsResponse( + subscriptions=[], + next_page_token='def', + ), + pubsub.ListSubscriptionsResponse( + subscriptions=[ + pubsub.Subscription(), + ], + next_page_token='ghi', + ), + pubsub.ListSubscriptionsResponse( + subscriptions=[ + pubsub.Subscription(), + pubsub.Subscription(), + ], + ), + RuntimeError, + ) + pages = list(client.list_subscriptions(request={}).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +@pytest.mark.asyncio +async def test_list_subscriptions_async_pager(): + client = SubscriberAsyncClient( + credentials=credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_subscriptions), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + pubsub.ListSubscriptionsResponse( + subscriptions=[ + pubsub.Subscription(), + pubsub.Subscription(), + pubsub.Subscription(), + ], + next_page_token='abc', + ), + pubsub.ListSubscriptionsResponse( + subscriptions=[], + next_page_token='def', + ), + pubsub.ListSubscriptionsResponse( + subscriptions=[ + pubsub.Subscription(), + ], + next_page_token='ghi', + ), + pubsub.ListSubscriptionsResponse( + subscriptions=[ + pubsub.Subscription(), + pubsub.Subscription(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_subscriptions(request={},) + assert async_pager.next_page_token == 'abc' + responses = [] + async for response in async_pager: + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, pubsub.Subscription) + for i in responses) + +@pytest.mark.asyncio +async def test_list_subscriptions_async_pages(): + client = SubscriberAsyncClient( + credentials=credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_subscriptions), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + pubsub.ListSubscriptionsResponse( + subscriptions=[ + pubsub.Subscription(), + pubsub.Subscription(), + pubsub.Subscription(), + ], + next_page_token='abc', + ), + pubsub.ListSubscriptionsResponse( + subscriptions=[], + next_page_token='def', + ), + pubsub.ListSubscriptionsResponse( + subscriptions=[ + pubsub.Subscription(), + ], + next_page_token='ghi', + ), + pubsub.ListSubscriptionsResponse( + subscriptions=[ + pubsub.Subscription(), + pubsub.Subscription(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.list_subscriptions(request={})).pages: + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +def test_delete_subscription(transport: str = 'grpc', request_type=pubsub.DeleteSubscriptionRequest): + client = SubscriberClient( + credentials=credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_subscription), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + + response = client.delete_subscription(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == pubsub.DeleteSubscriptionRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_subscription_from_dict(): + test_delete_subscription(request_type=dict) + + +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', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_subscription), + '__call__') as call: + client.delete_subscription() + call.assert_called() + _, args, _ = call.mock_calls[0] + + assert args[0] == pubsub.DeleteSubscriptionRequest() + +@pytest.mark.asyncio +async def test_delete_subscription_async(transport: str = 'grpc_asyncio', request_type=pubsub.DeleteSubscriptionRequest): + client = SubscriberAsyncClient( + credentials=credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_subscription), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + + response = await client.delete_subscription(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == pubsub.DeleteSubscriptionRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.asyncio +async def test_delete_subscription_async_from_dict(): + await test_delete_subscription_async(request_type=dict) + + +def test_delete_subscription_field_headers(): + client = SubscriberClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = pubsub.DeleteSubscriptionRequest() + request.subscription = 'subscription/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_subscription), + '__call__') as call: + call.return_value = None + + client.delete_subscription(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'subscription=subscription/value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_delete_subscription_field_headers_async(): + client = SubscriberAsyncClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = pubsub.DeleteSubscriptionRequest() + request.subscription = 'subscription/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_subscription), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + + await client.delete_subscription(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'subscription=subscription/value', + ) in kw['metadata'] + + +def test_delete_subscription_flattened(): + client = SubscriberClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_subscription), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.delete_subscription( + subscription='subscription_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0].subscription == 'subscription_value' + + +def test_delete_subscription_flattened_error(): + client = SubscriberClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_subscription( + pubsub.DeleteSubscriptionRequest(), + subscription='subscription_value', + ) + + +@pytest.mark.asyncio +async def test_delete_subscription_flattened_async(): + client = SubscriberAsyncClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_subscription), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.delete_subscription( + subscription='subscription_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0].subscription == 'subscription_value' + + +@pytest.mark.asyncio +async def test_delete_subscription_flattened_error_async(): + client = SubscriberAsyncClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.delete_subscription( + pubsub.DeleteSubscriptionRequest(), + subscription='subscription_value', + ) + + +def test_modify_ack_deadline(transport: str = 'grpc', request_type=pubsub.ModifyAckDeadlineRequest): + client = SubscriberClient( + credentials=credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.modify_ack_deadline), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + + response = client.modify_ack_deadline(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == pubsub.ModifyAckDeadlineRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +def test_modify_ack_deadline_from_dict(): + test_modify_ack_deadline(request_type=dict) + + +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', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.modify_ack_deadline), + '__call__') as call: + client.modify_ack_deadline() + call.assert_called() + _, args, _ = call.mock_calls[0] + + assert args[0] == pubsub.ModifyAckDeadlineRequest() + +@pytest.mark.asyncio +async def test_modify_ack_deadline_async(transport: str = 'grpc_asyncio', request_type=pubsub.ModifyAckDeadlineRequest): + client = SubscriberAsyncClient( + credentials=credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.modify_ack_deadline), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + + response = await client.modify_ack_deadline(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == pubsub.ModifyAckDeadlineRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.asyncio +async def test_modify_ack_deadline_async_from_dict(): + await test_modify_ack_deadline_async(request_type=dict) + + +def test_modify_ack_deadline_field_headers(): + client = SubscriberClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = pubsub.ModifyAckDeadlineRequest() + request.subscription = 'subscription/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.modify_ack_deadline), + '__call__') as call: + call.return_value = None + + client.modify_ack_deadline(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'subscription=subscription/value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_modify_ack_deadline_field_headers_async(): + client = SubscriberAsyncClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = pubsub.ModifyAckDeadlineRequest() + request.subscription = 'subscription/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.modify_ack_deadline), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + + await client.modify_ack_deadline(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'subscription=subscription/value', + ) in kw['metadata'] + + +def test_modify_ack_deadline_flattened(): + client = SubscriberClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.modify_ack_deadline), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.modify_ack_deadline( + subscription='subscription_value', + ack_ids=['ack_ids_value'], + ack_deadline_seconds=2066, + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + 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(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.modify_ack_deadline( + pubsub.ModifyAckDeadlineRequest(), + subscription='subscription_value', + ack_ids=['ack_ids_value'], + ack_deadline_seconds=2066, + ) + + +@pytest.mark.asyncio +async def test_modify_ack_deadline_flattened_async(): + client = SubscriberAsyncClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.modify_ack_deadline), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.modify_ack_deadline( + subscription='subscription_value', + ack_ids=['ack_ids_value'], + ack_deadline_seconds=2066, + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + 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(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.modify_ack_deadline( + pubsub.ModifyAckDeadlineRequest(), + subscription='subscription_value', + ack_ids=['ack_ids_value'], + ack_deadline_seconds=2066, + ) + + +def test_acknowledge(transport: str = 'grpc', request_type=pubsub.AcknowledgeRequest): + client = SubscriberClient( + credentials=credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.acknowledge), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + + response = client.acknowledge(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == pubsub.AcknowledgeRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +def test_acknowledge_from_dict(): + test_acknowledge(request_type=dict) + + +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', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.acknowledge), + '__call__') as call: + client.acknowledge() + call.assert_called() + _, args, _ = call.mock_calls[0] + + assert args[0] == pubsub.AcknowledgeRequest() + +@pytest.mark.asyncio +async def test_acknowledge_async(transport: str = 'grpc_asyncio', request_type=pubsub.AcknowledgeRequest): + client = SubscriberAsyncClient( + credentials=credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.acknowledge), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + + response = await client.acknowledge(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == pubsub.AcknowledgeRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.asyncio +async def test_acknowledge_async_from_dict(): + await test_acknowledge_async(request_type=dict) + + +def test_acknowledge_field_headers(): + client = SubscriberClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = pubsub.AcknowledgeRequest() + request.subscription = 'subscription/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.acknowledge), + '__call__') as call: + call.return_value = None + + client.acknowledge(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'subscription=subscription/value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_acknowledge_field_headers_async(): + client = SubscriberAsyncClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = pubsub.AcknowledgeRequest() + request.subscription = 'subscription/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.acknowledge), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + + await client.acknowledge(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'subscription=subscription/value', + ) in kw['metadata'] + + +def test_acknowledge_flattened(): + client = SubscriberClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.acknowledge), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.acknowledge( + subscription='subscription_value', + ack_ids=['ack_ids_value'], + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0].subscription == 'subscription_value' + + assert args[0].ack_ids == ['ack_ids_value'] + + +def test_acknowledge_flattened_error(): + client = SubscriberClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.acknowledge( + pubsub.AcknowledgeRequest(), + subscription='subscription_value', + ack_ids=['ack_ids_value'], + ) + + +@pytest.mark.asyncio +async def test_acknowledge_flattened_async(): + client = SubscriberAsyncClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.acknowledge), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.acknowledge( + subscription='subscription_value', + ack_ids=['ack_ids_value'], + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + 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(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.acknowledge( + pubsub.AcknowledgeRequest(), + subscription='subscription_value', + ack_ids=['ack_ids_value'], + ) + + +def test_pull(transport: str = 'grpc', request_type=pubsub.PullRequest): + client = SubscriberClient( + credentials=credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.pull), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = pubsub.PullResponse( + ) + + response = client.pull(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == pubsub.PullRequest() + + # Establish that the response is the type that we expect. + + assert isinstance(response, pubsub.PullResponse) + + +def test_pull_from_dict(): + test_pull(request_type=dict) + + +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', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.pull), + '__call__') as call: + client.pull() + call.assert_called() + _, args, _ = call.mock_calls[0] + + assert args[0] == pubsub.PullRequest() + +@pytest.mark.asyncio +async def test_pull_async(transport: str = 'grpc_asyncio', request_type=pubsub.PullRequest): + client = SubscriberAsyncClient( + credentials=credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.pull), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(pubsub.PullResponse( + )) + + response = await client.pull(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == pubsub.PullRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pubsub.PullResponse) + + +@pytest.mark.asyncio +async def test_pull_async_from_dict(): + await test_pull_async(request_type=dict) + + +def test_pull_field_headers(): + client = SubscriberClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = pubsub.PullRequest() + request.subscription = 'subscription/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.pull), + '__call__') as call: + call.return_value = pubsub.PullResponse() + + client.pull(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'subscription=subscription/value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_pull_field_headers_async(): + client = SubscriberAsyncClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = pubsub.PullRequest() + request.subscription = 'subscription/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.pull), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(pubsub.PullResponse()) + + await client.pull(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'subscription=subscription/value', + ) in kw['metadata'] + + +def test_pull_flattened(): + client = SubscriberClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.pull), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = pubsub.PullResponse() + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.pull( + subscription='subscription_value', + return_immediately=True, + max_messages=1277, + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + 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(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.pull( + pubsub.PullRequest(), + subscription='subscription_value', + return_immediately=True, + max_messages=1277, + ) + + +@pytest.mark.asyncio +async def test_pull_flattened_async(): + client = SubscriberAsyncClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.pull), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = pubsub.PullResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(pubsub.PullResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.pull( + subscription='subscription_value', + return_immediately=True, + max_messages=1277, + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + 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(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.pull( + pubsub.PullRequest(), + subscription='subscription_value', + return_immediately=True, + max_messages=1277, + ) + + +def test_streaming_pull(transport: str = 'grpc', request_type=pubsub.StreamingPullRequest): + client = SubscriberClient( + credentials=credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + requests = [request] + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.streaming_pull), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = iter([pubsub.StreamingPullResponse()]) + + response = client.streaming_pull(iter(requests)) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert next(args[0]) == request + + # Establish that the response is the type that we expect. + for message in response: + assert isinstance(message, pubsub.StreamingPullResponse) + + +def test_streaming_pull_from_dict(): + test_streaming_pull(request_type=dict) + + +@pytest.mark.asyncio +async def test_streaming_pull_async(transport: str = 'grpc_asyncio', request_type=pubsub.StreamingPullRequest): + client = SubscriberAsyncClient( + credentials=credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + requests = [request] + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.streaming_pull), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = mock.Mock(aio.StreamStreamCall, autospec=True) + call.return_value.read = mock.AsyncMock(side_effect=[pubsub.StreamingPullResponse()]) + + response = await client.streaming_pull(iter(requests)) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert next(args[0]) == request + + # Establish that the response is the type that we expect. + message = await response.read() + assert isinstance(message, pubsub.StreamingPullResponse) + + +@pytest.mark.asyncio +async def test_streaming_pull_async_from_dict(): + await test_streaming_pull_async(request_type=dict) + + +def test_modify_push_config(transport: str = 'grpc', request_type=pubsub.ModifyPushConfigRequest): + client = SubscriberClient( + credentials=credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.modify_push_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + + response = client.modify_push_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == pubsub.ModifyPushConfigRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +def test_modify_push_config_from_dict(): + test_modify_push_config(request_type=dict) + + +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', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.modify_push_config), + '__call__') as call: + client.modify_push_config() + call.assert_called() + _, args, _ = call.mock_calls[0] + + assert args[0] == pubsub.ModifyPushConfigRequest() + +@pytest.mark.asyncio +async def test_modify_push_config_async(transport: str = 'grpc_asyncio', request_type=pubsub.ModifyPushConfigRequest): + client = SubscriberAsyncClient( + credentials=credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.modify_push_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + + response = await client.modify_push_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == pubsub.ModifyPushConfigRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.asyncio +async def test_modify_push_config_async_from_dict(): + await test_modify_push_config_async(request_type=dict) + + +def test_modify_push_config_field_headers(): + client = SubscriberClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = pubsub.ModifyPushConfigRequest() + request.subscription = 'subscription/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.modify_push_config), + '__call__') as call: + call.return_value = None + + client.modify_push_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'subscription=subscription/value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_modify_push_config_field_headers_async(): + client = SubscriberAsyncClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = pubsub.ModifyPushConfigRequest() + request.subscription = 'subscription/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.modify_push_config), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + + await client.modify_push_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'subscription=subscription/value', + ) in kw['metadata'] + + +def test_modify_push_config_flattened(): + client = SubscriberClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.modify_push_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.modify_push_config( + subscription='subscription_value', + push_config=pubsub.PushConfig(push_endpoint='push_endpoint_value'), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + 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(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.modify_push_config( + pubsub.ModifyPushConfigRequest(), + subscription='subscription_value', + push_config=pubsub.PushConfig(push_endpoint='push_endpoint_value'), + ) + + +@pytest.mark.asyncio +async def test_modify_push_config_flattened_async(): + client = SubscriberAsyncClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.modify_push_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.modify_push_config( + subscription='subscription_value', + push_config=pubsub.PushConfig(push_endpoint='push_endpoint_value'), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0].subscription == 'subscription_value' + + assert args[0].push_config == pubsub.PushConfig(push_endpoint='push_endpoint_value') + + +@pytest.mark.asyncio +async def test_modify_push_config_flattened_error_async(): + client = SubscriberAsyncClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.modify_push_config( + pubsub.ModifyPushConfigRequest(), + subscription='subscription_value', + push_config=pubsub.PushConfig(push_endpoint='push_endpoint_value'), + ) + + +def test_get_snapshot(transport: str = 'grpc', request_type=pubsub.GetSnapshotRequest): + client = SubscriberClient( + credentials=credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_snapshot), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = pubsub.Snapshot( + name='name_value', + + topic='topic_value', + + ) + + response = client.get_snapshot(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == pubsub.GetSnapshotRequest() + + # Establish that the response is the type that we expect. + + assert isinstance(response, pubsub.Snapshot) + + assert response.name == 'name_value' + + assert response.topic == 'topic_value' + + +def test_get_snapshot_from_dict(): + test_get_snapshot(request_type=dict) + + +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', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_snapshot), + '__call__') as call: + client.get_snapshot() + call.assert_called() + _, args, _ = call.mock_calls[0] + + assert args[0] == pubsub.GetSnapshotRequest() + +@pytest.mark.asyncio +async def test_get_snapshot_async(transport: str = 'grpc_asyncio', request_type=pubsub.GetSnapshotRequest): + client = SubscriberAsyncClient( + credentials=credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_snapshot), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(pubsub.Snapshot( + name='name_value', + topic='topic_value', + )) + + response = await client.get_snapshot(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == pubsub.GetSnapshotRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pubsub.Snapshot) + + assert response.name == 'name_value' + + assert response.topic == 'topic_value' + + +@pytest.mark.asyncio +async def test_get_snapshot_async_from_dict(): + await test_get_snapshot_async(request_type=dict) + + +def test_get_snapshot_field_headers(): + client = SubscriberClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = pubsub.GetSnapshotRequest() + request.snapshot = 'snapshot/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_snapshot), + '__call__') as call: + call.return_value = pubsub.Snapshot() + + client.get_snapshot(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'snapshot=snapshot/value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_get_snapshot_field_headers_async(): + client = SubscriberAsyncClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = pubsub.GetSnapshotRequest() + request.snapshot = 'snapshot/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_snapshot), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(pubsub.Snapshot()) + + await client.get_snapshot(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'snapshot=snapshot/value', + ) in kw['metadata'] + + +def test_get_snapshot_flattened(): + client = SubscriberClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_snapshot), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = pubsub.Snapshot() + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_snapshot( + snapshot='snapshot_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0].snapshot == 'snapshot_value' + + +def test_get_snapshot_flattened_error(): + client = SubscriberClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_snapshot( + pubsub.GetSnapshotRequest(), + snapshot='snapshot_value', + ) + + +@pytest.mark.asyncio +async def test_get_snapshot_flattened_async(): + client = SubscriberAsyncClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_snapshot), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = pubsub.Snapshot() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(pubsub.Snapshot()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_snapshot( + snapshot='snapshot_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0].snapshot == 'snapshot_value' + + +@pytest.mark.asyncio +async def test_get_snapshot_flattened_error_async(): + client = SubscriberAsyncClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_snapshot( + pubsub.GetSnapshotRequest(), + snapshot='snapshot_value', + ) + + +def test_list_snapshots(transport: str = 'grpc', request_type=pubsub.ListSnapshotsRequest): + client = SubscriberClient( + credentials=credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_snapshots), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = pubsub.ListSnapshotsResponse( + next_page_token='next_page_token_value', + + ) + + response = client.list_snapshots(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == pubsub.ListSnapshotsRequest() + + # Establish that the response is the type that we expect. + + assert isinstance(response, pagers.ListSnapshotsPager) + + assert response.next_page_token == 'next_page_token_value' + + +def test_list_snapshots_from_dict(): + test_list_snapshots(request_type=dict) + + +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', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_snapshots), + '__call__') as call: + client.list_snapshots() + call.assert_called() + _, args, _ = call.mock_calls[0] + + assert args[0] == pubsub.ListSnapshotsRequest() + +@pytest.mark.asyncio +async def test_list_snapshots_async(transport: str = 'grpc_asyncio', request_type=pubsub.ListSnapshotsRequest): + client = SubscriberAsyncClient( + credentials=credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_snapshots), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(pubsub.ListSnapshotsResponse( + next_page_token='next_page_token_value', + )) + + response = await client.list_snapshots(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == pubsub.ListSnapshotsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListSnapshotsAsyncPager) + + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_snapshots_async_from_dict(): + await test_list_snapshots_async(request_type=dict) + + +def test_list_snapshots_field_headers(): + client = SubscriberClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = pubsub.ListSnapshotsRequest() + request.project = 'project/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_snapshots), + '__call__') as call: + call.return_value = pubsub.ListSnapshotsResponse() + + client.list_snapshots(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'project=project/value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_list_snapshots_field_headers_async(): + client = SubscriberAsyncClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = pubsub.ListSnapshotsRequest() + request.project = 'project/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_snapshots), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(pubsub.ListSnapshotsResponse()) + + await client.list_snapshots(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'project=project/value', + ) in kw['metadata'] + + +def test_list_snapshots_flattened(): + client = SubscriberClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_snapshots), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = pubsub.ListSnapshotsResponse() + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_snapshots( + project='project_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0].project == 'project_value' + + +def test_list_snapshots_flattened_error(): + client = SubscriberClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_snapshots( + pubsub.ListSnapshotsRequest(), + project='project_value', + ) + + +@pytest.mark.asyncio +async def test_list_snapshots_flattened_async(): + client = SubscriberAsyncClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_snapshots), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = pubsub.ListSnapshotsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(pubsub.ListSnapshotsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_snapshots( + project='project_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0].project == 'project_value' + + +@pytest.mark.asyncio +async def test_list_snapshots_flattened_error_async(): + client = SubscriberAsyncClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_snapshots( + pubsub.ListSnapshotsRequest(), + project='project_value', + ) + + +def test_list_snapshots_pager(): + client = SubscriberClient( + credentials=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: + # Set the response to a series of pages. + call.side_effect = ( + pubsub.ListSnapshotsResponse( + snapshots=[ + pubsub.Snapshot(), + pubsub.Snapshot(), + pubsub.Snapshot(), + ], + next_page_token='abc', + ), + pubsub.ListSnapshotsResponse( + snapshots=[], + next_page_token='def', + ), + pubsub.ListSnapshotsResponse( + snapshots=[ + pubsub.Snapshot(), + ], + next_page_token='ghi', + ), + pubsub.ListSnapshotsResponse( + snapshots=[ + pubsub.Snapshot(), + pubsub.Snapshot(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('project', ''), + )), + ) + pager = client.list_snapshots(request={}) + + assert pager._metadata == metadata + + results = [i for i in pager] + assert len(results) == 6 + assert all(isinstance(i, pubsub.Snapshot) + for i in results) + +def test_list_snapshots_pages(): + client = SubscriberClient( + credentials=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: + # Set the response to a series of pages. + call.side_effect = ( + pubsub.ListSnapshotsResponse( + snapshots=[ + pubsub.Snapshot(), + pubsub.Snapshot(), + pubsub.Snapshot(), + ], + next_page_token='abc', + ), + pubsub.ListSnapshotsResponse( + snapshots=[], + next_page_token='def', + ), + pubsub.ListSnapshotsResponse( + snapshots=[ + pubsub.Snapshot(), + ], + next_page_token='ghi', + ), + pubsub.ListSnapshotsResponse( + snapshots=[ + pubsub.Snapshot(), + pubsub.Snapshot(), + ], + ), + RuntimeError, + ) + pages = list(client.list_snapshots(request={}).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +@pytest.mark.asyncio +async def test_list_snapshots_async_pager(): + client = SubscriberAsyncClient( + credentials=credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_snapshots), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + pubsub.ListSnapshotsResponse( + snapshots=[ + pubsub.Snapshot(), + pubsub.Snapshot(), + pubsub.Snapshot(), + ], + next_page_token='abc', + ), + pubsub.ListSnapshotsResponse( + snapshots=[], + next_page_token='def', + ), + pubsub.ListSnapshotsResponse( + snapshots=[ + pubsub.Snapshot(), + ], + next_page_token='ghi', + ), + pubsub.ListSnapshotsResponse( + snapshots=[ + pubsub.Snapshot(), + pubsub.Snapshot(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_snapshots(request={},) + assert async_pager.next_page_token == 'abc' + responses = [] + async for response in async_pager: + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, pubsub.Snapshot) + for i in responses) + +@pytest.mark.asyncio +async def test_list_snapshots_async_pages(): + client = SubscriberAsyncClient( + credentials=credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_snapshots), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + pubsub.ListSnapshotsResponse( + snapshots=[ + pubsub.Snapshot(), + pubsub.Snapshot(), + pubsub.Snapshot(), + ], + next_page_token='abc', + ), + pubsub.ListSnapshotsResponse( + snapshots=[], + next_page_token='def', + ), + pubsub.ListSnapshotsResponse( + snapshots=[ + pubsub.Snapshot(), + ], + next_page_token='ghi', + ), + pubsub.ListSnapshotsResponse( + snapshots=[ + pubsub.Snapshot(), + pubsub.Snapshot(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.list_snapshots(request={})).pages: + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +def test_create_snapshot(transport: str = 'grpc', request_type=pubsub.CreateSnapshotRequest): + client = SubscriberClient( + credentials=credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_snapshot), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = pubsub.Snapshot( + name='name_value', + + topic='topic_value', + + ) + + response = client.create_snapshot(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == pubsub.CreateSnapshotRequest() + + # Establish that the response is the type that we expect. + + assert isinstance(response, pubsub.Snapshot) + + assert response.name == 'name_value' + + assert response.topic == 'topic_value' + + +def test_create_snapshot_from_dict(): + test_create_snapshot(request_type=dict) + + +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', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_snapshot), + '__call__') as call: + client.create_snapshot() + call.assert_called() + _, args, _ = call.mock_calls[0] + + assert args[0] == pubsub.CreateSnapshotRequest() + +@pytest.mark.asyncio +async def test_create_snapshot_async(transport: str = 'grpc_asyncio', request_type=pubsub.CreateSnapshotRequest): + client = SubscriberAsyncClient( + credentials=credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_snapshot), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(pubsub.Snapshot( + name='name_value', + topic='topic_value', + )) + + response = await client.create_snapshot(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == pubsub.CreateSnapshotRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pubsub.Snapshot) + + assert response.name == 'name_value' + + assert response.topic == 'topic_value' + + +@pytest.mark.asyncio +async def test_create_snapshot_async_from_dict(): + await test_create_snapshot_async(request_type=dict) + + +def test_create_snapshot_field_headers(): + client = SubscriberClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = pubsub.CreateSnapshotRequest() + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_snapshot), + '__call__') as call: + call.return_value = pubsub.Snapshot() + + client.create_snapshot(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name/value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_create_snapshot_field_headers_async(): + client = SubscriberAsyncClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = pubsub.CreateSnapshotRequest() + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_snapshot), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(pubsub.Snapshot()) + + await client.create_snapshot(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name/value', + ) in kw['metadata'] + + +def test_create_snapshot_flattened(): + client = SubscriberClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_snapshot), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = pubsub.Snapshot() + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_snapshot( + name='name_value', + subscription='subscription_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0].name == 'name_value' + + assert args[0].subscription == 'subscription_value' + + +def test_create_snapshot_flattened_error(): + client = SubscriberClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.create_snapshot( + pubsub.CreateSnapshotRequest(), + name='name_value', + subscription='subscription_value', + ) + + +@pytest.mark.asyncio +async def test_create_snapshot_flattened_async(): + client = SubscriberAsyncClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_snapshot), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = pubsub.Snapshot() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(pubsub.Snapshot()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_snapshot( + name='name_value', + subscription='subscription_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + 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(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.create_snapshot( + pubsub.CreateSnapshotRequest(), + name='name_value', + subscription='subscription_value', + ) + + +def test_update_snapshot(transport: str = 'grpc', request_type=pubsub.UpdateSnapshotRequest): + client = SubscriberClient( + credentials=credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_snapshot), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = pubsub.Snapshot( + name='name_value', + + topic='topic_value', + + ) + + response = client.update_snapshot(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == pubsub.UpdateSnapshotRequest() + + # Establish that the response is the type that we expect. + + assert isinstance(response, pubsub.Snapshot) + + assert response.name == 'name_value' + + assert response.topic == 'topic_value' + + +def test_update_snapshot_from_dict(): + test_update_snapshot(request_type=dict) + + +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', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_snapshot), + '__call__') as call: + client.update_snapshot() + call.assert_called() + _, args, _ = call.mock_calls[0] + + assert args[0] == pubsub.UpdateSnapshotRequest() + +@pytest.mark.asyncio +async def test_update_snapshot_async(transport: str = 'grpc_asyncio', request_type=pubsub.UpdateSnapshotRequest): + client = SubscriberAsyncClient( + credentials=credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_snapshot), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(pubsub.Snapshot( + name='name_value', + topic='topic_value', + )) + + response = await client.update_snapshot(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == pubsub.UpdateSnapshotRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pubsub.Snapshot) + + assert response.name == 'name_value' + + assert response.topic == 'topic_value' + + +@pytest.mark.asyncio +async def test_update_snapshot_async_from_dict(): + await test_update_snapshot_async(request_type=dict) + + +def test_update_snapshot_field_headers(): + client = SubscriberClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = pubsub.UpdateSnapshotRequest() + request.snapshot.name = 'snapshot.name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_snapshot), + '__call__') as call: + call.return_value = pubsub.Snapshot() + + client.update_snapshot(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'snapshot.name=snapshot.name/value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_snapshot_field_headers_async(): + client = SubscriberAsyncClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = pubsub.UpdateSnapshotRequest() + request.snapshot.name = 'snapshot.name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_snapshot), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(pubsub.Snapshot()) + + await client.update_snapshot(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'snapshot.name=snapshot.name/value', + ) in kw['metadata'] + + +def test_delete_snapshot(transport: str = 'grpc', request_type=pubsub.DeleteSnapshotRequest): + client = SubscriberClient( + credentials=credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_snapshot), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + + response = client.delete_snapshot(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == pubsub.DeleteSnapshotRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_snapshot_from_dict(): + test_delete_snapshot(request_type=dict) + + +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', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_snapshot), + '__call__') as call: + client.delete_snapshot() + call.assert_called() + _, args, _ = call.mock_calls[0] + + assert args[0] == pubsub.DeleteSnapshotRequest() + +@pytest.mark.asyncio +async def test_delete_snapshot_async(transport: str = 'grpc_asyncio', request_type=pubsub.DeleteSnapshotRequest): + client = SubscriberAsyncClient( + credentials=credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_snapshot), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + + response = await client.delete_snapshot(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == pubsub.DeleteSnapshotRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.asyncio +async def test_delete_snapshot_async_from_dict(): + await test_delete_snapshot_async(request_type=dict) + + +def test_delete_snapshot_field_headers(): + client = SubscriberClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = pubsub.DeleteSnapshotRequest() + request.snapshot = 'snapshot/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_snapshot), + '__call__') as call: + call.return_value = None + + client.delete_snapshot(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'snapshot=snapshot/value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_delete_snapshot_field_headers_async(): + client = SubscriberAsyncClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = pubsub.DeleteSnapshotRequest() + request.snapshot = 'snapshot/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_snapshot), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + + await client.delete_snapshot(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'snapshot=snapshot/value', + ) in kw['metadata'] + + +def test_delete_snapshot_flattened(): + client = SubscriberClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_snapshot), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.delete_snapshot( + snapshot='snapshot_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0].snapshot == 'snapshot_value' + + +def test_delete_snapshot_flattened_error(): + client = SubscriberClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_snapshot( + pubsub.DeleteSnapshotRequest(), + snapshot='snapshot_value', + ) + + +@pytest.mark.asyncio +async def test_delete_snapshot_flattened_async(): + client = SubscriberAsyncClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_snapshot), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.delete_snapshot( + snapshot='snapshot_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0].snapshot == 'snapshot_value' + + +@pytest.mark.asyncio +async def test_delete_snapshot_flattened_error_async(): + client = SubscriberAsyncClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.delete_snapshot( + pubsub.DeleteSnapshotRequest(), + snapshot='snapshot_value', + ) + + +def test_seek(transport: str = 'grpc', request_type=pubsub.SeekRequest): + client = SubscriberClient( + credentials=credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.seek), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = pubsub.SeekResponse( + ) + + response = client.seek(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == pubsub.SeekRequest() + + # Establish that the response is the type that we expect. + + assert isinstance(response, pubsub.SeekResponse) + + +def test_seek_from_dict(): + test_seek(request_type=dict) + + +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', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.seek), + '__call__') as call: + client.seek() + call.assert_called() + _, args, _ = call.mock_calls[0] + + assert args[0] == pubsub.SeekRequest() + +@pytest.mark.asyncio +async def test_seek_async(transport: str = 'grpc_asyncio', request_type=pubsub.SeekRequest): + client = SubscriberAsyncClient( + credentials=credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.seek), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(pubsub.SeekResponse( + )) + + response = await client.seek(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == pubsub.SeekRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pubsub.SeekResponse) + + +@pytest.mark.asyncio +async def test_seek_async_from_dict(): + await test_seek_async(request_type=dict) + + +def test_seek_field_headers(): + client = SubscriberClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = pubsub.SeekRequest() + request.subscription = 'subscription/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.seek), + '__call__') as call: + call.return_value = pubsub.SeekResponse() + + client.seek(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'subscription=subscription/value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_seek_field_headers_async(): + client = SubscriberAsyncClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = pubsub.SeekRequest() + request.subscription = 'subscription/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.seek), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(pubsub.SeekResponse()) + + await client.seek(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'subscription=subscription/value', + ) in kw['metadata'] + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.SubscriberGrpcTransport( + credentials=credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = SubscriberClient( + credentials=credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.SubscriberGrpcTransport( + credentials=credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = SubscriberClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.SubscriberGrpcTransport( + credentials=credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = SubscriberClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.SubscriberGrpcTransport( + credentials=credentials.AnonymousCredentials(), + ) + client = SubscriberClient(transport=transport) + assert client.transport is transport + + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.SubscriberGrpcTransport( + credentials=credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.SubscriberGrpcAsyncIOTransport( + credentials=credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + +@pytest.mark.parametrize("transport_class", [ + transports.SubscriberGrpcTransport, + transports.SubscriberGrpcAsyncIOTransport, +]) +def test_transport_adc(transport_class): + # Test default credentials are used if not provided. + with mock.patch.object(auth, 'default') as adc: + adc.return_value = (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(), + ) + 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): + transport = transports.SubscriberTransport( + credentials=credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_subscriber_base_transport(): + # Instantiate the base transport. + with mock.patch('google.pubsub_v1.services.subscriber.transports.SubscriberTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.SubscriberTransport( + credentials=credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'create_subscription', + 'get_subscription', + 'update_subscription', + 'list_subscriptions', + 'delete_subscription', + 'modify_ack_deadline', + 'acknowledge', + 'pull', + 'streaming_pull', + 'modify_push_config', + 'get_snapshot', + 'list_snapshots', + 'create_snapshot', + 'update_snapshot', + 'delete_snapshot', + 'seek', + 'set_iam_policy', + 'get_iam_policy', + 'test_iam_permissions', + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + +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') 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=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/pubsub', + ), + quota_project_id="octopus", + ) + + +def test_subscriber_base_transport_with_adc(): + # Test the default credentials are used if credentials and credentials_file are None. + with mock.patch.object(auth, 'default') 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) + transport = transports.SubscriberTransport() + adc.assert_called_once() + + +def test_subscriber_auth_adc(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(auth, 'default') as adc: + adc.return_value = (credentials.AnonymousCredentials(), None) + SubscriberClient() + adc.assert_called_once_with(scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/pubsub',), + quota_project_id=None, + ) + + +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') as adc: + adc.return_value = (credentials.AnonymousCredentials(), None) + transports.SubscriberGrpcTransport(host="squid.clam.whelk", quota_project_id="octopus") + adc.assert_called_once_with(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]) +def test_subscriber_grpc_transport_client_cert_source_for_mtls( + transport_class +): + cred = credentials.AnonymousCredentials() + + # Check ssl_channel_credentials is used if provided. + with mock.patch.object(transport_class, "create_channel") as mock_create_channel: + mock_ssl_channel_creds = mock.Mock() + transport_class( + host="squid.clam.whelk", + credentials=cred, + ssl_channel_credentials=mock_ssl_channel_creds + ) + mock_create_channel.assert_called_once_with( + "squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/pubsub', + ), + ssl_credentials=mock_ssl_channel_creds, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls + # is used. + with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): + with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: + transport_class( + credentials=cred, + client_cert_source_for_mtls=client_cert_source_callback + ) + expected_cert, expected_key = client_cert_source_callback() + mock_ssl_cred.assert_called_once_with( + certificate_chain=expected_cert, + private_key=expected_key + ) + + +def test_subscriber_host_no_port(): + client = SubscriberClient( + credentials=credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='pubsub.googleapis.com'), + ) + assert client.transport._host == 'pubsub.googleapis.com:443' + + +def test_subscriber_host_with_port(): + client = SubscriberClient( + credentials=credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='pubsub.googleapis.com:8000'), + ) + assert client.transport._host == 'pubsub.googleapis.com:8000' + + +def test_subscriber_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.SubscriberGrpcTransport( + host="squid.clam.whelk", + channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert transport._ssl_channel_credentials == None + + +def test_subscriber_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.SubscriberGrpcAsyncIOTransport( + host="squid.clam.whelk", + channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert transport._ssl_channel_credentials == None + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize("transport_class", [transports.SubscriberGrpcTransport, transports.SubscriberGrpcAsyncIOTransport]) +def test_subscriber_transport_channel_mtls_with_client_cert_source( + transport_class +): + with mock.patch("grpc.ssl_channel_credentials", autospec=True) as grpc_ssl_channel_cred: + with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: + mock_ssl_cred = mock.Mock() + grpc_ssl_channel_cred.return_value = mock_ssl_cred + + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + + cred = credentials.AnonymousCredentials() + with pytest.warns(DeprecationWarning): + with mock.patch.object(auth, 'default') as adc: + adc.return_value = (cred, None) + transport = transport_class( + host="squid.clam.whelk", + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=client_cert_source_callback, + ) + adc.assert_called_once() + + grpc_ssl_channel_cred.assert_called_once_with( + certificate_chain=b"cert bytes", private_key=b"key bytes" + ) + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/pubsub', + ), + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + assert transport._ssl_channel_credentials == mock_ssl_cred + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize("transport_class", [transports.SubscriberGrpcTransport, transports.SubscriberGrpcAsyncIOTransport]) +def test_subscriber_transport_channel_mtls_with_adc( + transport_class +): + mock_ssl_cred = mock.Mock() + with mock.patch.multiple( + "google.auth.transport.grpc.SslCredentials", + __init__=mock.Mock(return_value=None), + ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), + ): + with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + mock_cred = mock.Mock() + + with pytest.warns(DeprecationWarning): + transport = transport_class( + host="squid.clam.whelk", + credentials=mock_cred, + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=None, + ) + + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=mock_cred, + credentials_file=None, + scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/pubsub', + ), + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + + +def test_snapshot_path(): + project = "squid" + snapshot = "clam" + + expected = "projects/{project}/snapshots/{snapshot}".format(project=project, snapshot=snapshot, ) + actual = SubscriberClient.snapshot_path(project, snapshot) + assert expected == actual + + +def test_parse_snapshot_path(): + expected = { + "project": "whelk", + "snapshot": "octopus", + + } + path = SubscriberClient.snapshot_path(**expected) + + # Check that the path construction is reversible. + actual = SubscriberClient.parse_snapshot_path(path) + assert expected == actual + +def test_subscription_path(): + project = "oyster" + subscription = "nudibranch" + + expected = "projects/{project}/subscriptions/{subscription}".format(project=project, subscription=subscription, ) + actual = SubscriberClient.subscription_path(project, subscription) + assert expected == actual + + +def test_parse_subscription_path(): + expected = { + "project": "cuttlefish", + "subscription": "mussel", + + } + path = SubscriberClient.subscription_path(**expected) + + # Check that the path construction is reversible. + actual = SubscriberClient.parse_subscription_path(path) + assert expected == actual + +def test_topic_path(): + project = "winkle" + topic = "nautilus" + + expected = "projects/{project}/topics/{topic}".format(project=project, topic=topic, ) + actual = SubscriberClient.topic_path(project, topic) + assert expected == actual + + +def test_parse_topic_path(): + expected = { + "project": "scallop", + "topic": "abalone", + + } + path = SubscriberClient.topic_path(**expected) + + # Check that the path construction is reversible. + actual = SubscriberClient.parse_topic_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "squid" + + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = SubscriberClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "clam", + + } + path = SubscriberClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = SubscriberClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "whelk" + + expected = "folders/{folder}".format(folder=folder, ) + actual = SubscriberClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "octopus", + + } + path = SubscriberClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = SubscriberClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "oyster" + + expected = "organizations/{organization}".format(organization=organization, ) + actual = SubscriberClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "nudibranch", + + } + path = SubscriberClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = SubscriberClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "cuttlefish" + + expected = "projects/{project}".format(project=project, ) + actual = SubscriberClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "mussel", + + } + path = SubscriberClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = SubscriberClient.parse_common_project_path(path) + assert expected == actual + +def test_common_location_path(): + project = "winkle" + location = "nautilus" + + expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) + actual = SubscriberClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "scallop", + "location": "abalone", + + } + path = SubscriberClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = SubscriberClient.parse_common_location_path(path) + assert expected == actual + + +def test_client_withDEFAULT_CLIENT_INFO(): + client_info = gapic_v1.client_info.ClientInfo() + + with mock.patch.object(transports.SubscriberTransport, '_prep_wrapped_messages') as prep: + client = SubscriberClient( + credentials=credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.SubscriberTransport, '_prep_wrapped_messages') as prep: + transport_class = SubscriberClient.get_transport_class() + transport = transport_class( + credentials=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, + ) + + # Everything is optional 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() + + # 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",) + + response = client.set_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, policy.Policy) + + assert response.version == 774 + + assert response.etag == b"etag_blob" + + +@pytest.mark.asyncio +async def test_set_iam_policy_async(transport: str = "grpc_asyncio"): + client = SubscriberAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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() + + # 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",) + ) + + response = await client.set_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, policy.Policy) + + assert response.version == 774 + + assert response.etag == b"etag_blob" + + +def test_set_iam_policy_field_headers(): + client = SubscriberClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Any value 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.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() + + client.set_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_set_iam_policy_field_headers_async(): + client = SubscriberAsyncClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Any value 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.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()) + + await client.set_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] + + +def test_set_iam_policy_from_dict(): + client = SubscriberClient( + credentials=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() + + response = client.set_iam_policy( + request={ + "resource": "resource_value", + "policy": policy.Policy(version=774), + } + ) + call.assert_called() + + +@pytest.mark.asyncio +async def test_set_iam_policy_from_dict_async(): + client = SubscriberAsyncClient( + credentials=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() + ) + + response = await client.set_iam_policy( + request={ + "resource": "resource_value", + "policy": policy.Policy(version=774), + } + ) + call.assert_called() + + +def test_get_iam_policy(transport: str = "grpc"): + client = SubscriberClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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() + + # 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",) + + response = client.get_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, policy.Policy) + + assert response.version == 774 + + assert response.etag == b"etag_blob" + + +@pytest.mark.asyncio +async def test_get_iam_policy_async(transport: str = "grpc_asyncio"): + client = SubscriberAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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() + + # 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",) + ) + + response = await client.get_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, policy.Policy) + + assert response.version == 774 + + assert response.etag == b"etag_blob" + + +def test_get_iam_policy_field_headers(): + client = SubscriberClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Any value 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.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() + + client.get_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_get_iam_policy_field_headers_async(): + client = SubscriberAsyncClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Any value 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.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()) + + await client.get_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] + + +def test_get_iam_policy_from_dict(): + client = SubscriberClient( + credentials=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() + + response = client.get_iam_policy( + request={ + "resource": "resource_value", + "options": options.GetPolicyOptions(requested_policy_version=2598), + } + ) + call.assert_called() + +@pytest.mark.asyncio +async def test_get_iam_policy_from_dict_async(): + client = SubscriberAsyncClient( + credentials=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() + ) + + response = await client.get_iam_policy( + request={ + "resource": "resource_value", + "options": options.GetPolicyOptions(requested_policy_version=2598), + } + ) + call.assert_called() + + +def test_test_iam_permissions(transport: str = "grpc"): + client = SubscriberClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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() + + # 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( + permissions=["permissions_value"], + ) + + response = client.test_iam_permissions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, iam_policy.TestIamPermissionsResponse) + + assert response.permissions == ["permissions_value"] + + +@pytest.mark.asyncio +async def test_test_iam_permissions_async(transport: str = "grpc_asyncio"): + client = SubscriberAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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() + + # 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(permissions=["permissions_value"],) + ) + + response = await client.test_iam_permissions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, iam_policy.TestIamPermissionsResponse) + + assert response.permissions == ["permissions_value"] + + +def test_test_iam_permissions_field_headers(): + client = SubscriberClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Any value 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.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() + + client.test_iam_permissions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_test_iam_permissions_field_headers_async(): + client = SubscriberAsyncClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Any value 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.resource = "resource/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + iam_policy.TestIamPermissionsResponse() + ) + + await client.test_iam_permissions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] + + +def test_test_iam_permissions_from_dict(): + client = SubscriberClient( + credentials=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() + + response = client.test_iam_permissions( + request={ + "resource": "resource_value", + "permissions": ["permissions_value"], + } + ) + call.assert_called() + +@pytest.mark.asyncio +async def test_test_iam_permissions_from_dict_async(): + client = SubscriberAsyncClient( + credentials=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() + ) + + response = await client.test_iam_permissions( + request={ + "resource": "resource_value", + "permissions": ["permissions_value"], + } + ) + call.assert_called() From 232118d289747297774b85fee9ca808fe670848c Mon Sep 17 00:00:00 2001 From: Anthonios Partheniou Date: Wed, 12 May 2021 21:44:59 -0400 Subject: [PATCH 03/14] chore: run the post processor --- .pre-commit-config.yaml | 2 +- CONTRIBUTING.rst | 16 +- noxfile.py | 14 +- owl-bot-staging/v1/MANIFEST.in | 2 - owl-bot-staging/v1/README.rst | 49 - owl-bot-staging/v1/docs/conf.py | 378 -- owl-bot-staging/v1/docs/index.rst | 7 - .../v1/docs/pubsub_v1/publisher.rst | 11 - .../v1/docs/pubsub_v1/schema_service.rst | 11 - .../v1/docs/pubsub_v1/services.rst | 8 - .../v1/docs/pubsub_v1/subscriber.rst | 11 - owl-bot-staging/v1/docs/pubsub_v1/types.rst | 7 - owl-bot-staging/v1/google/pubsub/__init__.py | 144 - owl-bot-staging/v1/google/pubsub/py.typed | 2 - .../v1/google/pubsub_v1/__init__.py | 139 - owl-bot-staging/v1/google/pubsub_v1/py.typed | 2 - .../v1/google/pubsub_v1/services/__init__.py | 16 - .../pubsub_v1/services/publisher/__init__.py | 24 - .../services/publisher/async_client.py | 1236 ---- .../pubsub_v1/services/publisher/client.py | 1340 ---- .../pubsub_v1/services/publisher/pagers.py | 386 -- .../services/publisher/transports/__init__.py | 35 - .../services/publisher/transports/base.py | 368 -- .../services/publisher/transports/grpc.py | 558 -- .../publisher/transports/grpc_asyncio.py | 564 -- .../services/schema_service/__init__.py | 24 - .../services/schema_service/async_client.py | 906 --- .../services/schema_service/client.py | 1085 ---- .../services/schema_service/pagers.py | 142 - .../schema_service/transports/__init__.py | 35 - .../schema_service/transports/base.py | 232 - .../schema_service/transports/grpc.py | 461 -- .../schema_service/transports/grpc_asyncio.py | 467 -- .../pubsub_v1/services/subscriber/__init__.py | 24 - .../services/subscriber/async_client.py | 1994 ------ .../pubsub_v1/services/subscriber/client.py | 2032 ------- .../pubsub_v1/services/subscriber/pagers.py | 264 - .../subscriber/transports/__init__.py | 35 - .../services/subscriber/transports/base.py | 533 -- .../services/subscriber/transports/grpc.py | 820 --- .../subscriber/transports/grpc_asyncio.py | 826 --- .../v1/google/pubsub_v1/types/__init__.py | 136 - .../v1/google/pubsub_v1/types/pubsub.py | 1372 ----- .../v1/google/pubsub_v1/types/schema.py | 262 - owl-bot-staging/v1/mypy.ini | 3 - owl-bot-staging/v1/noxfile.py | 72 - .../v1/scripts/fixup_pubsub_v1_keywords.py | 213 - owl-bot-staging/v1/setup.py | 56 - .../v1/tests/unit/gapic/pubsub_v1/__init__.py | 17 - .../unit/gapic/pubsub_v1/test_publisher.py | 3983 ------------ .../gapic/pubsub_v1/test_schema_service.py | 2900 --------- .../unit/gapic/pubsub_v1/test_subscriber.py | 5363 ----------------- 52 files changed, 4 insertions(+), 29583 deletions(-) delete mode 100644 owl-bot-staging/v1/MANIFEST.in delete mode 100644 owl-bot-staging/v1/README.rst delete mode 100644 owl-bot-staging/v1/docs/conf.py delete mode 100644 owl-bot-staging/v1/docs/index.rst delete mode 100644 owl-bot-staging/v1/docs/pubsub_v1/publisher.rst delete mode 100644 owl-bot-staging/v1/docs/pubsub_v1/schema_service.rst delete mode 100644 owl-bot-staging/v1/docs/pubsub_v1/services.rst delete mode 100644 owl-bot-staging/v1/docs/pubsub_v1/subscriber.rst delete mode 100644 owl-bot-staging/v1/docs/pubsub_v1/types.rst delete mode 100644 owl-bot-staging/v1/google/pubsub/__init__.py delete mode 100644 owl-bot-staging/v1/google/pubsub/py.typed delete mode 100644 owl-bot-staging/v1/google/pubsub_v1/__init__.py delete mode 100644 owl-bot-staging/v1/google/pubsub_v1/py.typed delete mode 100644 owl-bot-staging/v1/google/pubsub_v1/services/__init__.py delete mode 100644 owl-bot-staging/v1/google/pubsub_v1/services/publisher/__init__.py delete mode 100644 owl-bot-staging/v1/google/pubsub_v1/services/publisher/async_client.py delete mode 100644 owl-bot-staging/v1/google/pubsub_v1/services/publisher/client.py delete mode 100644 owl-bot-staging/v1/google/pubsub_v1/services/publisher/pagers.py delete mode 100644 owl-bot-staging/v1/google/pubsub_v1/services/publisher/transports/__init__.py delete mode 100644 owl-bot-staging/v1/google/pubsub_v1/services/publisher/transports/base.py delete mode 100644 owl-bot-staging/v1/google/pubsub_v1/services/publisher/transports/grpc.py delete mode 100644 owl-bot-staging/v1/google/pubsub_v1/services/publisher/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/v1/google/pubsub_v1/services/schema_service/__init__.py delete mode 100644 owl-bot-staging/v1/google/pubsub_v1/services/schema_service/async_client.py delete mode 100644 owl-bot-staging/v1/google/pubsub_v1/services/schema_service/client.py delete mode 100644 owl-bot-staging/v1/google/pubsub_v1/services/schema_service/pagers.py delete mode 100644 owl-bot-staging/v1/google/pubsub_v1/services/schema_service/transports/__init__.py delete mode 100644 owl-bot-staging/v1/google/pubsub_v1/services/schema_service/transports/base.py delete mode 100644 owl-bot-staging/v1/google/pubsub_v1/services/schema_service/transports/grpc.py delete mode 100644 owl-bot-staging/v1/google/pubsub_v1/services/schema_service/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/v1/google/pubsub_v1/services/subscriber/__init__.py delete mode 100644 owl-bot-staging/v1/google/pubsub_v1/services/subscriber/async_client.py delete mode 100644 owl-bot-staging/v1/google/pubsub_v1/services/subscriber/client.py delete mode 100644 owl-bot-staging/v1/google/pubsub_v1/services/subscriber/pagers.py delete mode 100644 owl-bot-staging/v1/google/pubsub_v1/services/subscriber/transports/__init__.py delete mode 100644 owl-bot-staging/v1/google/pubsub_v1/services/subscriber/transports/base.py delete mode 100644 owl-bot-staging/v1/google/pubsub_v1/services/subscriber/transports/grpc.py delete mode 100644 owl-bot-staging/v1/google/pubsub_v1/services/subscriber/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/v1/google/pubsub_v1/types/__init__.py delete mode 100644 owl-bot-staging/v1/google/pubsub_v1/types/pubsub.py delete mode 100644 owl-bot-staging/v1/google/pubsub_v1/types/schema.py delete mode 100644 owl-bot-staging/v1/mypy.ini delete mode 100644 owl-bot-staging/v1/noxfile.py delete mode 100644 owl-bot-staging/v1/scripts/fixup_pubsub_v1_keywords.py delete mode 100644 owl-bot-staging/v1/setup.py delete mode 100644 owl-bot-staging/v1/tests/unit/gapic/pubsub_v1/__init__.py delete mode 100644 owl-bot-staging/v1/tests/unit/gapic/pubsub_v1/test_publisher.py delete mode 100644 owl-bot-staging/v1/tests/unit/gapic/pubsub_v1/test_schema_service.py delete mode 100644 owl-bot-staging/v1/tests/unit/gapic/pubsub_v1/test_subscriber.py diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 8912e9b5d..1bbd78783 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -26,6 +26,6 @@ repos: hooks: - id: black - repo: https://gitlab.com/pycqa/flake8 - rev: 3.9.0 + rev: 3.9.1 hooks: - id: flake8 diff --git a/CONTRIBUTING.rst b/CONTRIBUTING.rst index 6dbc9d2d6..55453e840 100644 --- a/CONTRIBUTING.rst +++ b/CONTRIBUTING.rst @@ -160,21 +160,7 @@ Running System Tests 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 diff --git a/noxfile.py b/noxfile.py index 6ccdf5e63..e8dbd3f17 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") diff --git a/owl-bot-staging/v1/MANIFEST.in b/owl-bot-staging/v1/MANIFEST.in deleted file mode 100644 index 4daeccbde..000000000 --- a/owl-bot-staging/v1/MANIFEST.in +++ /dev/null @@ -1,2 +0,0 @@ -recursive-include google/pubsub *.py -recursive-include google/pubsub_v1 *.py diff --git a/owl-bot-staging/v1/README.rst b/owl-bot-staging/v1/README.rst deleted file mode 100644 index 4c7897d8f..000000000 --- a/owl-bot-staging/v1/README.rst +++ /dev/null @@ -1,49 +0,0 @@ -Python Client for Google Pubsub API -================================================= - -Quick Start ------------ - -In order to use this library, you first need to go through the following steps: - -1. `Select or create a Cloud Platform project.`_ -2. `Enable billing for your project.`_ -3. Enable the Google Pubsub API. -4. `Setup Authentication.`_ - -.. _Select or create a Cloud Platform project.: https://console.cloud.google.com/project -.. _Enable billing for your project.: https://cloud.google.com/billing/docs/how-to/modify-project#enable_billing_for_a_project -.. _Setup Authentication.: https://googleapis.dev/python/google-api-core/latest/auth.html - -Installation -~~~~~~~~~~~~ - -Install this library in a `virtualenv`_ using pip. `virtualenv`_ is a tool to -create isolated Python environments. The basic problem it addresses is one of -dependencies and versions, and indirectly permissions. - -With `virtualenv`_, it's possible to install this library without needing system -install permissions, and without clashing with the installed system -dependencies. - -.. _`virtualenv`: https://virtualenv.pypa.io/en/latest/ - - -Mac/Linux -^^^^^^^^^ - -.. code-block:: console - - python3 -m venv - source /bin/activate - /bin/pip install /path/to/library - - -Windows -^^^^^^^ - -.. code-block:: console - - python3 -m venv - \Scripts\activate - \Scripts\pip.exe install \path\to\library diff --git a/owl-bot-staging/v1/docs/conf.py b/owl-bot-staging/v1/docs/conf.py deleted file mode 100644 index 3bfe4fa16..000000000 --- a/owl-bot-staging/v1/docs/conf.py +++ /dev/null @@ -1,378 +0,0 @@ -# -*- coding: utf-8 -*- - -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -# -# google-pubsub documentation build configuration file -# -# This file is execfile()d with the current directory set to its -# containing dir. -# -# Note that not all possible configuration values are present in this -# autogenerated file. -# -# All configuration values have a default; values that are commented out -# serve to show the default. - -import sys -import os -import shlex - -# If extensions (or modules to document with autodoc) are in another directory, -# add these directories to sys.path here. If the directory is relative to the -# documentation root, use os.path.abspath to make it absolute, like shown here. -sys.path.insert(0, os.path.abspath("..")) - -__version__ = "0.1.0" - -# -- General configuration ------------------------------------------------ - -# If your documentation needs a minimal Sphinx version, state it here. -needs_sphinx = "1.6.3" - -# Add any Sphinx extension module names here, as strings. They can be -# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom -# ones. -extensions = [ - "sphinx.ext.autodoc", - "sphinx.ext.autosummary", - "sphinx.ext.intersphinx", - "sphinx.ext.coverage", - "sphinx.ext.napoleon", - "sphinx.ext.todo", - "sphinx.ext.viewcode", -] - -# autodoc/autosummary flags -autoclass_content = "both" -autodoc_default_flags = ["members"] -autosummary_generate = True - - -# Add any paths that contain templates here, relative to this directory. -templates_path = ["_templates"] - -# Allow markdown includes (so releases.md can include CHANGLEOG.md) -# http://www.sphinx-doc.org/en/master/markdown.html -source_parsers = {".md": "recommonmark.parser.CommonMarkParser"} - -# The suffix(es) of source filenames. -# You can specify multiple suffix as a list of string: -source_suffix = [".rst", ".md"] - -# The encoding of source files. -# source_encoding = 'utf-8-sig' - -# The master toctree document. -master_doc = "index" - -# General information about the project. -project = u"google-pubsub" -copyright = u"2020, Google, LLC" -author = u"Google APIs" # TODO: autogenerate this bit - -# The version info for the project you're documenting, acts as replacement for -# |version| and |release|, also used in various other places throughout the -# built documents. -# -# The full version, including alpha/beta/rc tags. -release = __version__ -# The short X.Y version. -version = ".".join(release.split(".")[0:2]) - -# The language for content autogenerated by Sphinx. Refer to documentation -# for a list of supported languages. -# -# This is also used if you do content translation via gettext catalogs. -# Usually you set "language" from the command line for these cases. -language = None - -# There are two options for replacing |today|: either, you set today to some -# non-false value, then it is used: -# today = '' -# Else, today_fmt is used as the format for a strftime call. -# today_fmt = '%B %d, %Y' - -# List of patterns, relative to source directory, that match files and -# directories to ignore when looking for source files. -exclude_patterns = ["_build"] - -# The reST default role (used for this markup: `text`) to use for all -# documents. -# default_role = None - -# If true, '()' will be appended to :func: etc. cross-reference text. -# add_function_parentheses = True - -# If true, the current module name will be prepended to all description -# unit titles (such as .. function::). -# add_module_names = True - -# If true, sectionauthor and moduleauthor directives will be shown in the -# output. They are ignored by default. -# show_authors = False - -# The name of the Pygments (syntax highlighting) style to use. -pygments_style = "sphinx" - -# A list of ignored prefixes for module index sorting. -# modindex_common_prefix = [] - -# If true, keep warnings as "system message" paragraphs in the built documents. -# keep_warnings = False - -# If true, `todo` and `todoList` produce output, else they produce nothing. -todo_include_todos = True - - -# -- Options for HTML output ---------------------------------------------- - -# The theme to use for HTML and HTML Help pages. See the documentation for -# a list of builtin themes. -html_theme = "alabaster" - -# Theme options are theme-specific and customize the look and feel of a theme -# further. For a list of options available for each theme, see the -# documentation. -html_theme_options = { - "description": "Google Client Libraries for Python", - "github_user": "googleapis", - "github_repo": "google-cloud-python", - "github_banner": True, - "font_family": "'Roboto', Georgia, sans", - "head_font_family": "'Roboto', Georgia, serif", - "code_font_family": "'Roboto Mono', 'Consolas', monospace", -} - -# Add any paths that contain custom themes here, relative to this directory. -# html_theme_path = [] - -# The name for this set of Sphinx documents. If None, it defaults to -# " v documentation". -# html_title = None - -# A shorter title for the navigation bar. Default is the same as html_title. -# html_short_title = None - -# The name of an image file (relative to this directory) to place at the top -# of the sidebar. -# html_logo = None - -# The name of an image file (within the static path) to use as favicon of the -# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 -# pixels large. -# html_favicon = None - -# Add any paths that contain custom static files (such as style sheets) here, -# relative to this directory. They are copied after the builtin static files, -# so a file named "default.css" will overwrite the builtin "default.css". -html_static_path = ["_static"] - -# Add any extra paths that contain custom files (such as robots.txt or -# .htaccess) here, relative to this directory. These files are copied -# directly to the root of the documentation. -# html_extra_path = [] - -# If not '', a 'Last updated on:' timestamp is inserted at every page bottom, -# using the given strftime format. -# html_last_updated_fmt = '%b %d, %Y' - -# If true, SmartyPants will be used to convert quotes and dashes to -# typographically correct entities. -# html_use_smartypants = True - -# Custom sidebar templates, maps document names to template names. -# html_sidebars = {} - -# Additional templates that should be rendered to pages, maps page names to -# template names. -# html_additional_pages = {} - -# If false, no module index is generated. -# html_domain_indices = True - -# If false, no index is generated. -# html_use_index = True - -# If true, the index is split into individual pages for each letter. -# html_split_index = False - -# If true, links to the reST sources are added to the pages. -# html_show_sourcelink = True - -# If true, "Created using Sphinx" is shown in the HTML footer. Default is True. -# html_show_sphinx = True - -# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. -# html_show_copyright = True - -# If true, an OpenSearch description file will be output, and all pages will -# contain a tag referring to it. The value of this option must be the -# base URL from which the finished HTML is served. -# html_use_opensearch = '' - -# This is the file name suffix for HTML files (e.g. ".xhtml"). -# html_file_suffix = None - -# Language to be used for generating the HTML full-text search index. -# Sphinx supports the following languages: -# 'da', 'de', 'en', 'es', 'fi', 'fr', 'hu', 'it', 'ja' -# 'nl', 'no', 'pt', 'ro', 'ru', 'sv', 'tr' -# html_search_language = 'en' - -# A dictionary with options for the search language support, empty by default. -# Now only 'ja' uses this config value -# html_search_options = {'type': 'default'} - -# The name of a javascript file (relative to the configuration directory) that -# implements a search results scorer. If empty, the default will be used. -# html_search_scorer = 'scorer.js' - -# Output file base name for HTML help builder. -htmlhelp_basename = "google-pubsub-doc" - -# -- Options for warnings ------------------------------------------------------ - - -suppress_warnings = [ - # Temporarily suppress this to avoid "more than one target found for - # cross-reference" warning, which are intractable for us to avoid while in - # a mono-repo. - # See https://github.com/sphinx-doc/sphinx/blob - # /2a65ffeef5c107c19084fabdd706cdff3f52d93c/sphinx/domains/python.py#L843 - "ref.python" -] - -# -- Options for LaTeX output --------------------------------------------- - -latex_elements = { - # The paper size ('letterpaper' or 'a4paper'). - # 'papersize': 'letterpaper', - # The font size ('10pt', '11pt' or '12pt'). - # 'pointsize': '10pt', - # Additional stuff for the LaTeX preamble. - # 'preamble': '', - # Latex figure (float) alignment - # 'figure_align': 'htbp', -} - -# Grouping the document tree into LaTeX files. List of tuples -# (source start file, target name, title, -# author, documentclass [howto, manual, or own class]). -latex_documents = [ - ( - master_doc, - "google-pubsub.tex", - u"google-pubsub Documentation", - author, - "manual", - ) -] - -# The name of an image file (relative to this directory) to place at the top of -# the title page. -# latex_logo = None - -# For "manual" documents, if this is true, then toplevel headings are parts, -# not chapters. -# latex_use_parts = False - -# If true, show page references after internal links. -# latex_show_pagerefs = False - -# If true, show URL addresses after external links. -# latex_show_urls = False - -# Documents to append as an appendix to all manuals. -# latex_appendices = [] - -# If false, no module index is generated. -# latex_domain_indices = True - - -# -- Options for manual page output --------------------------------------- - -# One entry per manual page. List of tuples -# (source start file, name, description, authors, manual section). -man_pages = [ - ( - master_doc, - "google-pubsub", - u"Google Pubsub Documentation", - [author], - 1, - ) -] - -# If true, show URL addresses after external links. -# man_show_urls = False - - -# -- Options for Texinfo output ------------------------------------------- - -# Grouping the document tree into Texinfo files. List of tuples -# (source start file, target name, title, author, -# dir menu entry, description, category) -texinfo_documents = [ - ( - master_doc, - "google-pubsub", - u"google-pubsub Documentation", - author, - "google-pubsub", - "GAPIC library for Google Pubsub API", - "APIs", - ) -] - -# Documents to append as an appendix to all manuals. -# texinfo_appendices = [] - -# If false, no module index is generated. -# texinfo_domain_indices = True - -# How to display URL addresses: 'footnote', 'no', or 'inline'. -# texinfo_show_urls = 'footnote' - -# If true, do not generate a @detailmenu in the "Top" node's menu. -# texinfo_no_detailmenu = False - - -# Example configuration for intersphinx: refer to the Python standard library. -intersphinx_mapping = { - "python": ("http://python.readthedocs.org/en/latest/", None), - "gax": ("https://gax-python.readthedocs.org/en/latest/", None), - "google-auth": ("https://google-auth.readthedocs.io/en/stable", None), - "google-gax": ("https://gax-python.readthedocs.io/en/latest/", None), - "google.api_core": ("https://googleapis.dev/python/google-api-core/latest/", None), - "grpc": ("https://grpc.io/grpc/python/", None), - "requests": ("http://requests.kennethreitz.org/en/stable/", None), - "proto": ("https://proto-plus-python.readthedocs.io/en/stable", None), - "protobuf": ("https://googleapis.dev/python/protobuf/latest/", None), -} - - -# Napoleon settings -napoleon_google_docstring = True -napoleon_numpy_docstring = True -napoleon_include_private_with_doc = False -napoleon_include_special_with_doc = True -napoleon_use_admonition_for_examples = False -napoleon_use_admonition_for_notes = False -napoleon_use_admonition_for_references = False -napoleon_use_ivar = False -napoleon_use_param = True -napoleon_use_rtype = True diff --git a/owl-bot-staging/v1/docs/index.rst b/owl-bot-staging/v1/docs/index.rst deleted file mode 100644 index 5cb0459d0..000000000 --- a/owl-bot-staging/v1/docs/index.rst +++ /dev/null @@ -1,7 +0,0 @@ -API Reference -------------- -.. toctree:: - :maxdepth: 2 - - pubsub_v1/services - pubsub_v1/types diff --git a/owl-bot-staging/v1/docs/pubsub_v1/publisher.rst b/owl-bot-staging/v1/docs/pubsub_v1/publisher.rst deleted file mode 100644 index bc5c9c7d0..000000000 --- a/owl-bot-staging/v1/docs/pubsub_v1/publisher.rst +++ /dev/null @@ -1,11 +0,0 @@ -Publisher ---------------------------- - -.. automodule:: google.pubsub_v1.services.publisher - :members: - :inherited-members: - - -.. automodule:: google.pubsub_v1.services.publisher.pagers - :members: - :inherited-members: diff --git a/owl-bot-staging/v1/docs/pubsub_v1/schema_service.rst b/owl-bot-staging/v1/docs/pubsub_v1/schema_service.rst deleted file mode 100644 index c52db7a12..000000000 --- a/owl-bot-staging/v1/docs/pubsub_v1/schema_service.rst +++ /dev/null @@ -1,11 +0,0 @@ -SchemaService -------------------------------- - -.. automodule:: google.pubsub_v1.services.schema_service - :members: - :inherited-members: - - -.. automodule:: google.pubsub_v1.services.schema_service.pagers - :members: - :inherited-members: diff --git a/owl-bot-staging/v1/docs/pubsub_v1/services.rst b/owl-bot-staging/v1/docs/pubsub_v1/services.rst deleted file mode 100644 index 6ab7d9e52..000000000 --- a/owl-bot-staging/v1/docs/pubsub_v1/services.rst +++ /dev/null @@ -1,8 +0,0 @@ -Services for Google Pubsub v1 API -================================= -.. toctree:: - :maxdepth: 2 - - publisher - schema_service - subscriber diff --git a/owl-bot-staging/v1/docs/pubsub_v1/subscriber.rst b/owl-bot-staging/v1/docs/pubsub_v1/subscriber.rst deleted file mode 100644 index 808840ed7..000000000 --- a/owl-bot-staging/v1/docs/pubsub_v1/subscriber.rst +++ /dev/null @@ -1,11 +0,0 @@ -Subscriber ----------------------------- - -.. automodule:: google.pubsub_v1.services.subscriber - :members: - :inherited-members: - - -.. automodule:: google.pubsub_v1.services.subscriber.pagers - :members: - :inherited-members: diff --git a/owl-bot-staging/v1/docs/pubsub_v1/types.rst b/owl-bot-staging/v1/docs/pubsub_v1/types.rst deleted file mode 100644 index 964dfe575..000000000 --- a/owl-bot-staging/v1/docs/pubsub_v1/types.rst +++ /dev/null @@ -1,7 +0,0 @@ -Types for Google Pubsub v1 API -============================== - -.. automodule:: google.pubsub_v1.types - :members: - :undoc-members: - :show-inheritance: diff --git a/owl-bot-staging/v1/google/pubsub/__init__.py b/owl-bot-staging/v1/google/pubsub/__init__.py deleted file mode 100644 index 3af00486b..000000000 --- a/owl-bot-staging/v1/google/pubsub/__init__.py +++ /dev/null @@ -1,144 +0,0 @@ -# -*- coding: utf-8 -*- - -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -from google.pubsub_v1.services.publisher.async_client import PublisherAsyncClient -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.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 -from google.pubsub_v1.types.pubsub import DeleteSnapshotRequest -from google.pubsub_v1.types.pubsub import DeleteSubscriptionRequest -from google.pubsub_v1.types.pubsub import DeleteTopicRequest -from google.pubsub_v1.types.pubsub import DetachSubscriptionRequest -from google.pubsub_v1.types.pubsub import DetachSubscriptionResponse -from google.pubsub_v1.types.pubsub import ExpirationPolicy -from google.pubsub_v1.types.pubsub import GetSnapshotRequest -from google.pubsub_v1.types.pubsub import GetSubscriptionRequest -from google.pubsub_v1.types.pubsub import GetTopicRequest -from google.pubsub_v1.types.pubsub import ListSnapshotsRequest -from google.pubsub_v1.types.pubsub import ListSnapshotsResponse -from google.pubsub_v1.types.pubsub import ListSubscriptionsRequest -from google.pubsub_v1.types.pubsub import ListSubscriptionsResponse -from google.pubsub_v1.types.pubsub import ListTopicSnapshotsRequest -from google.pubsub_v1.types.pubsub import ListTopicSnapshotsResponse -from google.pubsub_v1.types.pubsub import 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 -from google.pubsub_v1.types.pubsub import PublishRequest -from google.pubsub_v1.types.pubsub import PublishResponse -from google.pubsub_v1.types.pubsub import PubsubMessage -from google.pubsub_v1.types.pubsub import PullRequest -from google.pubsub_v1.types.pubsub import PullResponse -from google.pubsub_v1.types.pubsub import PushConfig -from google.pubsub_v1.types.pubsub import ReceivedMessage -from google.pubsub_v1.types.pubsub import RetryPolicy -from google.pubsub_v1.types.pubsub import SchemaSettings -from google.pubsub_v1.types.pubsub import SeekRequest -from google.pubsub_v1.types.pubsub import SeekResponse -from google.pubsub_v1.types.pubsub import Snapshot -from google.pubsub_v1.types.pubsub import StreamingPullRequest -from google.pubsub_v1.types.pubsub import StreamingPullResponse -from google.pubsub_v1.types.pubsub import Subscription -from google.pubsub_v1.types.pubsub import Topic -from google.pubsub_v1.types.pubsub import UpdateSnapshotRequest -from google.pubsub_v1.types.pubsub import UpdateSubscriptionRequest -from google.pubsub_v1.types.pubsub import UpdateTopicRequest -from google.pubsub_v1.types.schema import CreateSchemaRequest -from google.pubsub_v1.types.schema import DeleteSchemaRequest -from google.pubsub_v1.types.schema import 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 - -__all__ = ( - 'AcknowledgeRequest', - 'CreateSchemaRequest', - 'CreateSnapshotRequest', - 'DeadLetterPolicy', - 'DeleteSchemaRequest', - 'DeleteSnapshotRequest', - 'DeleteSubscriptionRequest', - 'DeleteTopicRequest', - 'DetachSubscriptionRequest', - 'DetachSubscriptionResponse', - 'Encoding', - 'ExpirationPolicy', - 'GetSchemaRequest', - 'GetSnapshotRequest', - 'GetSubscriptionRequest', - 'GetTopicRequest', - 'ListSchemasRequest', - 'ListSchemasResponse', - 'ListSnapshotsRequest', - 'ListSnapshotsResponse', - 'ListSubscriptionsRequest', - 'ListSubscriptionsResponse', - 'ListTopicSnapshotsRequest', - 'ListTopicSnapshotsResponse', - 'ListTopicSubscriptionsRequest', - 'ListTopicSubscriptionsResponse', - 'ListTopicsRequest', - 'ListTopicsResponse', - 'MessageStoragePolicy', - 'ModifyAckDeadlineRequest', - 'ModifyPushConfigRequest', - 'PublishRequest', - 'PublishResponse', - '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', - 'ValidateMessageRequest', - 'ValidateMessageResponse', - 'ValidateSchemaRequest', - 'ValidateSchemaResponse', -) diff --git a/owl-bot-staging/v1/google/pubsub/py.typed b/owl-bot-staging/v1/google/pubsub/py.typed deleted file mode 100644 index 9b0e37433..000000000 --- a/owl-bot-staging/v1/google/pubsub/py.typed +++ /dev/null @@ -1,2 +0,0 @@ -# Marker file for PEP 561. -# The google-pubsub package uses inline types. diff --git a/owl-bot-staging/v1/google/pubsub_v1/__init__.py b/owl-bot-staging/v1/google/pubsub_v1/__init__.py deleted file mode 100644 index 4fbae4d67..000000000 --- a/owl-bot-staging/v1/google/pubsub_v1/__init__.py +++ /dev/null @@ -1,139 +0,0 @@ -# -*- coding: utf-8 -*- - -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -from .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 -from .types.pubsub import DeleteSnapshotRequest -from .types.pubsub import DeleteSubscriptionRequest -from .types.pubsub import DeleteTopicRequest -from .types.pubsub import DetachSubscriptionRequest -from .types.pubsub import DetachSubscriptionResponse -from .types.pubsub import ExpirationPolicy -from .types.pubsub import GetSnapshotRequest -from .types.pubsub import GetSubscriptionRequest -from .types.pubsub import GetTopicRequest -from .types.pubsub import ListSnapshotsRequest -from .types.pubsub import ListSnapshotsResponse -from .types.pubsub import ListSubscriptionsRequest -from .types.pubsub import ListSubscriptionsResponse -from .types.pubsub import ListTopicSnapshotsRequest -from .types.pubsub import ListTopicSnapshotsResponse -from .types.pubsub import 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 -from .types.pubsub import PublishRequest -from .types.pubsub import PublishResponse -from .types.pubsub import PubsubMessage -from .types.pubsub import PullRequest -from .types.pubsub import PullResponse -from .types.pubsub import PushConfig -from .types.pubsub import ReceivedMessage -from .types.pubsub import RetryPolicy -from .types.pubsub import SchemaSettings -from .types.pubsub import SeekRequest -from .types.pubsub import SeekResponse -from .types.pubsub import Snapshot -from .types.pubsub import StreamingPullRequest -from .types.pubsub import StreamingPullResponse -from .types.pubsub import Subscription -from .types.pubsub import Topic -from .types.pubsub import UpdateSnapshotRequest -from .types.pubsub import UpdateSubscriptionRequest -from .types.pubsub import UpdateTopicRequest -from .types.schema import CreateSchemaRequest -from .types.schema import DeleteSchemaRequest -from .types.schema import 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 - - -__all__ = ( - 'AcknowledgeRequest', - 'CreateSchemaRequest', - 'CreateSnapshotRequest', - 'DeadLetterPolicy', - 'DeleteSchemaRequest', - 'DeleteSnapshotRequest', - 'DeleteSubscriptionRequest', - 'DeleteTopicRequest', - 'DetachSubscriptionRequest', - 'DetachSubscriptionResponse', - 'Encoding', - 'ExpirationPolicy', - 'GetSchemaRequest', - 'GetSnapshotRequest', - 'GetSubscriptionRequest', - 'GetTopicRequest', - 'ListSchemasRequest', - 'ListSchemasResponse', - 'ListSnapshotsRequest', - 'ListSnapshotsResponse', - 'ListSubscriptionsRequest', - 'ListSubscriptionsResponse', - 'ListTopicSnapshotsRequest', - 'ListTopicSnapshotsResponse', - 'ListTopicSubscriptionsRequest', - 'ListTopicSubscriptionsResponse', - 'ListTopicsRequest', - 'ListTopicsResponse', - 'MessageStoragePolicy', - 'ModifyAckDeadlineRequest', - 'ModifyPushConfigRequest', - 'PublishRequest', - 'PublishResponse', - 'PubsubMessage', - 'PullRequest', - 'PullResponse', - 'PushConfig', - 'ReceivedMessage', - 'RetryPolicy', - 'Schema', - 'SchemaServiceClient', - 'SchemaSettings', - 'SchemaView', - 'SeekRequest', - 'SeekResponse', - 'Snapshot', - 'StreamingPullRequest', - 'StreamingPullResponse', - 'SubscriberClient', - 'Subscription', - 'Topic', - 'UpdateSnapshotRequest', - 'UpdateSubscriptionRequest', - 'UpdateTopicRequest', - 'ValidateMessageRequest', - 'ValidateMessageResponse', - 'ValidateSchemaRequest', - 'ValidateSchemaResponse', -'PublisherClient', -) diff --git a/owl-bot-staging/v1/google/pubsub_v1/py.typed b/owl-bot-staging/v1/google/pubsub_v1/py.typed deleted file mode 100644 index 9b0e37433..000000000 --- a/owl-bot-staging/v1/google/pubsub_v1/py.typed +++ /dev/null @@ -1,2 +0,0 @@ -# Marker file for PEP 561. -# The google-pubsub package uses inline types. diff --git a/owl-bot-staging/v1/google/pubsub_v1/services/__init__.py b/owl-bot-staging/v1/google/pubsub_v1/services/__init__.py deleted file mode 100644 index 42ffdf2bc..000000000 --- a/owl-bot-staging/v1/google/pubsub_v1/services/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ -# -*- coding: utf-8 -*- - -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# diff --git a/owl-bot-staging/v1/google/pubsub_v1/services/publisher/__init__.py b/owl-bot-staging/v1/google/pubsub_v1/services/publisher/__init__.py deleted file mode 100644 index 3ef7d2838..000000000 --- a/owl-bot-staging/v1/google/pubsub_v1/services/publisher/__init__.py +++ /dev/null @@ -1,24 +0,0 @@ -# -*- coding: utf-8 -*- - -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -from .client import PublisherClient -from .async_client import PublisherAsyncClient - -__all__ = ( - 'PublisherClient', - 'PublisherAsyncClient', -) diff --git a/owl-bot-staging/v1/google/pubsub_v1/services/publisher/async_client.py b/owl-bot-staging/v1/google/pubsub_v1/services/publisher/async_client.py deleted file mode 100644 index 35087e7ef..000000000 --- a/owl-bot-staging/v1/google/pubsub_v1/services/publisher/async_client.py +++ /dev/null @@ -1,1236 +0,0 @@ -# -*- coding: utf-8 -*- - -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -from collections import OrderedDict -import functools -import re -from typing import Dict, Sequence, Tuple, Type, Union -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 gapic_v1 # type: ignore -from google.api_core import retry as retries # type: ignore -from google.auth import 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.pubsub_v1.services.publisher import pagers -from google.pubsub_v1.types import pubsub - -from .transports.base import PublisherTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import PublisherGrpcAsyncIOTransport -from .client import PublisherClient - - -class PublisherAsyncClient: - """The service that an application uses to manipulate topics, - and to send messages to a topic. - """ - - _client: PublisherClient - - DEFAULT_ENDPOINT = PublisherClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = PublisherClient.DEFAULT_MTLS_ENDPOINT - - schema_path = staticmethod(PublisherClient.schema_path) - parse_schema_path = staticmethod(PublisherClient.parse_schema_path) - subscription_path = staticmethod(PublisherClient.subscription_path) - parse_subscription_path = staticmethod(PublisherClient.parse_subscription_path) - topic_path = staticmethod(PublisherClient.topic_path) - parse_topic_path = staticmethod(PublisherClient.parse_topic_path) - - common_billing_account_path = staticmethod(PublisherClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(PublisherClient.parse_common_billing_account_path) - - common_folder_path = staticmethod(PublisherClient.common_folder_path) - parse_common_folder_path = staticmethod(PublisherClient.parse_common_folder_path) - - common_organization_path = staticmethod(PublisherClient.common_organization_path) - parse_common_organization_path = staticmethod(PublisherClient.parse_common_organization_path) - - common_project_path = staticmethod(PublisherClient.common_project_path) - parse_common_project_path = staticmethod(PublisherClient.parse_common_project_path) - - common_location_path = staticmethod(PublisherClient.common_location_path) - parse_common_location_path = staticmethod(PublisherClient.parse_common_location_path) - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials info. - - Args: - info (dict): The service account private key info. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - PublisherAsyncClient: The constructed client. - """ - return PublisherClient.from_service_account_info.__func__(PublisherAsyncClient, info, *args, **kwargs) # type: ignore - - @classmethod - def from_service_account_file(cls, filename: str, *args, **kwargs): - """Creates an instance of this client using the provided credentials - file. - - Args: - filename (str): The path to the service account private key json - file. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - PublisherAsyncClient: The constructed client. - """ - return PublisherClient.from_service_account_file.__func__(PublisherAsyncClient, filename, *args, **kwargs) # type: ignore - - from_service_account_json = from_service_account_file - - @property - def transport(self) -> PublisherTransport: - """Return the transport used by the client instance. - - Returns: - PublisherTransport: The transport used by the client instance. - """ - return self._client.transport - - get_transport_class = functools.partial(type(PublisherClient).get_transport_class, type(PublisherClient)) - - def __init__(self, *, - credentials: credentials.Credentials = None, - transport: Union[str, PublisherTransport] = 'grpc_asyncio', - client_options: ClientOptions = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiate the publisher client. - - Args: - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - transport (Union[str, ~.PublisherTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (ClientOptions): Custom options for the client. It - won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - """ - - self._client = PublisherClient( - credentials=credentials, - transport=transport, - client_options=client_options, - client_info=client_info, - - ) - - async def create_topic(self, - request: pubsub.Topic = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pubsub.Topic: - r"""Creates the given topic with the given name. See the [resource - name rules] - (https://cloud.google.com/pubsub/docs/admin#resource_names). - - Args: - request (:class:`google.pubsub_v1.types.Topic`): - The request object. A topic resource. - name (:class:`str`): - Required. The name of the topic. It must have the format - ``"projects/{project}/topics/{topic}"``. ``{topic}`` - must start with a letter, and contain only letters - (``[A-Za-z]``), numbers (``[0-9]``), dashes (``-``), - underscores (``_``), periods (``.``), tildes (``~``), - plus (``+``) or percent signs (``%``). It must be - between 3 and 255 characters in length, and it must not - start with ``"goog"``. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.pubsub_v1.types.Topic: - A topic resource. - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - request = pubsub.Topic(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.create_topic, - default_retry=retries.Retry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('name', request.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def update_topic(self, - request: pubsub.UpdateTopicRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pubsub.Topic: - r"""Updates an existing topic. Note that certain - properties of a topic are not modifiable. - - 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 (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.pubsub_v1.types.Topic: - A topic resource. - """ - # Create or coerce a protobuf request object. - - request = pubsub.UpdateTopicRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.update_topic, - default_retry=retries.Retry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('topic.name', request.topic.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def publish(self, - request: pubsub.PublishRequest = None, - *, - topic: str = None, - messages: Sequence[pubsub.PubsubMessage] = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pubsub.PublishResponse: - r"""Adds one or more messages to the topic. Returns ``NOT_FOUND`` if - the topic does not exist. - - Args: - request (:class:`google.pubsub_v1.types.PublishRequest`): - The request object. Request for the Publish method. - topic (:class:`str`): - Required. The messages in the request will be published - on this topic. Format is - ``projects/{project}/topics/{topic}``. - - This corresponds to the ``topic`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - messages (:class:`Sequence[google.pubsub_v1.types.PubsubMessage]`): - Required. The messages to publish. - This corresponds to the ``messages`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.pubsub_v1.types.PublishResponse: - Response for the Publish method. - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([topic, messages]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - request = pubsub.PublishRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - - if topic is not None: - request.topic = topic - - if messages: - request.messages.extend(messages) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.publish, - default_retry=retries.Retry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - exceptions.Aborted, - exceptions.Cancelled, - exceptions.DeadlineExceeded, - exceptions.InternalServerError, - exceptions.ResourceExhausted, - exceptions.ServiceUnavailable, - exceptions.Unknown, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('topic', request.topic), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def get_topic(self, - request: pubsub.GetTopicRequest = None, - *, - topic: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pubsub.Topic: - r"""Gets the configuration of a topic. - - Args: - request (:class:`google.pubsub_v1.types.GetTopicRequest`): - The request object. Request for the GetTopic method. - topic (:class:`str`): - Required. The name of the topic to get. Format is - ``projects/{project}/topics/{topic}``. - - This corresponds to the ``topic`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.pubsub_v1.types.Topic: - A topic resource. - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([topic]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - request = pubsub.GetTopicRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - - if topic is not None: - request.topic = topic - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.get_topic, - default_retry=retries.Retry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - exceptions.Aborted, - exceptions.ServiceUnavailable, - exceptions.Unknown, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('topic', request.topic), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def list_topics(self, - request: pubsub.ListTopicsRequest = None, - *, - project: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListTopicsAsyncPager: - r"""Lists matching topics. - - Args: - request (:class:`google.pubsub_v1.types.ListTopicsRequest`): - The request object. Request for the `ListTopics` method. - project (:class:`str`): - Required. The name of the project in which to list - topics. Format is ``projects/{project-id}``. - - This corresponds to the ``project`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.pubsub_v1.services.publisher.pagers.ListTopicsAsyncPager: - Response for the ListTopics method. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([project]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - request = pubsub.ListTopicsRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - - if project is not None: - request.project = project - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.list_topics, - default_retry=retries.Retry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - exceptions.Aborted, - exceptions.ServiceUnavailable, - exceptions.Unknown, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('project', request.project), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__aiter__` convenience method. - response = pagers.ListTopicsAsyncPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def list_topic_subscriptions(self, - request: pubsub.ListTopicSubscriptionsRequest = None, - *, - topic: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListTopicSubscriptionsAsyncPager: - r"""Lists the names of the attached subscriptions on this - topic. - - Args: - request (:class:`google.pubsub_v1.types.ListTopicSubscriptionsRequest`): - The request object. Request for the - `ListTopicSubscriptions` method. - topic (:class:`str`): - Required. The name of the topic that subscriptions are - attached to. Format is - ``projects/{project}/topics/{topic}``. - - This corresponds to the ``topic`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.pubsub_v1.services.publisher.pagers.ListTopicSubscriptionsAsyncPager: - Response for the ListTopicSubscriptions method. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([topic]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - request = pubsub.ListTopicSubscriptionsRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - - if topic is not None: - request.topic = topic - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.list_topic_subscriptions, - default_retry=retries.Retry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - exceptions.Aborted, - exceptions.ServiceUnavailable, - exceptions.Unknown, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('topic', request.topic), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__aiter__` convenience method. - response = pagers.ListTopicSubscriptionsAsyncPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def list_topic_snapshots(self, - request: pubsub.ListTopicSnapshotsRequest = None, - *, - topic: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListTopicSnapshotsAsyncPager: - r"""Lists the names of the snapshots on this topic. Snapshots are - used in - `Seek `__ - operations, which allow you to manage message acknowledgments in - bulk. That is, you can set the acknowledgment state of messages - in an existing subscription to the state captured by a snapshot. - - Args: - request (:class:`google.pubsub_v1.types.ListTopicSnapshotsRequest`): - The request object. Request for the `ListTopicSnapshots` - method. - topic (:class:`str`): - Required. The name of the topic that snapshots are - attached to. Format is - ``projects/{project}/topics/{topic}``. - - This corresponds to the ``topic`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.pubsub_v1.services.publisher.pagers.ListTopicSnapshotsAsyncPager: - Response for the ListTopicSnapshots method. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([topic]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - request = pubsub.ListTopicSnapshotsRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - - if topic is not None: - request.topic = topic - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.list_topic_snapshots, - default_retry=retries.Retry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - exceptions.Aborted, - exceptions.ServiceUnavailable, - exceptions.Unknown, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('topic', request.topic), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__aiter__` convenience method. - response = pagers.ListTopicSnapshotsAsyncPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def delete_topic(self, - request: pubsub.DeleteTopicRequest = None, - *, - topic: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes the topic with the given name. Returns ``NOT_FOUND`` if - the topic does not exist. After a topic is deleted, a new topic - may be created with the same name; this is an entirely new topic - with none of the old configuration or subscriptions. Existing - subscriptions to this topic are not deleted, but their ``topic`` - field is set to ``_deleted-topic_``. - - Args: - request (:class:`google.pubsub_v1.types.DeleteTopicRequest`): - The request object. Request for the `DeleteTopic` - method. - topic (:class:`str`): - Required. Name of the topic to delete. Format is - ``projects/{project}/topics/{topic}``. - - This corresponds to the ``topic`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([topic]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - request = pubsub.DeleteTopicRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - - if topic is not None: - request.topic = topic - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.delete_topic, - default_retry=retries.Retry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('topic', request.topic), - )), - ) - - # Send the request. - await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - async def detach_subscription(self, - request: pubsub.DetachSubscriptionRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pubsub.DetachSubscriptionResponse: - r"""Detaches a subscription from this topic. All messages retained - in the subscription are dropped. Subsequent ``Pull`` and - ``StreamingPull`` requests will return FAILED_PRECONDITION. If - the subscription is a push subscription, pushes to the endpoint - will stop. - - Args: - 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 (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.pubsub_v1.types.DetachSubscriptionResponse: - Response for the DetachSubscription - method. Reserved for future use. - - """ - # Create or coerce a protobuf request object. - - request = pubsub.DetachSubscriptionRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.detach_subscription, - default_retry=retries.Retry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('subscription', request.subscription), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def set_iam_policy( - self, - request: iam_policy.SetIamPolicyRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> policy.Policy: - r"""Sets the IAM access control policy on the specified - function. Replaces any existing policy. - Args: - request (:class:`~.iam_policy.SetIamPolicyRequest`): - The request object. Request message for `SetIamPolicy` - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.policy.Policy: - Defines an Identity and Access Management (IAM) policy. - It is used to specify access control policies for Cloud - Platform resources. - A ``Policy`` is a collection of ``bindings``. A - ``binding`` binds one or more ``members`` to a single - ``role``. Members can be user accounts, service - accounts, Google groups, and domains (such as G Suite). - A ``role`` is a named list of permissions (defined by - IAM or configured by users). A ``binding`` can - optionally specify a ``condition``, which is a logic - expression that further constrains the role binding - based on attributes about the request and/or target - resource. - **JSON Example** - :: - { - "bindings": [ - { - "role": "roles/resourcemanager.organizationAdmin", - "members": [ - "user:mike@example.com", - "group:admins@example.com", - "domain:google.com", - "serviceAccount:my-project-id@appspot.gserviceaccount.com" - ] - }, - { - "role": "roles/resourcemanager.organizationViewer", - "members": ["user:eve@example.com"], - "condition": { - "title": "expirable access", - "description": "Does not grant access after Sep 2020", - "expression": "request.time < - timestamp('2020-10-01T00:00:00.000Z')", - } - } - ] - } - **YAML Example** - :: - bindings: - - members: - - user:mike@example.com - - group:admins@example.com - - domain:google.com - - serviceAccount:my-project-id@appspot.gserviceaccount.com - role: roles/resourcemanager.organizationAdmin - - members: - - user:eve@example.com - role: roles/resourcemanager.organizationViewer - condition: - title: expirable access - description: Does not grant access after Sep 2020 - expression: request.time < timestamp('2020-10-01T00:00:00.000Z') - For a description of IAM and its features, see the `IAM - developer's - guide `__. - """ - # Create or coerce a protobuf request object. - - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = iam_policy.SetIamPolicyRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.set_iam_policy, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("resource", request.resource),)), - ) - - # Send the request. - response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - async def get_iam_policy( - self, - request: iam_policy.GetIamPolicyRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> policy.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`): - The request object. Request message for `GetIamPolicy` - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.policy.Policy: - Defines an Identity and Access Management (IAM) policy. - It is used to specify access control policies for Cloud - Platform resources. - A ``Policy`` is a collection of ``bindings``. A - ``binding`` binds one or more ``members`` to a single - ``role``. Members can be user accounts, service - accounts, Google groups, and domains (such as G Suite). - A ``role`` is a named list of permissions (defined by - IAM or configured by users). A ``binding`` can - optionally specify a ``condition``, which is a logic - expression that further constrains the role binding - based on attributes about the request and/or target - resource. - **JSON Example** - :: - { - "bindings": [ - { - "role": "roles/resourcemanager.organizationAdmin", - "members": [ - "user:mike@example.com", - "group:admins@example.com", - "domain:google.com", - "serviceAccount:my-project-id@appspot.gserviceaccount.com" - ] - }, - { - "role": "roles/resourcemanager.organizationViewer", - "members": ["user:eve@example.com"], - "condition": { - "title": "expirable access", - "description": "Does not grant access after Sep 2020", - "expression": "request.time < - timestamp('2020-10-01T00:00:00.000Z')", - } - } - ] - } - **YAML Example** - :: - bindings: - - members: - - user:mike@example.com - - group:admins@example.com - - domain:google.com - - serviceAccount:my-project-id@appspot.gserviceaccount.com - role: roles/resourcemanager.organizationAdmin - - members: - - user:eve@example.com - role: roles/resourcemanager.organizationViewer - condition: - title: expirable access - description: Does not grant access after Sep 2020 - expression: request.time < timestamp('2020-10-01T00:00:00.000Z') - For a description of IAM and its features, see the `IAM - developer's - guide `__. - """ - # Create or coerce a protobuf request object. - - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = iam_policy.GetIamPolicyRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.get_iam_policy, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("resource", request.resource),)), - ) - - # Send the request. - response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - async def test_iam_permissions( - self, - request: iam_policy.TestIamPermissionsRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> iam_policy.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`): - The request object. Request message for - `TestIamPermissions` method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.iam_policy.TestIamPermissionsResponse: - Response message for ``TestIamPermissions`` method. - """ - # Create or coerce a protobuf request object. - - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = iam_policy.TestIamPermissionsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.test_iam_permissions, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("resource", request.resource),)), - ) - - # Send the request. - response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - 'google-pubsub', - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - 'PublisherAsyncClient', -) diff --git a/owl-bot-staging/v1/google/pubsub_v1/services/publisher/client.py b/owl-bot-staging/v1/google/pubsub_v1/services/publisher/client.py deleted file mode 100644 index d37e13661..000000000 --- a/owl-bot-staging/v1/google/pubsub_v1/services/publisher/client.py +++ /dev/null @@ -1,1340 +0,0 @@ -# -*- coding: utf-8 -*- - -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -from collections import OrderedDict -from distutils import util -import os -import re -from typing import Callable, Dict, Optional, Sequence, Tuple, Type, Union -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 gapic_v1 # type: ignore -from google.api_core import retry as retries # type: ignore -from google.auth import 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.pubsub_v1.services.publisher import pagers -from google.pubsub_v1.types import pubsub - -from .transports.base import PublisherTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import PublisherGrpcTransport -from .transports.grpc_asyncio import PublisherGrpcAsyncIOTransport - - -class PublisherClientMeta(type): - """Metaclass for the Publisher client. - - This provides class-level methods for building and retrieving - support objects (e.g. transport) without polluting the client instance - objects. - """ - _transport_registry = OrderedDict() # type: Dict[str, Type[PublisherTransport]] - _transport_registry['grpc'] = PublisherGrpcTransport - _transport_registry['grpc_asyncio'] = PublisherGrpcAsyncIOTransport - - def get_transport_class(cls, - label: str = None, - ) -> Type[PublisherTransport]: - """Return an appropriate transport class. - - Args: - label: The name of the desired transport. If none is - provided, then the first transport in the registry is used. - - Returns: - The transport class to use. - """ - # If a specific transport is requested, return that one. - if label: - return cls._transport_registry[label] - - # No transport is requested; return the default (that is, the first one - # in the dictionary). - return next(iter(cls._transport_registry.values())) - - -class PublisherClient(metaclass=PublisherClientMeta): - """The service that an application uses to manipulate topics, - and to send messages to a topic. - """ - - @staticmethod - def _get_default_mtls_endpoint(api_endpoint): - """Convert api endpoint to mTLS endpoint. - Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to - "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. - Args: - api_endpoint (Optional[str]): the api endpoint to convert. - Returns: - str: converted mTLS api endpoint. - """ - if not api_endpoint: - return api_endpoint - - mtls_endpoint_re = re.compile( - r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" - ) - - m = mtls_endpoint_re.match(api_endpoint) - name, mtls, sandbox, googledomain = m.groups() - if mtls or not googledomain: - return api_endpoint - - if sandbox: - return api_endpoint.replace( - "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" - ) - - return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") - - DEFAULT_ENDPOINT = 'pubsub.googleapis.com' - DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore - DEFAULT_ENDPOINT - ) - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials info. - - Args: - info (dict): The service account private key info. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - PublisherClient: The constructed client. - """ - credentials = service_account.Credentials.from_service_account_info(info) - kwargs["credentials"] = credentials - return cls(*args, **kwargs) - - @classmethod - def from_service_account_file(cls, filename: str, *args, **kwargs): - """Creates an instance of this client using the provided credentials - file. - - Args: - filename (str): The path to the service account private key json - file. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - PublisherClient: The constructed client. - """ - credentials = service_account.Credentials.from_service_account_file( - filename) - kwargs['credentials'] = credentials - return cls(*args, **kwargs) - - from_service_account_json = from_service_account_file - - @property - def transport(self) -> PublisherTransport: - """Return the transport used by the client instance. - - Returns: - PublisherTransport: The transport used by the client instance. - """ - return self._transport - - @staticmethod - def schema_path(project: str,schema: str,) -> str: - """Return 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.""" - 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.""" - 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.""" - m = re.match(r"^projects/(?P.+?)/subscriptions/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def topic_path(project: str,topic: str,) -> str: - """Return 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.""" - 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.""" - return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - - @staticmethod - def parse_common_billing_account_path(path: str) -> Dict[str,str]: - """Parse a billing_account path into its component segments.""" - m = re.match(r"^billingAccounts/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_folder_path(folder: str, ) -> str: - """Return a fully-qualified folder string.""" - return "folders/{folder}".format(folder=folder, ) - - @staticmethod - def parse_common_folder_path(path: str) -> Dict[str,str]: - """Parse a folder path into its component segments.""" - m = re.match(r"^folders/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_organization_path(organization: str, ) -> str: - """Return a fully-qualified organization string.""" - return "organizations/{organization}".format(organization=organization, ) - - @staticmethod - def parse_common_organization_path(path: str) -> Dict[str,str]: - """Parse a organization path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_project_path(project: str, ) -> str: - """Return a fully-qualified project string.""" - return "projects/{project}".format(project=project, ) - - @staticmethod - def parse_common_project_path(path: str) -> Dict[str,str]: - """Parse a project path into its component segments.""" - m = re.match(r"^projects/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_location_path(project: str, location: str, ) -> str: - """Return a fully-qualified location string.""" - return "projects/{project}/locations/{location}".format(project=project, location=location, ) - - @staticmethod - def parse_common_location_path(path: str) -> Dict[str,str]: - """Parse a location path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) - return m.groupdict() if m else {} - - def __init__(self, *, - credentials: Optional[credentials.Credentials] = None, - transport: Union[str, PublisherTransport, None] = None, - client_options: Optional[client_options_lib.ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiate the publisher client. - - Args: - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - transport (Union[str, PublisherTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. It won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - """ - if isinstance(client_options, dict): - client_options = client_options_lib.from_dict(client_options) - if client_options is None: - client_options = client_options_lib.ClientOptions() - - # Create SSL credentials for mutual TLS if needed. - use_client_cert = bool(util.strtobool(os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false"))) - - client_cert_source_func = None - is_mtls = False - if use_client_cert: - if client_options.client_cert_source: - is_mtls = True - 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 - - # Figure out which api endpoint to use. - if client_options.api_endpoint is not None: - api_endpoint = client_options.api_endpoint - else: - use_mtls_env = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_mtls_env == "never": - api_endpoint = self.DEFAULT_ENDPOINT - 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 - else: - raise MutualTLSChannelError( - "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted values: never, auto, always" - ) - - # Save or instantiate the transport. - # Ordinarily, we provide the transport, but allowing a custom transport - # instance provides an extensibility point for unusual situations. - if isinstance(transport, PublisherTransport): - # transport is a PublisherTransport instance. - if credentials or client_options.credentials_file: - raise ValueError('When providing a transport instance, ' - 'provide its credentials directly.') - if client_options.scopes: - raise ValueError( - "When providing a transport instance, " - "provide its scopes directly." - ) - self._transport = transport - else: - Transport = type(self).get_transport_class(transport) - self._transport = Transport( - credentials=credentials, - credentials_file=client_options.credentials_file, - host=api_endpoint, - scopes=client_options.scopes, - client_cert_source_for_mtls=client_cert_source_func, - quota_project_id=client_options.quota_project_id, - client_info=client_info, - ) - - def create_topic(self, - request: pubsub.Topic = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pubsub.Topic: - r"""Creates the given topic with the given name. See the [resource - name rules] - (https://cloud.google.com/pubsub/docs/admin#resource_names). - - Args: - request (google.pubsub_v1.types.Topic): - The request object. A topic resource. - name (str): - Required. The name of the topic. It must have the format - ``"projects/{project}/topics/{topic}"``. ``{topic}`` - must start with a letter, and contain only letters - (``[A-Za-z]``), numbers (``[0-9]``), dashes (``-``), - underscores (``_``), periods (``.``), tildes (``~``), - plus (``+``) or percent signs (``%``). It must be - between 3 and 255 characters in length, and it must not - start with ``"goog"``. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.pubsub_v1.types.Topic: - A topic resource. - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a pubsub.Topic. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, pubsub.Topic): - request = pubsub.Topic(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_topic] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('name', request.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def update_topic(self, - request: pubsub.UpdateTopicRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pubsub.Topic: - r"""Updates an existing topic. Note that certain - properties of a topic are not modifiable. - - 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 (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.pubsub_v1.types.Topic: - A topic resource. - """ - # Create or coerce a protobuf request object. - - # Minor optimization to avoid making a copy if the user passes - # in a pubsub.UpdateTopicRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, pubsub.UpdateTopicRequest): - request = pubsub.UpdateTopicRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.update_topic] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('topic.name', request.topic.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def publish(self, - request: pubsub.PublishRequest = None, - *, - topic: str = None, - messages: Sequence[pubsub.PubsubMessage] = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pubsub.PublishResponse: - r"""Adds one or more messages to the topic. Returns ``NOT_FOUND`` if - the topic does not exist. - - Args: - request (google.pubsub_v1.types.PublishRequest): - The request object. Request for the Publish method. - topic (str): - Required. The messages in the request will be published - on this topic. Format is - ``projects/{project}/topics/{topic}``. - - This corresponds to the ``topic`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - messages (Sequence[google.pubsub_v1.types.PubsubMessage]): - Required. The messages to publish. - This corresponds to the ``messages`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.pubsub_v1.types.PublishResponse: - Response for the Publish method. - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([topic, messages]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a pubsub.PublishRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, pubsub.PublishRequest): - request = pubsub.PublishRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - - if topic is not None: - request.topic = topic - if messages is not None: - request.messages = messages - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.publish] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('topic', request.topic), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def get_topic(self, - request: pubsub.GetTopicRequest = None, - *, - topic: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pubsub.Topic: - r"""Gets the configuration of a topic. - - Args: - request (google.pubsub_v1.types.GetTopicRequest): - The request object. Request for the GetTopic method. - topic (str): - Required. The name of the topic to get. Format is - ``projects/{project}/topics/{topic}``. - - This corresponds to the ``topic`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.pubsub_v1.types.Topic: - A topic resource. - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([topic]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a pubsub.GetTopicRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, pubsub.GetTopicRequest): - request = pubsub.GetTopicRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - - if topic is not None: - request.topic = topic - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.get_topic] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('topic', request.topic), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def list_topics(self, - request: pubsub.ListTopicsRequest = None, - *, - project: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListTopicsPager: - r"""Lists matching topics. - - Args: - request (google.pubsub_v1.types.ListTopicsRequest): - The request object. Request for the `ListTopics` method. - project (str): - Required. The name of the project in which to list - topics. Format is ``projects/{project-id}``. - - This corresponds to the ``project`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.pubsub_v1.services.publisher.pagers.ListTopicsPager: - Response for the ListTopics method. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([project]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a pubsub.ListTopicsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, pubsub.ListTopicsRequest): - request = pubsub.ListTopicsRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - - if project is not None: - request.project = project - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.list_topics] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('project', request.project), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__iter__` convenience method. - response = pagers.ListTopicsPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - def list_topic_subscriptions(self, - request: pubsub.ListTopicSubscriptionsRequest = None, - *, - topic: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListTopicSubscriptionsPager: - r"""Lists the names of the attached subscriptions on this - topic. - - Args: - request (google.pubsub_v1.types.ListTopicSubscriptionsRequest): - The request object. Request for the - `ListTopicSubscriptions` method. - topic (str): - Required. The name of the topic that subscriptions are - attached to. Format is - ``projects/{project}/topics/{topic}``. - - This corresponds to the ``topic`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.pubsub_v1.services.publisher.pagers.ListTopicSubscriptionsPager: - Response for the ListTopicSubscriptions method. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([topic]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a pubsub.ListTopicSubscriptionsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, pubsub.ListTopicSubscriptionsRequest): - request = pubsub.ListTopicSubscriptionsRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - - if topic is not None: - request.topic = topic - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.list_topic_subscriptions] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('topic', request.topic), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__iter__` convenience method. - response = pagers.ListTopicSubscriptionsPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - def list_topic_snapshots(self, - request: pubsub.ListTopicSnapshotsRequest = None, - *, - topic: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListTopicSnapshotsPager: - r"""Lists the names of the snapshots on this topic. Snapshots are - used in - `Seek `__ - operations, which allow you to manage message acknowledgments in - bulk. That is, you can set the acknowledgment state of messages - in an existing subscription to the state captured by a snapshot. - - Args: - request (google.pubsub_v1.types.ListTopicSnapshotsRequest): - The request object. Request for the `ListTopicSnapshots` - method. - topic (str): - Required. The name of the topic that snapshots are - attached to. Format is - ``projects/{project}/topics/{topic}``. - - This corresponds to the ``topic`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.pubsub_v1.services.publisher.pagers.ListTopicSnapshotsPager: - Response for the ListTopicSnapshots method. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([topic]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a pubsub.ListTopicSnapshotsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, pubsub.ListTopicSnapshotsRequest): - request = pubsub.ListTopicSnapshotsRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - - if topic is not None: - request.topic = topic - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.list_topic_snapshots] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('topic', request.topic), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__iter__` convenience method. - response = pagers.ListTopicSnapshotsPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - def delete_topic(self, - request: pubsub.DeleteTopicRequest = None, - *, - topic: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes the topic with the given name. Returns ``NOT_FOUND`` if - the topic does not exist. After a topic is deleted, a new topic - may be created with the same name; this is an entirely new topic - with none of the old configuration or subscriptions. Existing - subscriptions to this topic are not deleted, but their ``topic`` - field is set to ``_deleted-topic_``. - - Args: - request (google.pubsub_v1.types.DeleteTopicRequest): - The request object. Request for the `DeleteTopic` - method. - topic (str): - Required. Name of the topic to delete. Format is - ``projects/{project}/topics/{topic}``. - - This corresponds to the ``topic`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([topic]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a pubsub.DeleteTopicRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, pubsub.DeleteTopicRequest): - request = pubsub.DeleteTopicRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - - if topic is not None: - request.topic = topic - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.delete_topic] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('topic', request.topic), - )), - ) - - # Send the request. - rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - def detach_subscription(self, - request: pubsub.DetachSubscriptionRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pubsub.DetachSubscriptionResponse: - r"""Detaches a subscription from this topic. All messages retained - in the subscription are dropped. Subsequent ``Pull`` and - ``StreamingPull`` requests will return FAILED_PRECONDITION. If - the subscription is a push subscription, pushes to the endpoint - will stop. - - Args: - 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 (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.pubsub_v1.types.DetachSubscriptionResponse: - Response for the DetachSubscription - method. Reserved for future use. - - """ - # Create or coerce a protobuf request object. - - # Minor optimization to avoid making a copy if the user passes - # in a pubsub.DetachSubscriptionRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, pubsub.DetachSubscriptionRequest): - request = pubsub.DetachSubscriptionRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.detach_subscription] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('subscription', request.subscription), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def set_iam_policy( - self, - request: iam_policy.SetIamPolicyRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> policy.Policy: - r"""Sets the IAM access control policy on the specified - function. Replaces any existing policy. - Args: - request (:class:`~.iam_policy.SetIamPolicyRequest`): - The request object. Request message for `SetIamPolicy` - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.policy.Policy: - Defines an Identity and Access Management (IAM) policy. - It is used to specify access control policies for Cloud - Platform resources. - A ``Policy`` is a collection of ``bindings``. A - ``binding`` binds one or more ``members`` to a single - ``role``. Members can be user accounts, service - accounts, Google groups, and domains (such as G Suite). - A ``role`` is a named list of permissions (defined by - IAM or configured by users). A ``binding`` can - optionally specify a ``condition``, which is a logic - expression that further constrains the role binding - based on attributes about the request and/or target - resource. - **JSON Example** - :: - { - "bindings": [ - { - "role": "roles/resourcemanager.organizationAdmin", - "members": [ - "user:mike@example.com", - "group:admins@example.com", - "domain:google.com", - "serviceAccount:my-project-id@appspot.gserviceaccount.com" - ] - }, - { - "role": "roles/resourcemanager.organizationViewer", - "members": ["user:eve@example.com"], - "condition": { - "title": "expirable access", - "description": "Does not grant access after Sep 2020", - "expression": "request.time < - timestamp('2020-10-01T00:00:00.000Z')", - } - } - ] - } - **YAML Example** - :: - bindings: - - members: - - user:mike@example.com - - group:admins@example.com - - domain:google.com - - serviceAccount:my-project-id@appspot.gserviceaccount.com - role: roles/resourcemanager.organizationAdmin - - members: - - user:eve@example.com - role: roles/resourcemanager.organizationViewer - condition: - title: expirable access - description: Does not grant access after Sep 2020 - expression: request.time < timestamp('2020-10-01T00:00:00.000Z') - For a description of IAM and its features, see the `IAM - developer's - guide `__. - """ - # Create or coerce a protobuf request object. - - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = iam_policy.SetIamPolicyRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.set_iam_policy, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("resource", request.resource),)), - ) - - # Send the request. - response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - def get_iam_policy( - self, - request: iam_policy.GetIamPolicyRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> policy.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`): - The request object. Request message for `GetIamPolicy` - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.policy.Policy: - Defines an Identity and Access Management (IAM) policy. - It is used to specify access control policies for Cloud - Platform resources. - A ``Policy`` is a collection of ``bindings``. A - ``binding`` binds one or more ``members`` to a single - ``role``. Members can be user accounts, service - accounts, Google groups, and domains (such as G Suite). - A ``role`` is a named list of permissions (defined by - IAM or configured by users). A ``binding`` can - optionally specify a ``condition``, which is a logic - expression that further constrains the role binding - based on attributes about the request and/or target - resource. - **JSON Example** - :: - { - "bindings": [ - { - "role": "roles/resourcemanager.organizationAdmin", - "members": [ - "user:mike@example.com", - "group:admins@example.com", - "domain:google.com", - "serviceAccount:my-project-id@appspot.gserviceaccount.com" - ] - }, - { - "role": "roles/resourcemanager.organizationViewer", - "members": ["user:eve@example.com"], - "condition": { - "title": "expirable access", - "description": "Does not grant access after Sep 2020", - "expression": "request.time < - timestamp('2020-10-01T00:00:00.000Z')", - } - } - ] - } - **YAML Example** - :: - bindings: - - members: - - user:mike@example.com - - group:admins@example.com - - domain:google.com - - serviceAccount:my-project-id@appspot.gserviceaccount.com - role: roles/resourcemanager.organizationAdmin - - members: - - user:eve@example.com - role: roles/resourcemanager.organizationViewer - condition: - title: expirable access - description: Does not grant access after Sep 2020 - expression: request.time < timestamp('2020-10-01T00:00:00.000Z') - For a description of IAM and its features, see the `IAM - developer's - guide `__. - """ - # Create or coerce a protobuf request object. - - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = iam_policy.GetIamPolicyRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.get_iam_policy, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("resource", request.resource),)), - ) - - # Send the request. - response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - def test_iam_permissions( - self, - request: iam_policy.TestIamPermissionsRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> iam_policy.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`): - The request object. Request message for - `TestIamPermissions` method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.iam_policy.TestIamPermissionsResponse: - Response message for ``TestIamPermissions`` method. - """ - # Create or coerce a protobuf request object. - - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = iam_policy.TestIamPermissionsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.test_iam_permissions, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("resource", request.resource),)), - ) - - # Send the request. - response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - 'google-pubsub', - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - 'PublisherClient', -) diff --git a/owl-bot-staging/v1/google/pubsub_v1/services/publisher/pagers.py b/owl-bot-staging/v1/google/pubsub_v1/services/publisher/pagers.py deleted file mode 100644 index 1b237533a..000000000 --- a/owl-bot-staging/v1/google/pubsub_v1/services/publisher/pagers.py +++ /dev/null @@ -1,386 +0,0 @@ -# -*- coding: utf-8 -*- - -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -from typing import Any, AsyncIterable, Awaitable, Callable, Iterable, Sequence, Tuple, Optional - -from google.pubsub_v1.types import pubsub - - -class ListTopicsPager: - """A pager for iterating through ``list_topics`` requests. - - This class thinly wraps an initial - :class:`google.pubsub_v1.types.ListTopicsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``topics`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListTopics`` requests and continue to iterate - through the ``topics`` field on the - corresponding responses. - - All the usual :class:`google.pubsub_v1.types.ListTopicsResponse` - attributes are available on the pager. If multiple requests are made, only - the most recent response is retained, and thus used for attribute lookup. - """ - def __init__(self, - method: Callable[..., pubsub.ListTopicsResponse], - request: pubsub.ListTopicsRequest, - response: pubsub.ListTopicsResponse, - *, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiate the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.pubsub_v1.types.ListTopicsRequest): - The initial request object. - response (google.pubsub_v1.types.ListTopicsResponse): - The initial response object. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = pubsub.ListTopicsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterable[pubsub.ListTopicsResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = self._method(self._request, metadata=self._metadata) - yield self._response - - def __iter__(self) -> Iterable[pubsub.Topic]: - for page in self.pages: - yield from page.topics - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListTopicsAsyncPager: - """A pager for iterating through ``list_topics`` requests. - - This class thinly wraps an initial - :class:`google.pubsub_v1.types.ListTopicsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``topics`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListTopics`` requests and continue to iterate - through the ``topics`` field on the - corresponding responses. - - All the usual :class:`google.pubsub_v1.types.ListTopicsResponse` - attributes are available on the pager. If multiple requests are made, only - the most recent response is retained, and thus used for attribute lookup. - """ - def __init__(self, - method: Callable[..., Awaitable[pubsub.ListTopicsResponse]], - request: pubsub.ListTopicsRequest, - response: pubsub.ListTopicsResponse, - *, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiate the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.pubsub_v1.types.ListTopicsRequest): - The initial request object. - response (google.pubsub_v1.types.ListTopicsResponse): - The initial response object. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = pubsub.ListTopicsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterable[pubsub.ListTopicsResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = await self._method(self._request, metadata=self._metadata) - yield self._response - - def __aiter__(self) -> AsyncIterable[pubsub.Topic]: - async def async_generator(): - async for page in self.pages: - for response in page.topics: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListTopicSubscriptionsPager: - """A pager for iterating through ``list_topic_subscriptions`` requests. - - This class thinly wraps an initial - :class:`google.pubsub_v1.types.ListTopicSubscriptionsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``subscriptions`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListTopicSubscriptions`` requests and continue to iterate - through the ``subscriptions`` field on the - corresponding responses. - - All the usual :class:`google.pubsub_v1.types.ListTopicSubscriptionsResponse` - attributes are available on the pager. If multiple requests are made, only - the most recent response is retained, and thus used for attribute lookup. - """ - def __init__(self, - method: Callable[..., pubsub.ListTopicSubscriptionsResponse], - request: pubsub.ListTopicSubscriptionsRequest, - response: pubsub.ListTopicSubscriptionsResponse, - *, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiate the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.pubsub_v1.types.ListTopicSubscriptionsRequest): - The initial request object. - response (google.pubsub_v1.types.ListTopicSubscriptionsResponse): - The initial response object. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = pubsub.ListTopicSubscriptionsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterable[pubsub.ListTopicSubscriptionsResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = self._method(self._request, metadata=self._metadata) - yield self._response - - def __iter__(self) -> Iterable[str]: - for page in self.pages: - yield from page.subscriptions - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListTopicSubscriptionsAsyncPager: - """A pager for iterating through ``list_topic_subscriptions`` requests. - - This class thinly wraps an initial - :class:`google.pubsub_v1.types.ListTopicSubscriptionsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``subscriptions`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListTopicSubscriptions`` requests and continue to iterate - through the ``subscriptions`` field on the - corresponding responses. - - All the usual :class:`google.pubsub_v1.types.ListTopicSubscriptionsResponse` - attributes are available on the pager. If multiple requests are made, only - the most recent response is retained, and thus used for attribute lookup. - """ - def __init__(self, - method: Callable[..., Awaitable[pubsub.ListTopicSubscriptionsResponse]], - request: pubsub.ListTopicSubscriptionsRequest, - response: pubsub.ListTopicSubscriptionsResponse, - *, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiate the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.pubsub_v1.types.ListTopicSubscriptionsRequest): - The initial request object. - response (google.pubsub_v1.types.ListTopicSubscriptionsResponse): - The initial response object. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = pubsub.ListTopicSubscriptionsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterable[pubsub.ListTopicSubscriptionsResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = await self._method(self._request, metadata=self._metadata) - yield self._response - - def __aiter__(self) -> AsyncIterable[str]: - async def async_generator(): - async for page in self.pages: - for response in page.subscriptions: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListTopicSnapshotsPager: - """A pager for iterating through ``list_topic_snapshots`` requests. - - This class thinly wraps an initial - :class:`google.pubsub_v1.types.ListTopicSnapshotsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``snapshots`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListTopicSnapshots`` requests and continue to iterate - through the ``snapshots`` field on the - corresponding responses. - - All the usual :class:`google.pubsub_v1.types.ListTopicSnapshotsResponse` - attributes are available on the pager. If multiple requests are made, only - the most recent response is retained, and thus used for attribute lookup. - """ - def __init__(self, - method: Callable[..., pubsub.ListTopicSnapshotsResponse], - request: pubsub.ListTopicSnapshotsRequest, - response: pubsub.ListTopicSnapshotsResponse, - *, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiate the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.pubsub_v1.types.ListTopicSnapshotsRequest): - The initial request object. - response (google.pubsub_v1.types.ListTopicSnapshotsResponse): - The initial response object. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = pubsub.ListTopicSnapshotsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterable[pubsub.ListTopicSnapshotsResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = self._method(self._request, metadata=self._metadata) - yield self._response - - def __iter__(self) -> Iterable[str]: - for page in self.pages: - yield from page.snapshots - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListTopicSnapshotsAsyncPager: - """A pager for iterating through ``list_topic_snapshots`` requests. - - This class thinly wraps an initial - :class:`google.pubsub_v1.types.ListTopicSnapshotsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``snapshots`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListTopicSnapshots`` requests and continue to iterate - through the ``snapshots`` field on the - corresponding responses. - - All the usual :class:`google.pubsub_v1.types.ListTopicSnapshotsResponse` - attributes are available on the pager. If multiple requests are made, only - the most recent response is retained, and thus used for attribute lookup. - """ - def __init__(self, - method: Callable[..., Awaitable[pubsub.ListTopicSnapshotsResponse]], - request: pubsub.ListTopicSnapshotsRequest, - response: pubsub.ListTopicSnapshotsResponse, - *, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiate the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.pubsub_v1.types.ListTopicSnapshotsRequest): - The initial request object. - response (google.pubsub_v1.types.ListTopicSnapshotsResponse): - The initial response object. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = pubsub.ListTopicSnapshotsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterable[pubsub.ListTopicSnapshotsResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = await self._method(self._request, metadata=self._metadata) - yield self._response - - def __aiter__(self) -> AsyncIterable[str]: - async def async_generator(): - async for page in self.pages: - for response in page.snapshots: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) diff --git a/owl-bot-staging/v1/google/pubsub_v1/services/publisher/transports/__init__.py b/owl-bot-staging/v1/google/pubsub_v1/services/publisher/transports/__init__.py deleted file mode 100644 index 0d8e158e6..000000000 --- a/owl-bot-staging/v1/google/pubsub_v1/services/publisher/transports/__init__.py +++ /dev/null @@ -1,35 +0,0 @@ -# -*- coding: utf-8 -*- - -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -from collections import OrderedDict -from typing import Dict, Type - -from .base import PublisherTransport -from .grpc import PublisherGrpcTransport -from .grpc_asyncio import PublisherGrpcAsyncIOTransport - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[PublisherTransport]] -_transport_registry['grpc'] = PublisherGrpcTransport -_transport_registry['grpc_asyncio'] = PublisherGrpcAsyncIOTransport - -__all__ = ( - 'PublisherTransport', - 'PublisherGrpcTransport', - 'PublisherGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v1/google/pubsub_v1/services/publisher/transports/base.py b/owl-bot-staging/v1/google/pubsub_v1/services/publisher/transports/base.py deleted file mode 100644 index 9f17d8e2e..000000000 --- a/owl-bot-staging/v1/google/pubsub_v1/services/publisher/transports/base.py +++ /dev/null @@ -1,368 +0,0 @@ -# -*- coding: utf-8 -*- - -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -import abc -import typing -import pkg_resources - -from google import auth # 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 -from google.auth import 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.pubsub_v1.types import pubsub - - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - 'google-pubsub', - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - -class PublisherTransport(abc.ABC): - """Abstract transport class for Publisher.""" - - AUTH_SCOPES = ( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/pubsub', - ) - - 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, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - **kwargs, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - 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): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - """ - # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ':' not in host: - host += ':443' - self._host = host - - # 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("'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 - ) - - elif credentials is None: - credentials, _ = auth.default(scopes=self._scopes, quota_project_id=quota_project_id) - - # Save the credentials. - self._credentials = credentials - - def _prep_wrapped_messages(self, client_info): - # Precompute the wrapped methods. - self._wrapped_methods = { - self.create_topic: gapic_v1.method.wrap_method( - self.create_topic, - default_retry=retries.Retry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.update_topic: gapic_v1.method.wrap_method( - self.update_topic, - default_retry=retries.Retry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.publish: gapic_v1.method.wrap_method( - self.publish, - default_retry=retries.Retry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - exceptions.Aborted, - exceptions.Cancelled, - exceptions.DeadlineExceeded, - exceptions.InternalServerError, - exceptions.ResourceExhausted, - exceptions.ServiceUnavailable, - exceptions.Unknown, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.get_topic: gapic_v1.method.wrap_method( - self.get_topic, - default_retry=retries.Retry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - exceptions.Aborted, - exceptions.ServiceUnavailable, - exceptions.Unknown, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.list_topics: gapic_v1.method.wrap_method( - self.list_topics, - default_retry=retries.Retry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - exceptions.Aborted, - exceptions.ServiceUnavailable, - exceptions.Unknown, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.list_topic_subscriptions: gapic_v1.method.wrap_method( - self.list_topic_subscriptions, - default_retry=retries.Retry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - exceptions.Aborted, - exceptions.ServiceUnavailable, - exceptions.Unknown, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.list_topic_snapshots: gapic_v1.method.wrap_method( - self.list_topic_snapshots, - default_retry=retries.Retry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - exceptions.Aborted, - exceptions.ServiceUnavailable, - exceptions.Unknown, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.delete_topic: gapic_v1.method.wrap_method( - self.delete_topic, - default_retry=retries.Retry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.detach_subscription: gapic_v1.method.wrap_method( - self.detach_subscription, - default_retry=retries.Retry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - - } - - @property - def create_topic(self) -> typing.Callable[ - [pubsub.Topic], - typing.Union[ - pubsub.Topic, - typing.Awaitable[pubsub.Topic] - ]]: - raise NotImplementedError() - - @property - def update_topic(self) -> typing.Callable[ - [pubsub.UpdateTopicRequest], - typing.Union[ - pubsub.Topic, - typing.Awaitable[pubsub.Topic] - ]]: - raise NotImplementedError() - - @property - def publish(self) -> typing.Callable[ - [pubsub.PublishRequest], - typing.Union[ - pubsub.PublishResponse, - typing.Awaitable[pubsub.PublishResponse] - ]]: - raise NotImplementedError() - - @property - def get_topic(self) -> typing.Callable[ - [pubsub.GetTopicRequest], - typing.Union[ - pubsub.Topic, - typing.Awaitable[pubsub.Topic] - ]]: - raise NotImplementedError() - - @property - def list_topics(self) -> typing.Callable[ - [pubsub.ListTopicsRequest], - typing.Union[ - pubsub.ListTopicsResponse, - typing.Awaitable[pubsub.ListTopicsResponse] - ]]: - raise NotImplementedError() - - @property - def list_topic_subscriptions(self) -> typing.Callable[ - [pubsub.ListTopicSubscriptionsRequest], - typing.Union[ - pubsub.ListTopicSubscriptionsResponse, - typing.Awaitable[pubsub.ListTopicSubscriptionsResponse] - ]]: - raise NotImplementedError() - - @property - def list_topic_snapshots(self) -> typing.Callable[ - [pubsub.ListTopicSnapshotsRequest], - typing.Union[ - pubsub.ListTopicSnapshotsResponse, - typing.Awaitable[pubsub.ListTopicSnapshotsResponse] - ]]: - raise NotImplementedError() - - @property - def delete_topic(self) -> typing.Callable[ - [pubsub.DeleteTopicRequest], - typing.Union[ - empty.Empty, - typing.Awaitable[empty.Empty] - ]]: - raise NotImplementedError() - - @property - def detach_subscription(self) -> typing.Callable[ - [pubsub.DetachSubscriptionRequest], - typing.Union[ - pubsub.DetachSubscriptionResponse, - typing.Awaitable[pubsub.DetachSubscriptionResponse] - ]]: - raise NotImplementedError() - - @property - def set_iam_policy( - self, - ) -> typing.Callable[ - [iam_policy.SetIamPolicyRequest], - typing.Union[policy.Policy, typing.Awaitable[policy.Policy]], - ]: - raise NotImplementedError() - - @property - def get_iam_policy( - self, - ) -> typing.Callable[ - [iam_policy.GetIamPolicyRequest], - typing.Union[policy.Policy, typing.Awaitable[policy.Policy]], - ]: - raise NotImplementedError() - - @property - def test_iam_permissions( - self, - ) -> typing.Callable[ - [iam_policy.TestIamPermissionsRequest], - typing.Union[ - iam_policy.TestIamPermissionsResponse, - typing.Awaitable[iam_policy.TestIamPermissionsResponse], - ], - ]: - raise NotImplementedError() - - -__all__ = ( - 'PublisherTransport', -) diff --git a/owl-bot-staging/v1/google/pubsub_v1/services/publisher/transports/grpc.py b/owl-bot-staging/v1/google/pubsub_v1/services/publisher/transports/grpc.py deleted file mode 100644 index 699339228..000000000 --- a/owl-bot-staging/v1/google/pubsub_v1/services/publisher/transports/grpc.py +++ /dev/null @@ -1,558 +0,0 @@ -# -*- coding: utf-8 -*- - -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple - -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 -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.pubsub_v1.types import pubsub - -from .base import PublisherTransport, DEFAULT_CLIENT_INFO - - -class PublisherGrpcTransport(PublisherTransport): - """gRPC backend transport for Publisher. - - The service that an application uses to manipulate topics, - and to send messages to a topic. - - This class defines the same methods as the primary client, so the - primary client can load the underlying transport implementation - and call it. - - It sends protocol buffers over the wire using gRPC (which is built on - top of HTTP/2); the ``grpcio`` package must be installed. - """ - _stubs: Dict[str, Callable] - - def __init__(self, *, - host: str = 'pubsub.googleapis.com', - credentials: credentials.Credentials = None, - credentials_file: str = None, - scopes: Sequence[str] = None, - channel: grpc.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - channel (Optional[grpc.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or applicatin default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - credentials=self._credentials, - credentials_file=credentials_file, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @classmethod - def create_channel(cls, - host: str = 'pubsub.googleapis.com', - credentials: credentials.Credentials = None, - credentials_file: str = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> grpc.Channel: - """Create and return a gRPC channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - grpc.Channel: A gRPC channel object. - - Raises: - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - 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, - **kwargs - ) - - @property - def grpc_channel(self) -> grpc.Channel: - """Return the channel designed to connect to this service. - """ - return self._grpc_channel - - @property - def create_topic(self) -> Callable[ - [pubsub.Topic], - pubsub.Topic]: - r"""Return a callable for the create topic method over gRPC. - - Creates the given topic with the given name. See the [resource - name rules] - (https://cloud.google.com/pubsub/docs/admin#resource_names). - - Returns: - Callable[[~.Topic], - ~.Topic]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'create_topic' not in self._stubs: - self._stubs['create_topic'] = self.grpc_channel.unary_unary( - '/google.pubsub.v1.Publisher/CreateTopic', - request_serializer=pubsub.Topic.serialize, - response_deserializer=pubsub.Topic.deserialize, - ) - return self._stubs['create_topic'] - - @property - def update_topic(self) -> Callable[ - [pubsub.UpdateTopicRequest], - pubsub.Topic]: - r"""Return a callable for the update topic method over gRPC. - - Updates an existing topic. Note that certain - properties of a topic are not modifiable. - - Returns: - Callable[[~.UpdateTopicRequest], - ~.Topic]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'update_topic' not in self._stubs: - self._stubs['update_topic'] = self.grpc_channel.unary_unary( - '/google.pubsub.v1.Publisher/UpdateTopic', - request_serializer=pubsub.UpdateTopicRequest.serialize, - response_deserializer=pubsub.Topic.deserialize, - ) - return self._stubs['update_topic'] - - @property - def publish(self) -> Callable[ - [pubsub.PublishRequest], - pubsub.PublishResponse]: - r"""Return a callable for the publish method over gRPC. - - Adds one or more messages to the topic. Returns ``NOT_FOUND`` if - the topic does not exist. - - Returns: - Callable[[~.PublishRequest], - ~.PublishResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'publish' not in self._stubs: - self._stubs['publish'] = self.grpc_channel.unary_unary( - '/google.pubsub.v1.Publisher/Publish', - request_serializer=pubsub.PublishRequest.serialize, - response_deserializer=pubsub.PublishResponse.deserialize, - ) - return self._stubs['publish'] - - @property - def get_topic(self) -> Callable[ - [pubsub.GetTopicRequest], - pubsub.Topic]: - r"""Return a callable for the get topic method over gRPC. - - Gets the configuration of a topic. - - Returns: - Callable[[~.GetTopicRequest], - ~.Topic]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'get_topic' not in self._stubs: - self._stubs['get_topic'] = self.grpc_channel.unary_unary( - '/google.pubsub.v1.Publisher/GetTopic', - request_serializer=pubsub.GetTopicRequest.serialize, - response_deserializer=pubsub.Topic.deserialize, - ) - return self._stubs['get_topic'] - - @property - def list_topics(self) -> Callable[ - [pubsub.ListTopicsRequest], - pubsub.ListTopicsResponse]: - r"""Return a callable for the list topics method over gRPC. - - Lists matching topics. - - Returns: - Callable[[~.ListTopicsRequest], - ~.ListTopicsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'list_topics' not in self._stubs: - self._stubs['list_topics'] = self.grpc_channel.unary_unary( - '/google.pubsub.v1.Publisher/ListTopics', - request_serializer=pubsub.ListTopicsRequest.serialize, - response_deserializer=pubsub.ListTopicsResponse.deserialize, - ) - return self._stubs['list_topics'] - - @property - def list_topic_subscriptions(self) -> Callable[ - [pubsub.ListTopicSubscriptionsRequest], - pubsub.ListTopicSubscriptionsResponse]: - r"""Return a callable for the list topic subscriptions method over gRPC. - - Lists the names of the attached subscriptions on this - topic. - - Returns: - Callable[[~.ListTopicSubscriptionsRequest], - ~.ListTopicSubscriptionsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'list_topic_subscriptions' not in self._stubs: - self._stubs['list_topic_subscriptions'] = self.grpc_channel.unary_unary( - '/google.pubsub.v1.Publisher/ListTopicSubscriptions', - request_serializer=pubsub.ListTopicSubscriptionsRequest.serialize, - response_deserializer=pubsub.ListTopicSubscriptionsResponse.deserialize, - ) - return self._stubs['list_topic_subscriptions'] - - @property - def list_topic_snapshots(self) -> Callable[ - [pubsub.ListTopicSnapshotsRequest], - pubsub.ListTopicSnapshotsResponse]: - r"""Return a callable for the list topic snapshots method over gRPC. - - Lists the names of the snapshots on this topic. Snapshots are - used in - `Seek `__ - operations, which allow you to manage message acknowledgments in - bulk. That is, you can set the acknowledgment state of messages - in an existing subscription to the state captured by a snapshot. - - Returns: - Callable[[~.ListTopicSnapshotsRequest], - ~.ListTopicSnapshotsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'list_topic_snapshots' not in self._stubs: - self._stubs['list_topic_snapshots'] = self.grpc_channel.unary_unary( - '/google.pubsub.v1.Publisher/ListTopicSnapshots', - request_serializer=pubsub.ListTopicSnapshotsRequest.serialize, - response_deserializer=pubsub.ListTopicSnapshotsResponse.deserialize, - ) - return self._stubs['list_topic_snapshots'] - - @property - def delete_topic(self) -> Callable[ - [pubsub.DeleteTopicRequest], - empty.Empty]: - r"""Return a callable for the delete topic method over gRPC. - - Deletes the topic with the given name. Returns ``NOT_FOUND`` if - the topic does not exist. After a topic is deleted, a new topic - may be created with the same name; this is an entirely new topic - with none of the old configuration or subscriptions. Existing - subscriptions to this topic are not deleted, but their ``topic`` - field is set to ``_deleted-topic_``. - - Returns: - Callable[[~.DeleteTopicRequest], - ~.Empty]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'delete_topic' not in self._stubs: - self._stubs['delete_topic'] = self.grpc_channel.unary_unary( - '/google.pubsub.v1.Publisher/DeleteTopic', - request_serializer=pubsub.DeleteTopicRequest.serialize, - response_deserializer=empty.Empty.FromString, - ) - return self._stubs['delete_topic'] - - @property - def detach_subscription(self) -> Callable[ - [pubsub.DetachSubscriptionRequest], - pubsub.DetachSubscriptionResponse]: - r"""Return a callable for the detach subscription method over gRPC. - - Detaches a subscription from this topic. All messages retained - in the subscription are dropped. Subsequent ``Pull`` and - ``StreamingPull`` requests will return FAILED_PRECONDITION. If - the subscription is a push subscription, pushes to the endpoint - will stop. - - Returns: - Callable[[~.DetachSubscriptionRequest], - ~.DetachSubscriptionResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'detach_subscription' not in self._stubs: - self._stubs['detach_subscription'] = self.grpc_channel.unary_unary( - '/google.pubsub.v1.Publisher/DetachSubscription', - request_serializer=pubsub.DetachSubscriptionRequest.serialize, - response_deserializer=pubsub.DetachSubscriptionResponse.deserialize, - ) - return self._stubs['detach_subscription'] - - @property - def set_iam_policy( - self, - ) -> Callable[[iam_policy.SetIamPolicyRequest], policy.Policy]: - r"""Return a callable for the set iam policy method over gRPC. - Sets the IAM access control policy on the specified - function. Replaces any existing policy. - Returns: - Callable[[~.SetIamPolicyRequest], - ~.Policy]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "set_iam_policy" not in self._stubs: - self._stubs["set_iam_policy"] = self.grpc_channel.unary_unary( - "/google.iam.v1.IAMPolicy/SetIamPolicy", - request_serializer=iam_policy.SetIamPolicyRequest.SerializeToString, - response_deserializer=policy.Policy.FromString, - ) - return self._stubs["set_iam_policy"] - - @property - def get_iam_policy( - self, - ) -> Callable[[iam_policy.GetIamPolicyRequest], policy.Policy]: - r"""Return a callable for the get iam policy method over gRPC. - Gets the IAM access control policy for a function. - Returns an empty policy if the function exists and does - not have a policy set. - Returns: - Callable[[~.GetIamPolicyRequest], - ~.Policy]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "get_iam_policy" not in self._stubs: - self._stubs["get_iam_policy"] = self.grpc_channel.unary_unary( - "/google.iam.v1.IAMPolicy/GetIamPolicy", - request_serializer=iam_policy.GetIamPolicyRequest.SerializeToString, - response_deserializer=policy.Policy.FromString, - ) - return self._stubs["get_iam_policy"] - - @property - def test_iam_permissions( - self, - ) -> Callable[ - [iam_policy.TestIamPermissionsRequest], iam_policy.TestIamPermissionsResponse - ]: - r"""Return a callable for the test iam permissions method over gRPC. - Tests the specified permissions against the IAM access control - policy for a function. If the function does not exist, this will - return an empty set of permissions, not a NOT_FOUND error. - Returns: - Callable[[~.TestIamPermissionsRequest], - ~.TestIamPermissionsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "test_iam_permissions" not in self._stubs: - self._stubs["test_iam_permissions"] = self.grpc_channel.unary_unary( - "/google.iam.v1.IAMPolicy/TestIamPermissions", - request_serializer=iam_policy.TestIamPermissionsRequest.SerializeToString, - response_deserializer=iam_policy.TestIamPermissionsResponse.FromString, - ) - return self._stubs["test_iam_permissions"] - - -__all__ = ( - 'PublisherGrpcTransport', -) diff --git a/owl-bot-staging/v1/google/pubsub_v1/services/publisher/transports/grpc_asyncio.py b/owl-bot-staging/v1/google/pubsub_v1/services/publisher/transports/grpc_asyncio.py deleted file mode 100644 index 80c8a32ce..000000000 --- a/owl-bot-staging/v1/google/pubsub_v1/services/publisher/transports/grpc_asyncio.py +++ /dev/null @@ -1,564 +0,0 @@ -# -*- coding: utf-8 -*- - -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -import warnings -from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple - -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 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.pubsub_v1.types import pubsub - -from .base import PublisherTransport, DEFAULT_CLIENT_INFO -from .grpc import PublisherGrpcTransport - - -class PublisherGrpcAsyncIOTransport(PublisherTransport): - """gRPC AsyncIO backend transport for Publisher. - - The service that an application uses to manipulate topics, - and to send messages to a topic. - - This class defines the same methods as the primary client, so the - primary client can load the underlying transport implementation - and call it. - - It sends protocol buffers over the wire using gRPC (which is built on - top of HTTP/2); the ``grpcio`` package must be installed. - """ - - _grpc_channel: aio.Channel - _stubs: Dict[str, Callable] = {} - - @classmethod - def create_channel(cls, - host: str = 'pubsub.googleapis.com', - credentials: credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> aio.Channel: - """Create and return a gRPC AsyncIO channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - aio.Channel: A gRPC AsyncIO channel object. - """ - 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, - **kwargs - ) - - def __init__(self, *, - host: str = 'pubsub.googleapis.com', - credentials: credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: aio.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, - quota_project_id=None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - channel (Optional[aio.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or applicatin default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - credentials=self._credentials, - credentials_file=credentials_file, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @property - def grpc_channel(self) -> aio.Channel: - """Create the channel designed to connect to this service. - - This property caches on the instance; repeated calls return - the same channel. - """ - # Return the channel from cache. - return self._grpc_channel - - @property - def create_topic(self) -> Callable[ - [pubsub.Topic], - Awaitable[pubsub.Topic]]: - r"""Return a callable for the create topic method over gRPC. - - Creates the given topic with the given name. See the [resource - name rules] - (https://cloud.google.com/pubsub/docs/admin#resource_names). - - Returns: - Callable[[~.Topic], - Awaitable[~.Topic]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'create_topic' not in self._stubs: - self._stubs['create_topic'] = self.grpc_channel.unary_unary( - '/google.pubsub.v1.Publisher/CreateTopic', - request_serializer=pubsub.Topic.serialize, - response_deserializer=pubsub.Topic.deserialize, - ) - return self._stubs['create_topic'] - - @property - def update_topic(self) -> Callable[ - [pubsub.UpdateTopicRequest], - Awaitable[pubsub.Topic]]: - r"""Return a callable for the update topic method over gRPC. - - Updates an existing topic. Note that certain - properties of a topic are not modifiable. - - Returns: - Callable[[~.UpdateTopicRequest], - Awaitable[~.Topic]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'update_topic' not in self._stubs: - self._stubs['update_topic'] = self.grpc_channel.unary_unary( - '/google.pubsub.v1.Publisher/UpdateTopic', - request_serializer=pubsub.UpdateTopicRequest.serialize, - response_deserializer=pubsub.Topic.deserialize, - ) - return self._stubs['update_topic'] - - @property - def publish(self) -> Callable[ - [pubsub.PublishRequest], - Awaitable[pubsub.PublishResponse]]: - r"""Return a callable for the publish method over gRPC. - - Adds one or more messages to the topic. Returns ``NOT_FOUND`` if - the topic does not exist. - - Returns: - Callable[[~.PublishRequest], - Awaitable[~.PublishResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'publish' not in self._stubs: - self._stubs['publish'] = self.grpc_channel.unary_unary( - '/google.pubsub.v1.Publisher/Publish', - request_serializer=pubsub.PublishRequest.serialize, - response_deserializer=pubsub.PublishResponse.deserialize, - ) - return self._stubs['publish'] - - @property - def get_topic(self) -> Callable[ - [pubsub.GetTopicRequest], - Awaitable[pubsub.Topic]]: - r"""Return a callable for the get topic method over gRPC. - - Gets the configuration of a topic. - - Returns: - Callable[[~.GetTopicRequest], - Awaitable[~.Topic]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'get_topic' not in self._stubs: - self._stubs['get_topic'] = self.grpc_channel.unary_unary( - '/google.pubsub.v1.Publisher/GetTopic', - request_serializer=pubsub.GetTopicRequest.serialize, - response_deserializer=pubsub.Topic.deserialize, - ) - return self._stubs['get_topic'] - - @property - def list_topics(self) -> Callable[ - [pubsub.ListTopicsRequest], - Awaitable[pubsub.ListTopicsResponse]]: - r"""Return a callable for the list topics method over gRPC. - - Lists matching topics. - - Returns: - Callable[[~.ListTopicsRequest], - Awaitable[~.ListTopicsResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'list_topics' not in self._stubs: - self._stubs['list_topics'] = self.grpc_channel.unary_unary( - '/google.pubsub.v1.Publisher/ListTopics', - request_serializer=pubsub.ListTopicsRequest.serialize, - response_deserializer=pubsub.ListTopicsResponse.deserialize, - ) - return self._stubs['list_topics'] - - @property - def list_topic_subscriptions(self) -> Callable[ - [pubsub.ListTopicSubscriptionsRequest], - Awaitable[pubsub.ListTopicSubscriptionsResponse]]: - r"""Return a callable for the list topic subscriptions method over gRPC. - - Lists the names of the attached subscriptions on this - topic. - - Returns: - Callable[[~.ListTopicSubscriptionsRequest], - Awaitable[~.ListTopicSubscriptionsResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'list_topic_subscriptions' not in self._stubs: - self._stubs['list_topic_subscriptions'] = self.grpc_channel.unary_unary( - '/google.pubsub.v1.Publisher/ListTopicSubscriptions', - request_serializer=pubsub.ListTopicSubscriptionsRequest.serialize, - response_deserializer=pubsub.ListTopicSubscriptionsResponse.deserialize, - ) - return self._stubs['list_topic_subscriptions'] - - @property - def list_topic_snapshots(self) -> Callable[ - [pubsub.ListTopicSnapshotsRequest], - Awaitable[pubsub.ListTopicSnapshotsResponse]]: - r"""Return a callable for the list topic snapshots method over gRPC. - - Lists the names of the snapshots on this topic. Snapshots are - used in - `Seek `__ - operations, which allow you to manage message acknowledgments in - bulk. That is, you can set the acknowledgment state of messages - in an existing subscription to the state captured by a snapshot. - - Returns: - Callable[[~.ListTopicSnapshotsRequest], - Awaitable[~.ListTopicSnapshotsResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'list_topic_snapshots' not in self._stubs: - self._stubs['list_topic_snapshots'] = self.grpc_channel.unary_unary( - '/google.pubsub.v1.Publisher/ListTopicSnapshots', - request_serializer=pubsub.ListTopicSnapshotsRequest.serialize, - response_deserializer=pubsub.ListTopicSnapshotsResponse.deserialize, - ) - return self._stubs['list_topic_snapshots'] - - @property - def delete_topic(self) -> Callable[ - [pubsub.DeleteTopicRequest], - Awaitable[empty.Empty]]: - r"""Return a callable for the delete topic method over gRPC. - - Deletes the topic with the given name. Returns ``NOT_FOUND`` if - the topic does not exist. After a topic is deleted, a new topic - may be created with the same name; this is an entirely new topic - with none of the old configuration or subscriptions. Existing - subscriptions to this topic are not deleted, but their ``topic`` - field is set to ``_deleted-topic_``. - - Returns: - Callable[[~.DeleteTopicRequest], - Awaitable[~.Empty]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'delete_topic' not in self._stubs: - self._stubs['delete_topic'] = self.grpc_channel.unary_unary( - '/google.pubsub.v1.Publisher/DeleteTopic', - request_serializer=pubsub.DeleteTopicRequest.serialize, - response_deserializer=empty.Empty.FromString, - ) - return self._stubs['delete_topic'] - - @property - def detach_subscription(self) -> Callable[ - [pubsub.DetachSubscriptionRequest], - Awaitable[pubsub.DetachSubscriptionResponse]]: - r"""Return a callable for the detach subscription method over gRPC. - - Detaches a subscription from this topic. All messages retained - in the subscription are dropped. Subsequent ``Pull`` and - ``StreamingPull`` requests will return FAILED_PRECONDITION. If - the subscription is a push subscription, pushes to the endpoint - will stop. - - Returns: - Callable[[~.DetachSubscriptionRequest], - Awaitable[~.DetachSubscriptionResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'detach_subscription' not in self._stubs: - self._stubs['detach_subscription'] = self.grpc_channel.unary_unary( - '/google.pubsub.v1.Publisher/DetachSubscription', - request_serializer=pubsub.DetachSubscriptionRequest.serialize, - response_deserializer=pubsub.DetachSubscriptionResponse.deserialize, - ) - return self._stubs['detach_subscription'] - - @property - def set_iam_policy( - self, - ) -> Callable[[iam_policy.SetIamPolicyRequest], Awaitable[policy.Policy]]: - r"""Return a callable for the set iam policy method over gRPC. - Sets the IAM access control policy on the specified - function. Replaces any existing policy. - Returns: - Callable[[~.SetIamPolicyRequest], - Awaitable[~.Policy]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "set_iam_policy" not in self._stubs: - self._stubs["set_iam_policy"] = self.grpc_channel.unary_unary( - "/google.iam.v1.IAMPolicy/SetIamPolicy", - request_serializer=iam_policy.SetIamPolicyRequest.SerializeToString, - response_deserializer=policy.Policy.FromString, - ) - return self._stubs["set_iam_policy"] - - @property - def get_iam_policy( - self, - ) -> Callable[[iam_policy.GetIamPolicyRequest], Awaitable[policy.Policy]]: - r"""Return a callable for the get iam policy method over gRPC. - Gets the IAM access control policy for a function. - Returns an empty policy if the function exists and does - not have a policy set. - Returns: - Callable[[~.GetIamPolicyRequest], - Awaitable[~.Policy]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "get_iam_policy" not in self._stubs: - self._stubs["get_iam_policy"] = self.grpc_channel.unary_unary( - "/google.iam.v1.IAMPolicy/GetIamPolicy", - request_serializer=iam_policy.GetIamPolicyRequest.SerializeToString, - response_deserializer=policy.Policy.FromString, - ) - return self._stubs["get_iam_policy"] - - @property - def test_iam_permissions( - self, - ) -> Callable[ - [iam_policy.TestIamPermissionsRequest], - Awaitable[iam_policy.TestIamPermissionsResponse], - ]: - r"""Return a callable for the test iam permissions method over gRPC. - Tests the specified permissions against the IAM access control - policy for a function. If the function does not exist, this will - return an empty set of permissions, not a NOT_FOUND error. - Returns: - Callable[[~.TestIamPermissionsRequest], - Awaitable[~.TestIamPermissionsResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "test_iam_permissions" not in self._stubs: - self._stubs["test_iam_permissions"] = self.grpc_channel.unary_unary( - "/google.iam.v1.IAMPolicy/TestIamPermissions", - request_serializer=iam_policy.TestIamPermissionsRequest.SerializeToString, - response_deserializer=iam_policy.TestIamPermissionsResponse.FromString, - ) - return self._stubs["test_iam_permissions"] - - -__all__ = ( - 'PublisherGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v1/google/pubsub_v1/services/schema_service/__init__.py b/owl-bot-staging/v1/google/pubsub_v1/services/schema_service/__init__.py deleted file mode 100644 index e971e94da..000000000 --- a/owl-bot-staging/v1/google/pubsub_v1/services/schema_service/__init__.py +++ /dev/null @@ -1,24 +0,0 @@ -# -*- coding: utf-8 -*- - -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -from .client import SchemaServiceClient -from .async_client import SchemaServiceAsyncClient - -__all__ = ( - 'SchemaServiceClient', - 'SchemaServiceAsyncClient', -) diff --git a/owl-bot-staging/v1/google/pubsub_v1/services/schema_service/async_client.py b/owl-bot-staging/v1/google/pubsub_v1/services/schema_service/async_client.py deleted file mode 100644 index 6787855f8..000000000 --- a/owl-bot-staging/v1/google/pubsub_v1/services/schema_service/async_client.py +++ /dev/null @@ -1,906 +0,0 @@ -# -*- coding: utf-8 -*- - -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -from collections import OrderedDict -import functools -import re -from typing import Dict, Sequence, Tuple, Type, Union -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 gapic_v1 # type: ignore -from google.api_core import retry as retries # type: ignore -from google.auth import 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.pubsub_v1.services.schema_service import pagers -from google.pubsub_v1.types import schema -from google.pubsub_v1.types import schema as gp_schema - -from .transports.base import SchemaServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import SchemaServiceGrpcAsyncIOTransport -from .client import SchemaServiceClient - - -class SchemaServiceAsyncClient: - """Service for doing schema-related operations.""" - - _client: SchemaServiceClient - - DEFAULT_ENDPOINT = SchemaServiceClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = SchemaServiceClient.DEFAULT_MTLS_ENDPOINT - - schema_path = staticmethod(SchemaServiceClient.schema_path) - parse_schema_path = staticmethod(SchemaServiceClient.parse_schema_path) - - common_billing_account_path = staticmethod(SchemaServiceClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(SchemaServiceClient.parse_common_billing_account_path) - - common_folder_path = staticmethod(SchemaServiceClient.common_folder_path) - parse_common_folder_path = staticmethod(SchemaServiceClient.parse_common_folder_path) - - common_organization_path = staticmethod(SchemaServiceClient.common_organization_path) - parse_common_organization_path = staticmethod(SchemaServiceClient.parse_common_organization_path) - - common_project_path = staticmethod(SchemaServiceClient.common_project_path) - parse_common_project_path = staticmethod(SchemaServiceClient.parse_common_project_path) - - common_location_path = staticmethod(SchemaServiceClient.common_location_path) - parse_common_location_path = staticmethod(SchemaServiceClient.parse_common_location_path) - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials info. - - Args: - info (dict): The service account private key info. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - SchemaServiceAsyncClient: The constructed client. - """ - return SchemaServiceClient.from_service_account_info.__func__(SchemaServiceAsyncClient, info, *args, **kwargs) # type: ignore - - @classmethod - def from_service_account_file(cls, filename: str, *args, **kwargs): - """Creates an instance of this client using the provided credentials - file. - - Args: - filename (str): The path to the service account private key json - file. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - SchemaServiceAsyncClient: The constructed client. - """ - return SchemaServiceClient.from_service_account_file.__func__(SchemaServiceAsyncClient, filename, *args, **kwargs) # type: ignore - - from_service_account_json = from_service_account_file - - @property - def transport(self) -> SchemaServiceTransport: - """Return the transport used by the client instance. - - Returns: - SchemaServiceTransport: The transport used by the client instance. - """ - return self._client.transport - - get_transport_class = functools.partial(type(SchemaServiceClient).get_transport_class, type(SchemaServiceClient)) - - def __init__(self, *, - credentials: credentials.Credentials = None, - transport: Union[str, SchemaServiceTransport] = 'grpc_asyncio', - client_options: ClientOptions = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiate the schema service client. - - Args: - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - transport (Union[str, ~.SchemaServiceTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (ClientOptions): Custom options for the client. It - won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - """ - - self._client = SchemaServiceClient( - credentials=credentials, - transport=transport, - client_options=client_options, - client_info=client_info, - - ) - - async def create_schema(self, - request: gp_schema.CreateSchemaRequest = None, - *, - parent: str = None, - schema: gp_schema.Schema = None, - schema_id: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gp_schema.Schema: - r"""Creates a schema. - - Args: - request (:class:`google.pubsub_v1.types.CreateSchemaRequest`): - The request object. Request for the CreateSchema method. - parent (:class:`str`): - Required. The name of the project in which to create the - schema. Format is ``projects/{project-id}``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - schema (:class:`google.pubsub_v1.types.Schema`): - Required. The schema object to create. - - This schema's ``name`` parameter is ignored. The schema - object returned by CreateSchema will have a ``name`` - made using the given ``parent`` and ``schema_id``. - - This corresponds to the ``schema`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - schema_id (:class:`str`): - The ID to use for the schema, which will become the - final component of the schema's resource name. - - See - https://cloud.google.com/pubsub/docs/admin#resource_names - for resource name constraints. - - This corresponds to the ``schema_id`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.pubsub_v1.types.Schema: - A schema resource. - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, schema, schema_id]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - request = gp_schema.CreateSchemaRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - - if parent is not None: - request.parent = parent - if schema is not None: - request.schema = schema - if schema_id is not None: - request.schema_id = schema_id - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.create_schema, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def get_schema(self, - request: schema.GetSchemaRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> schema.Schema: - r"""Gets a schema. - - Args: - request (:class:`google.pubsub_v1.types.GetSchemaRequest`): - The request object. Request for the GetSchema method. - name (:class:`str`): - Required. The name of the schema to get. Format is - ``projects/{project}/schemas/{schema}``. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.pubsub_v1.types.Schema: - A schema resource. - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - request = schema.GetSchemaRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.get_schema, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('name', request.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def list_schemas(self, - request: schema.ListSchemasRequest = None, - *, - parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListSchemasAsyncPager: - r"""Lists schemas in a project. - - Args: - request (:class:`google.pubsub_v1.types.ListSchemasRequest`): - The request object. Request for the `ListSchemas` - method. - parent (:class:`str`): - Required. The name of the project in which to list - schemas. Format is ``projects/{project-id}``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.pubsub_v1.services.schema_service.pagers.ListSchemasAsyncPager: - Response for the ListSchemas method. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - request = schema.ListSchemasRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - - if parent is not None: - request.parent = parent - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.list_schemas, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__aiter__` convenience method. - response = pagers.ListSchemasAsyncPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def delete_schema(self, - request: schema.DeleteSchemaRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes a schema. - - Args: - request (:class:`google.pubsub_v1.types.DeleteSchemaRequest`): - The request object. Request for the `DeleteSchema` - method. - name (:class:`str`): - Required. Name of the schema to delete. Format is - ``projects/{project}/schemas/{schema}``. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - request = schema.DeleteSchemaRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.delete_schema, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('name', request.name), - )), - ) - - # Send the request. - await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - async def validate_schema(self, - request: gp_schema.ValidateSchemaRequest = None, - *, - parent: str = None, - schema: gp_schema.Schema = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gp_schema.ValidateSchemaResponse: - r"""Validates a schema. - - Args: - request (:class:`google.pubsub_v1.types.ValidateSchemaRequest`): - The request object. Request for the `ValidateSchema` - method. - parent (:class:`str`): - Required. The name of the project in which to validate - schemas. Format is ``projects/{project-id}``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - schema (:class:`google.pubsub_v1.types.Schema`): - Required. The schema object to - validate. - - This corresponds to the ``schema`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.pubsub_v1.types.ValidateSchemaResponse: - Response for the ValidateSchema method. - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, schema]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - request = gp_schema.ValidateSchemaRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - - if parent is not None: - request.parent = parent - if schema is not None: - request.schema = schema - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.validate_schema, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def validate_message(self, - request: schema.ValidateMessageRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> schema.ValidateMessageResponse: - r"""Validates a message against a schema. - - Args: - 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. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.pubsub_v1.types.ValidateMessageResponse: - Response for the ValidateMessage method. - """ - # Create or coerce a protobuf request object. - - request = schema.ValidateMessageRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.validate_message, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def set_iam_policy( - self, - request: iam_policy.SetIamPolicyRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> policy.Policy: - r"""Sets the IAM access control policy on the specified - function. Replaces any existing policy. - Args: - request (:class:`~.iam_policy.SetIamPolicyRequest`): - The request object. Request message for `SetIamPolicy` - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.policy.Policy: - Defines an Identity and Access Management (IAM) policy. - It is used to specify access control policies for Cloud - Platform resources. - A ``Policy`` is a collection of ``bindings``. A - ``binding`` binds one or more ``members`` to a single - ``role``. Members can be user accounts, service - accounts, Google groups, and domains (such as G Suite). - A ``role`` is a named list of permissions (defined by - IAM or configured by users). A ``binding`` can - optionally specify a ``condition``, which is a logic - expression that further constrains the role binding - based on attributes about the request and/or target - resource. - **JSON Example** - :: - { - "bindings": [ - { - "role": "roles/resourcemanager.organizationAdmin", - "members": [ - "user:mike@example.com", - "group:admins@example.com", - "domain:google.com", - "serviceAccount:my-project-id@appspot.gserviceaccount.com" - ] - }, - { - "role": "roles/resourcemanager.organizationViewer", - "members": ["user:eve@example.com"], - "condition": { - "title": "expirable access", - "description": "Does not grant access after Sep 2020", - "expression": "request.time < - timestamp('2020-10-01T00:00:00.000Z')", - } - } - ] - } - **YAML Example** - :: - bindings: - - members: - - user:mike@example.com - - group:admins@example.com - - domain:google.com - - serviceAccount:my-project-id@appspot.gserviceaccount.com - role: roles/resourcemanager.organizationAdmin - - members: - - user:eve@example.com - role: roles/resourcemanager.organizationViewer - condition: - title: expirable access - description: Does not grant access after Sep 2020 - expression: request.time < timestamp('2020-10-01T00:00:00.000Z') - For a description of IAM and its features, see the `IAM - developer's - guide `__. - """ - # Create or coerce a protobuf request object. - - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = iam_policy.SetIamPolicyRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.set_iam_policy, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("resource", request.resource),)), - ) - - # Send the request. - response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - async def get_iam_policy( - self, - request: iam_policy.GetIamPolicyRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> policy.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`): - The request object. Request message for `GetIamPolicy` - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.policy.Policy: - Defines an Identity and Access Management (IAM) policy. - It is used to specify access control policies for Cloud - Platform resources. - A ``Policy`` is a collection of ``bindings``. A - ``binding`` binds one or more ``members`` to a single - ``role``. Members can be user accounts, service - accounts, Google groups, and domains (such as G Suite). - A ``role`` is a named list of permissions (defined by - IAM or configured by users). A ``binding`` can - optionally specify a ``condition``, which is a logic - expression that further constrains the role binding - based on attributes about the request and/or target - resource. - **JSON Example** - :: - { - "bindings": [ - { - "role": "roles/resourcemanager.organizationAdmin", - "members": [ - "user:mike@example.com", - "group:admins@example.com", - "domain:google.com", - "serviceAccount:my-project-id@appspot.gserviceaccount.com" - ] - }, - { - "role": "roles/resourcemanager.organizationViewer", - "members": ["user:eve@example.com"], - "condition": { - "title": "expirable access", - "description": "Does not grant access after Sep 2020", - "expression": "request.time < - timestamp('2020-10-01T00:00:00.000Z')", - } - } - ] - } - **YAML Example** - :: - bindings: - - members: - - user:mike@example.com - - group:admins@example.com - - domain:google.com - - serviceAccount:my-project-id@appspot.gserviceaccount.com - role: roles/resourcemanager.organizationAdmin - - members: - - user:eve@example.com - role: roles/resourcemanager.organizationViewer - condition: - title: expirable access - description: Does not grant access after Sep 2020 - expression: request.time < timestamp('2020-10-01T00:00:00.000Z') - For a description of IAM and its features, see the `IAM - developer's - guide `__. - """ - # Create or coerce a protobuf request object. - - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = iam_policy.GetIamPolicyRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.get_iam_policy, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("resource", request.resource),)), - ) - - # Send the request. - response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - async def test_iam_permissions( - self, - request: iam_policy.TestIamPermissionsRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> iam_policy.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`): - The request object. Request message for - `TestIamPermissions` method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.iam_policy.TestIamPermissionsResponse: - Response message for ``TestIamPermissions`` method. - """ - # Create or coerce a protobuf request object. - - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = iam_policy.TestIamPermissionsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.test_iam_permissions, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("resource", request.resource),)), - ) - - # Send the request. - response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - 'google-pubsub', - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - 'SchemaServiceAsyncClient', -) diff --git a/owl-bot-staging/v1/google/pubsub_v1/services/schema_service/client.py b/owl-bot-staging/v1/google/pubsub_v1/services/schema_service/client.py deleted file mode 100644 index 5e32b6c0d..000000000 --- a/owl-bot-staging/v1/google/pubsub_v1/services/schema_service/client.py +++ /dev/null @@ -1,1085 +0,0 @@ -# -*- coding: utf-8 -*- - -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -from collections import OrderedDict -from distutils import util -import os -import re -from typing import Callable, Dict, Optional, Sequence, Tuple, Type, Union -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 gapic_v1 # type: ignore -from google.api_core import retry as retries # type: ignore -from google.auth import 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.pubsub_v1.services.schema_service import pagers -from google.pubsub_v1.types import schema -from google.pubsub_v1.types import schema as gp_schema - -from .transports.base import SchemaServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import SchemaServiceGrpcTransport -from .transports.grpc_asyncio import SchemaServiceGrpcAsyncIOTransport - - -class SchemaServiceClientMeta(type): - """Metaclass for the SchemaService client. - - This provides class-level methods for building and retrieving - support objects (e.g. transport) without polluting the client instance - objects. - """ - _transport_registry = OrderedDict() # type: Dict[str, Type[SchemaServiceTransport]] - _transport_registry['grpc'] = SchemaServiceGrpcTransport - _transport_registry['grpc_asyncio'] = SchemaServiceGrpcAsyncIOTransport - - def get_transport_class(cls, - label: str = None, - ) -> Type[SchemaServiceTransport]: - """Return an appropriate transport class. - - Args: - label: The name of the desired transport. If none is - provided, then the first transport in the registry is used. - - Returns: - The transport class to use. - """ - # If a specific transport is requested, return that one. - if label: - return cls._transport_registry[label] - - # No transport is requested; return the default (that is, the first one - # in the dictionary). - return next(iter(cls._transport_registry.values())) - - -class SchemaServiceClient(metaclass=SchemaServiceClientMeta): - """Service for doing schema-related operations.""" - - @staticmethod - def _get_default_mtls_endpoint(api_endpoint): - """Convert api endpoint to mTLS endpoint. - Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to - "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. - Args: - api_endpoint (Optional[str]): the api endpoint to convert. - Returns: - str: converted mTLS api endpoint. - """ - if not api_endpoint: - return api_endpoint - - mtls_endpoint_re = re.compile( - r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" - ) - - m = mtls_endpoint_re.match(api_endpoint) - name, mtls, sandbox, googledomain = m.groups() - if mtls or not googledomain: - return api_endpoint - - if sandbox: - return api_endpoint.replace( - "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" - ) - - return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") - - DEFAULT_ENDPOINT = 'pubsub.googleapis.com' - DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore - DEFAULT_ENDPOINT - ) - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials info. - - Args: - info (dict): The service account private key info. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - SchemaServiceClient: The constructed client. - """ - credentials = service_account.Credentials.from_service_account_info(info) - kwargs["credentials"] = credentials - return cls(*args, **kwargs) - - @classmethod - def from_service_account_file(cls, filename: str, *args, **kwargs): - """Creates an instance of this client using the provided credentials - file. - - Args: - filename (str): The path to the service account private key json - file. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - SchemaServiceClient: The constructed client. - """ - credentials = service_account.Credentials.from_service_account_file( - filename) - kwargs['credentials'] = credentials - return cls(*args, **kwargs) - - from_service_account_json = from_service_account_file - - @property - def transport(self) -> SchemaServiceTransport: - """Return the transport used by the client instance. - - Returns: - SchemaServiceTransport: The transport used by the client instance. - """ - return self._transport - - @staticmethod - def schema_path(project: str,schema: str,) -> str: - """Return 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.""" - 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.""" - return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - - @staticmethod - def parse_common_billing_account_path(path: str) -> Dict[str,str]: - """Parse a billing_account path into its component segments.""" - m = re.match(r"^billingAccounts/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_folder_path(folder: str, ) -> str: - """Return a fully-qualified folder string.""" - return "folders/{folder}".format(folder=folder, ) - - @staticmethod - def parse_common_folder_path(path: str) -> Dict[str,str]: - """Parse a folder path into its component segments.""" - m = re.match(r"^folders/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_organization_path(organization: str, ) -> str: - """Return a fully-qualified organization string.""" - return "organizations/{organization}".format(organization=organization, ) - - @staticmethod - def parse_common_organization_path(path: str) -> Dict[str,str]: - """Parse a organization path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_project_path(project: str, ) -> str: - """Return a fully-qualified project string.""" - return "projects/{project}".format(project=project, ) - - @staticmethod - def parse_common_project_path(path: str) -> Dict[str,str]: - """Parse a project path into its component segments.""" - m = re.match(r"^projects/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_location_path(project: str, location: str, ) -> str: - """Return a fully-qualified location string.""" - return "projects/{project}/locations/{location}".format(project=project, location=location, ) - - @staticmethod - def parse_common_location_path(path: str) -> Dict[str,str]: - """Parse a location path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) - return m.groupdict() if m else {} - - def __init__(self, *, - credentials: Optional[credentials.Credentials] = None, - transport: Union[str, SchemaServiceTransport, None] = None, - client_options: Optional[client_options_lib.ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiate the schema service client. - - Args: - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - transport (Union[str, SchemaServiceTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. It won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - """ - if isinstance(client_options, dict): - client_options = client_options_lib.from_dict(client_options) - if client_options is None: - client_options = client_options_lib.ClientOptions() - - # Create SSL credentials for mutual TLS if needed. - use_client_cert = bool(util.strtobool(os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false"))) - - client_cert_source_func = None - is_mtls = False - if use_client_cert: - if client_options.client_cert_source: - is_mtls = True - 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 - - # Figure out which api endpoint to use. - if client_options.api_endpoint is not None: - api_endpoint = client_options.api_endpoint - else: - use_mtls_env = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_mtls_env == "never": - api_endpoint = self.DEFAULT_ENDPOINT - 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 - else: - raise MutualTLSChannelError( - "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted values: never, auto, always" - ) - - # Save or instantiate the transport. - # Ordinarily, we provide the transport, but allowing a custom transport - # instance provides an extensibility point for unusual situations. - if isinstance(transport, SchemaServiceTransport): - # transport is a SchemaServiceTransport instance. - if credentials or client_options.credentials_file: - raise ValueError('When providing a transport instance, ' - 'provide its credentials directly.') - if client_options.scopes: - raise ValueError( - "When providing a transport instance, " - "provide its scopes directly." - ) - self._transport = transport - else: - Transport = type(self).get_transport_class(transport) - self._transport = Transport( - credentials=credentials, - credentials_file=client_options.credentials_file, - host=api_endpoint, - scopes=client_options.scopes, - client_cert_source_for_mtls=client_cert_source_func, - quota_project_id=client_options.quota_project_id, - client_info=client_info, - ) - - def create_schema(self, - request: gp_schema.CreateSchemaRequest = None, - *, - parent: str = None, - schema: gp_schema.Schema = None, - schema_id: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gp_schema.Schema: - r"""Creates a schema. - - Args: - request (google.pubsub_v1.types.CreateSchemaRequest): - The request object. Request for the CreateSchema method. - parent (str): - Required. The name of the project in which to create the - schema. Format is ``projects/{project-id}``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - schema (google.pubsub_v1.types.Schema): - Required. The schema object to create. - - This schema's ``name`` parameter is ignored. The schema - object returned by CreateSchema will have a ``name`` - made using the given ``parent`` and ``schema_id``. - - This corresponds to the ``schema`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - schema_id (str): - The ID to use for the schema, which will become the - final component of the schema's resource name. - - See - https://cloud.google.com/pubsub/docs/admin#resource_names - for resource name constraints. - - This corresponds to the ``schema_id`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.pubsub_v1.types.Schema: - A schema resource. - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, schema, schema_id]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a gp_schema.CreateSchemaRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, gp_schema.CreateSchemaRequest): - request = gp_schema.CreateSchemaRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - - if parent is not None: - request.parent = parent - if schema is not None: - request.schema = schema - if schema_id is not None: - request.schema_id = schema_id - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_schema] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def get_schema(self, - request: schema.GetSchemaRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> schema.Schema: - r"""Gets a schema. - - Args: - request (google.pubsub_v1.types.GetSchemaRequest): - The request object. Request for the GetSchema method. - name (str): - Required. The name of the schema to get. Format is - ``projects/{project}/schemas/{schema}``. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.pubsub_v1.types.Schema: - A schema resource. - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a schema.GetSchemaRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, schema.GetSchemaRequest): - request = schema.GetSchemaRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.get_schema] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('name', request.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def list_schemas(self, - request: schema.ListSchemasRequest = None, - *, - parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListSchemasPager: - r"""Lists schemas in a project. - - Args: - request (google.pubsub_v1.types.ListSchemasRequest): - The request object. Request for the `ListSchemas` - method. - parent (str): - Required. The name of the project in which to list - schemas. Format is ``projects/{project-id}``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.pubsub_v1.services.schema_service.pagers.ListSchemasPager: - Response for the ListSchemas method. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a schema.ListSchemasRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, schema.ListSchemasRequest): - request = schema.ListSchemasRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - - if parent is not None: - request.parent = parent - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.list_schemas] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__iter__` convenience method. - response = pagers.ListSchemasPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - def delete_schema(self, - request: schema.DeleteSchemaRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes a schema. - - Args: - request (google.pubsub_v1.types.DeleteSchemaRequest): - The request object. Request for the `DeleteSchema` - method. - name (str): - Required. Name of the schema to delete. Format is - ``projects/{project}/schemas/{schema}``. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a schema.DeleteSchemaRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, schema.DeleteSchemaRequest): - request = schema.DeleteSchemaRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.delete_schema] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('name', request.name), - )), - ) - - # Send the request. - rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - def validate_schema(self, - request: gp_schema.ValidateSchemaRequest = None, - *, - parent: str = None, - schema: gp_schema.Schema = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gp_schema.ValidateSchemaResponse: - r"""Validates a schema. - - Args: - request (google.pubsub_v1.types.ValidateSchemaRequest): - The request object. Request for the `ValidateSchema` - method. - parent (str): - Required. The name of the project in which to validate - schemas. Format is ``projects/{project-id}``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - schema (google.pubsub_v1.types.Schema): - Required. The schema object to - validate. - - This corresponds to the ``schema`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.pubsub_v1.types.ValidateSchemaResponse: - Response for the ValidateSchema method. - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, schema]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a gp_schema.ValidateSchemaRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, gp_schema.ValidateSchemaRequest): - request = gp_schema.ValidateSchemaRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - - if parent is not None: - request.parent = parent - if schema is not None: - request.schema = schema - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.validate_schema] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def validate_message(self, - request: schema.ValidateMessageRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> schema.ValidateMessageResponse: - r"""Validates a message against a schema. - - Args: - 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. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.pubsub_v1.types.ValidateMessageResponse: - Response for the ValidateMessage method. - """ - # Create or coerce a protobuf request object. - - # Minor optimization to avoid making a copy if the user passes - # in a schema.ValidateMessageRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, schema.ValidateMessageRequest): - request = schema.ValidateMessageRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.validate_message] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def set_iam_policy( - self, - request: iam_policy.SetIamPolicyRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> policy.Policy: - r"""Sets the IAM access control policy on the specified - function. Replaces any existing policy. - Args: - request (:class:`~.iam_policy.SetIamPolicyRequest`): - The request object. Request message for `SetIamPolicy` - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.policy.Policy: - Defines an Identity and Access Management (IAM) policy. - It is used to specify access control policies for Cloud - Platform resources. - A ``Policy`` is a collection of ``bindings``. A - ``binding`` binds one or more ``members`` to a single - ``role``. Members can be user accounts, service - accounts, Google groups, and domains (such as G Suite). - A ``role`` is a named list of permissions (defined by - IAM or configured by users). A ``binding`` can - optionally specify a ``condition``, which is a logic - expression that further constrains the role binding - based on attributes about the request and/or target - resource. - **JSON Example** - :: - { - "bindings": [ - { - "role": "roles/resourcemanager.organizationAdmin", - "members": [ - "user:mike@example.com", - "group:admins@example.com", - "domain:google.com", - "serviceAccount:my-project-id@appspot.gserviceaccount.com" - ] - }, - { - "role": "roles/resourcemanager.organizationViewer", - "members": ["user:eve@example.com"], - "condition": { - "title": "expirable access", - "description": "Does not grant access after Sep 2020", - "expression": "request.time < - timestamp('2020-10-01T00:00:00.000Z')", - } - } - ] - } - **YAML Example** - :: - bindings: - - members: - - user:mike@example.com - - group:admins@example.com - - domain:google.com - - serviceAccount:my-project-id@appspot.gserviceaccount.com - role: roles/resourcemanager.organizationAdmin - - members: - - user:eve@example.com - role: roles/resourcemanager.organizationViewer - condition: - title: expirable access - description: Does not grant access after Sep 2020 - expression: request.time < timestamp('2020-10-01T00:00:00.000Z') - For a description of IAM and its features, see the `IAM - developer's - guide `__. - """ - # Create or coerce a protobuf request object. - - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = iam_policy.SetIamPolicyRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.set_iam_policy, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("resource", request.resource),)), - ) - - # Send the request. - response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - def get_iam_policy( - self, - request: iam_policy.GetIamPolicyRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> policy.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`): - The request object. Request message for `GetIamPolicy` - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.policy.Policy: - Defines an Identity and Access Management (IAM) policy. - It is used to specify access control policies for Cloud - Platform resources. - A ``Policy`` is a collection of ``bindings``. A - ``binding`` binds one or more ``members`` to a single - ``role``. Members can be user accounts, service - accounts, Google groups, and domains (such as G Suite). - A ``role`` is a named list of permissions (defined by - IAM or configured by users). A ``binding`` can - optionally specify a ``condition``, which is a logic - expression that further constrains the role binding - based on attributes about the request and/or target - resource. - **JSON Example** - :: - { - "bindings": [ - { - "role": "roles/resourcemanager.organizationAdmin", - "members": [ - "user:mike@example.com", - "group:admins@example.com", - "domain:google.com", - "serviceAccount:my-project-id@appspot.gserviceaccount.com" - ] - }, - { - "role": "roles/resourcemanager.organizationViewer", - "members": ["user:eve@example.com"], - "condition": { - "title": "expirable access", - "description": "Does not grant access after Sep 2020", - "expression": "request.time < - timestamp('2020-10-01T00:00:00.000Z')", - } - } - ] - } - **YAML Example** - :: - bindings: - - members: - - user:mike@example.com - - group:admins@example.com - - domain:google.com - - serviceAccount:my-project-id@appspot.gserviceaccount.com - role: roles/resourcemanager.organizationAdmin - - members: - - user:eve@example.com - role: roles/resourcemanager.organizationViewer - condition: - title: expirable access - description: Does not grant access after Sep 2020 - expression: request.time < timestamp('2020-10-01T00:00:00.000Z') - For a description of IAM and its features, see the `IAM - developer's - guide `__. - """ - # Create or coerce a protobuf request object. - - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = iam_policy.GetIamPolicyRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.get_iam_policy, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("resource", request.resource),)), - ) - - # Send the request. - response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - def test_iam_permissions( - self, - request: iam_policy.TestIamPermissionsRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> iam_policy.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`): - The request object. Request message for - `TestIamPermissions` method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.iam_policy.TestIamPermissionsResponse: - Response message for ``TestIamPermissions`` method. - """ - # Create or coerce a protobuf request object. - - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = iam_policy.TestIamPermissionsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.test_iam_permissions, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("resource", request.resource),)), - ) - - # Send the request. - response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - 'google-pubsub', - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - 'SchemaServiceClient', -) diff --git a/owl-bot-staging/v1/google/pubsub_v1/services/schema_service/pagers.py b/owl-bot-staging/v1/google/pubsub_v1/services/schema_service/pagers.py deleted file mode 100644 index 33081ca44..000000000 --- a/owl-bot-staging/v1/google/pubsub_v1/services/schema_service/pagers.py +++ /dev/null @@ -1,142 +0,0 @@ -# -*- coding: utf-8 -*- - -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -from typing import Any, AsyncIterable, Awaitable, Callable, Iterable, Sequence, Tuple, Optional - -from google.pubsub_v1.types import schema - - -class ListSchemasPager: - """A pager for iterating through ``list_schemas`` requests. - - This class thinly wraps an initial - :class:`google.pubsub_v1.types.ListSchemasResponse` object, and - provides an ``__iter__`` method to iterate through its - ``schemas`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListSchemas`` requests and continue to iterate - through the ``schemas`` field on the - corresponding responses. - - All the usual :class:`google.pubsub_v1.types.ListSchemasResponse` - attributes are available on the pager. If multiple requests are made, only - the most recent response is retained, and thus used for attribute lookup. - """ - def __init__(self, - method: Callable[..., schema.ListSchemasResponse], - request: schema.ListSchemasRequest, - response: schema.ListSchemasResponse, - *, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiate the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.pubsub_v1.types.ListSchemasRequest): - The initial request object. - response (google.pubsub_v1.types.ListSchemasResponse): - The initial response object. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = schema.ListSchemasRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterable[schema.ListSchemasResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = self._method(self._request, metadata=self._metadata) - yield self._response - - def __iter__(self) -> Iterable[schema.Schema]: - for page in self.pages: - yield from page.schemas - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListSchemasAsyncPager: - """A pager for iterating through ``list_schemas`` requests. - - This class thinly wraps an initial - :class:`google.pubsub_v1.types.ListSchemasResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``schemas`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListSchemas`` requests and continue to iterate - through the ``schemas`` field on the - corresponding responses. - - All the usual :class:`google.pubsub_v1.types.ListSchemasResponse` - attributes are available on the pager. If multiple requests are made, only - the most recent response is retained, and thus used for attribute lookup. - """ - def __init__(self, - method: Callable[..., Awaitable[schema.ListSchemasResponse]], - request: schema.ListSchemasRequest, - response: schema.ListSchemasResponse, - *, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiate the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.pubsub_v1.types.ListSchemasRequest): - The initial request object. - response (google.pubsub_v1.types.ListSchemasResponse): - The initial response object. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = schema.ListSchemasRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterable[schema.ListSchemasResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = await self._method(self._request, metadata=self._metadata) - yield self._response - - def __aiter__(self) -> AsyncIterable[schema.Schema]: - async def async_generator(): - async for page in self.pages: - for response in page.schemas: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) diff --git a/owl-bot-staging/v1/google/pubsub_v1/services/schema_service/transports/__init__.py b/owl-bot-staging/v1/google/pubsub_v1/services/schema_service/transports/__init__.py deleted file mode 100644 index e8b9b6315..000000000 --- a/owl-bot-staging/v1/google/pubsub_v1/services/schema_service/transports/__init__.py +++ /dev/null @@ -1,35 +0,0 @@ -# -*- coding: utf-8 -*- - -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -from collections import OrderedDict -from typing import Dict, Type - -from .base import SchemaServiceTransport -from .grpc import SchemaServiceGrpcTransport -from .grpc_asyncio import SchemaServiceGrpcAsyncIOTransport - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[SchemaServiceTransport]] -_transport_registry['grpc'] = SchemaServiceGrpcTransport -_transport_registry['grpc_asyncio'] = SchemaServiceGrpcAsyncIOTransport - -__all__ = ( - 'SchemaServiceTransport', - 'SchemaServiceGrpcTransport', - 'SchemaServiceGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v1/google/pubsub_v1/services/schema_service/transports/base.py b/owl-bot-staging/v1/google/pubsub_v1/services/schema_service/transports/base.py deleted file mode 100644 index 75209ec2a..000000000 --- a/owl-bot-staging/v1/google/pubsub_v1/services/schema_service/transports/base.py +++ /dev/null @@ -1,232 +0,0 @@ -# -*- coding: utf-8 -*- - -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -import abc -import typing -import pkg_resources - -from google import auth # 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 -from google.auth import 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.pubsub_v1.types import schema -from google.pubsub_v1.types import schema as gp_schema - - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - 'google-pubsub', - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - -class SchemaServiceTransport(abc.ABC): - """Abstract transport class for SchemaService.""" - - AUTH_SCOPES = ( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/pubsub', - ) - - 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, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - **kwargs, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - 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): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - """ - # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ':' not in host: - host += ':443' - self._host = host - - # 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("'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 - ) - - elif credentials is None: - credentials, _ = auth.default(scopes=self._scopes, quota_project_id=quota_project_id) - - # Save the credentials. - self._credentials = credentials - - def _prep_wrapped_messages(self, client_info): - # Precompute the wrapped methods. - self._wrapped_methods = { - self.create_schema: gapic_v1.method.wrap_method( - self.create_schema, - default_timeout=None, - client_info=client_info, - ), - self.get_schema: gapic_v1.method.wrap_method( - self.get_schema, - default_timeout=None, - client_info=client_info, - ), - self.list_schemas: gapic_v1.method.wrap_method( - self.list_schemas, - default_timeout=None, - client_info=client_info, - ), - self.delete_schema: gapic_v1.method.wrap_method( - self.delete_schema, - default_timeout=None, - client_info=client_info, - ), - self.validate_schema: gapic_v1.method.wrap_method( - self.validate_schema, - default_timeout=None, - client_info=client_info, - ), - self.validate_message: gapic_v1.method.wrap_method( - self.validate_message, - default_timeout=None, - client_info=client_info, - ), - - } - - @property - def create_schema(self) -> typing.Callable[ - [gp_schema.CreateSchemaRequest], - typing.Union[ - gp_schema.Schema, - typing.Awaitable[gp_schema.Schema] - ]]: - raise NotImplementedError() - - @property - def get_schema(self) -> typing.Callable[ - [schema.GetSchemaRequest], - typing.Union[ - schema.Schema, - typing.Awaitable[schema.Schema] - ]]: - raise NotImplementedError() - - @property - def list_schemas(self) -> typing.Callable[ - [schema.ListSchemasRequest], - typing.Union[ - schema.ListSchemasResponse, - typing.Awaitable[schema.ListSchemasResponse] - ]]: - raise NotImplementedError() - - @property - def delete_schema(self) -> typing.Callable[ - [schema.DeleteSchemaRequest], - typing.Union[ - empty.Empty, - typing.Awaitable[empty.Empty] - ]]: - raise NotImplementedError() - - @property - def validate_schema(self) -> typing.Callable[ - [gp_schema.ValidateSchemaRequest], - typing.Union[ - gp_schema.ValidateSchemaResponse, - typing.Awaitable[gp_schema.ValidateSchemaResponse] - ]]: - raise NotImplementedError() - - @property - def validate_message(self) -> typing.Callable[ - [schema.ValidateMessageRequest], - typing.Union[ - schema.ValidateMessageResponse, - typing.Awaitable[schema.ValidateMessageResponse] - ]]: - raise NotImplementedError() - - @property - def set_iam_policy( - self, - ) -> typing.Callable[ - [iam_policy.SetIamPolicyRequest], - typing.Union[policy.Policy, typing.Awaitable[policy.Policy]], - ]: - raise NotImplementedError() - - @property - def get_iam_policy( - self, - ) -> typing.Callable[ - [iam_policy.GetIamPolicyRequest], - typing.Union[policy.Policy, typing.Awaitable[policy.Policy]], - ]: - raise NotImplementedError() - - @property - def test_iam_permissions( - self, - ) -> typing.Callable[ - [iam_policy.TestIamPermissionsRequest], - typing.Union[ - iam_policy.TestIamPermissionsResponse, - typing.Awaitable[iam_policy.TestIamPermissionsResponse], - ], - ]: - raise NotImplementedError() - - -__all__ = ( - 'SchemaServiceTransport', -) diff --git a/owl-bot-staging/v1/google/pubsub_v1/services/schema_service/transports/grpc.py b/owl-bot-staging/v1/google/pubsub_v1/services/schema_service/transports/grpc.py deleted file mode 100644 index e0b15742f..000000000 --- a/owl-bot-staging/v1/google/pubsub_v1/services/schema_service/transports/grpc.py +++ /dev/null @@ -1,461 +0,0 @@ -# -*- coding: utf-8 -*- - -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple - -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 -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.pubsub_v1.types import schema -from google.pubsub_v1.types import schema as gp_schema - -from .base import SchemaServiceTransport, DEFAULT_CLIENT_INFO - - -class SchemaServiceGrpcTransport(SchemaServiceTransport): - """gRPC backend transport for SchemaService. - - Service for doing schema-related operations. - - This class defines the same methods as the primary client, so the - primary client can load the underlying transport implementation - and call it. - - It sends protocol buffers over the wire using gRPC (which is built on - top of HTTP/2); the ``grpcio`` package must be installed. - """ - _stubs: Dict[str, Callable] - - def __init__(self, *, - host: str = 'pubsub.googleapis.com', - credentials: credentials.Credentials = None, - credentials_file: str = None, - scopes: Sequence[str] = None, - channel: grpc.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - channel (Optional[grpc.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or applicatin default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - credentials=self._credentials, - credentials_file=credentials_file, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @classmethod - def create_channel(cls, - host: str = 'pubsub.googleapis.com', - credentials: credentials.Credentials = None, - credentials_file: str = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> grpc.Channel: - """Create and return a gRPC channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - grpc.Channel: A gRPC channel object. - - Raises: - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - 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, - **kwargs - ) - - @property - def grpc_channel(self) -> grpc.Channel: - """Return the channel designed to connect to this service. - """ - return self._grpc_channel - - @property - def create_schema(self) -> Callable[ - [gp_schema.CreateSchemaRequest], - gp_schema.Schema]: - r"""Return a callable for the create schema method over gRPC. - - Creates a schema. - - Returns: - Callable[[~.CreateSchemaRequest], - ~.Schema]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'create_schema' not in self._stubs: - self._stubs['create_schema'] = self.grpc_channel.unary_unary( - '/google.pubsub.v1.SchemaService/CreateSchema', - request_serializer=gp_schema.CreateSchemaRequest.serialize, - response_deserializer=gp_schema.Schema.deserialize, - ) - return self._stubs['create_schema'] - - @property - def get_schema(self) -> Callable[ - [schema.GetSchemaRequest], - schema.Schema]: - r"""Return a callable for the get schema method over gRPC. - - Gets a schema. - - Returns: - Callable[[~.GetSchemaRequest], - ~.Schema]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'get_schema' not in self._stubs: - self._stubs['get_schema'] = self.grpc_channel.unary_unary( - '/google.pubsub.v1.SchemaService/GetSchema', - request_serializer=schema.GetSchemaRequest.serialize, - response_deserializer=schema.Schema.deserialize, - ) - return self._stubs['get_schema'] - - @property - def list_schemas(self) -> Callable[ - [schema.ListSchemasRequest], - schema.ListSchemasResponse]: - r"""Return a callable for the list schemas method over gRPC. - - Lists schemas in a project. - - Returns: - Callable[[~.ListSchemasRequest], - ~.ListSchemasResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'list_schemas' not in self._stubs: - self._stubs['list_schemas'] = self.grpc_channel.unary_unary( - '/google.pubsub.v1.SchemaService/ListSchemas', - request_serializer=schema.ListSchemasRequest.serialize, - response_deserializer=schema.ListSchemasResponse.deserialize, - ) - return self._stubs['list_schemas'] - - @property - def delete_schema(self) -> Callable[ - [schema.DeleteSchemaRequest], - empty.Empty]: - r"""Return a callable for the delete schema method over gRPC. - - Deletes a schema. - - Returns: - Callable[[~.DeleteSchemaRequest], - ~.Empty]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'delete_schema' not in self._stubs: - self._stubs['delete_schema'] = self.grpc_channel.unary_unary( - '/google.pubsub.v1.SchemaService/DeleteSchema', - request_serializer=schema.DeleteSchemaRequest.serialize, - response_deserializer=empty.Empty.FromString, - ) - return self._stubs['delete_schema'] - - @property - def validate_schema(self) -> Callable[ - [gp_schema.ValidateSchemaRequest], - gp_schema.ValidateSchemaResponse]: - r"""Return a callable for the validate schema method over gRPC. - - Validates a schema. - - Returns: - Callable[[~.ValidateSchemaRequest], - ~.ValidateSchemaResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'validate_schema' not in self._stubs: - self._stubs['validate_schema'] = self.grpc_channel.unary_unary( - '/google.pubsub.v1.SchemaService/ValidateSchema', - request_serializer=gp_schema.ValidateSchemaRequest.serialize, - response_deserializer=gp_schema.ValidateSchemaResponse.deserialize, - ) - return self._stubs['validate_schema'] - - @property - def validate_message(self) -> Callable[ - [schema.ValidateMessageRequest], - schema.ValidateMessageResponse]: - r"""Return a callable for the validate message method over gRPC. - - Validates a message against a schema. - - Returns: - Callable[[~.ValidateMessageRequest], - ~.ValidateMessageResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'validate_message' not in self._stubs: - self._stubs['validate_message'] = self.grpc_channel.unary_unary( - '/google.pubsub.v1.SchemaService/ValidateMessage', - request_serializer=schema.ValidateMessageRequest.serialize, - response_deserializer=schema.ValidateMessageResponse.deserialize, - ) - return self._stubs['validate_message'] - - @property - def set_iam_policy( - self, - ) -> Callable[[iam_policy.SetIamPolicyRequest], policy.Policy]: - r"""Return a callable for the set iam policy method over gRPC. - Sets the IAM access control policy on the specified - function. Replaces any existing policy. - Returns: - Callable[[~.SetIamPolicyRequest], - ~.Policy]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "set_iam_policy" not in self._stubs: - self._stubs["set_iam_policy"] = self.grpc_channel.unary_unary( - "/google.iam.v1.IAMPolicy/SetIamPolicy", - request_serializer=iam_policy.SetIamPolicyRequest.SerializeToString, - response_deserializer=policy.Policy.FromString, - ) - return self._stubs["set_iam_policy"] - - @property - def get_iam_policy( - self, - ) -> Callable[[iam_policy.GetIamPolicyRequest], policy.Policy]: - r"""Return a callable for the get iam policy method over gRPC. - Gets the IAM access control policy for a function. - Returns an empty policy if the function exists and does - not have a policy set. - Returns: - Callable[[~.GetIamPolicyRequest], - ~.Policy]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "get_iam_policy" not in self._stubs: - self._stubs["get_iam_policy"] = self.grpc_channel.unary_unary( - "/google.iam.v1.IAMPolicy/GetIamPolicy", - request_serializer=iam_policy.GetIamPolicyRequest.SerializeToString, - response_deserializer=policy.Policy.FromString, - ) - return self._stubs["get_iam_policy"] - - @property - def test_iam_permissions( - self, - ) -> Callable[ - [iam_policy.TestIamPermissionsRequest], iam_policy.TestIamPermissionsResponse - ]: - r"""Return a callable for the test iam permissions method over gRPC. - Tests the specified permissions against the IAM access control - policy for a function. If the function does not exist, this will - return an empty set of permissions, not a NOT_FOUND error. - Returns: - Callable[[~.TestIamPermissionsRequest], - ~.TestIamPermissionsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "test_iam_permissions" not in self._stubs: - self._stubs["test_iam_permissions"] = self.grpc_channel.unary_unary( - "/google.iam.v1.IAMPolicy/TestIamPermissions", - request_serializer=iam_policy.TestIamPermissionsRequest.SerializeToString, - response_deserializer=iam_policy.TestIamPermissionsResponse.FromString, - ) - return self._stubs["test_iam_permissions"] - - -__all__ = ( - 'SchemaServiceGrpcTransport', -) diff --git a/owl-bot-staging/v1/google/pubsub_v1/services/schema_service/transports/grpc_asyncio.py b/owl-bot-staging/v1/google/pubsub_v1/services/schema_service/transports/grpc_asyncio.py deleted file mode 100644 index 8972d09be..000000000 --- a/owl-bot-staging/v1/google/pubsub_v1/services/schema_service/transports/grpc_asyncio.py +++ /dev/null @@ -1,467 +0,0 @@ -# -*- coding: utf-8 -*- - -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -import warnings -from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple - -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 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.pubsub_v1.types import schema -from google.pubsub_v1.types import schema as gp_schema - -from .base import SchemaServiceTransport, DEFAULT_CLIENT_INFO -from .grpc import SchemaServiceGrpcTransport - - -class SchemaServiceGrpcAsyncIOTransport(SchemaServiceTransport): - """gRPC AsyncIO backend transport for SchemaService. - - Service for doing schema-related operations. - - This class defines the same methods as the primary client, so the - primary client can load the underlying transport implementation - and call it. - - It sends protocol buffers over the wire using gRPC (which is built on - top of HTTP/2); the ``grpcio`` package must be installed. - """ - - _grpc_channel: aio.Channel - _stubs: Dict[str, Callable] = {} - - @classmethod - def create_channel(cls, - host: str = 'pubsub.googleapis.com', - credentials: credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> aio.Channel: - """Create and return a gRPC AsyncIO channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - aio.Channel: A gRPC AsyncIO channel object. - """ - 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, - **kwargs - ) - - def __init__(self, *, - host: str = 'pubsub.googleapis.com', - credentials: credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: aio.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, - quota_project_id=None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - channel (Optional[aio.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or applicatin default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - credentials=self._credentials, - credentials_file=credentials_file, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @property - def grpc_channel(self) -> aio.Channel: - """Create the channel designed to connect to this service. - - This property caches on the instance; repeated calls return - the same channel. - """ - # Return the channel from cache. - return self._grpc_channel - - @property - def create_schema(self) -> Callable[ - [gp_schema.CreateSchemaRequest], - Awaitable[gp_schema.Schema]]: - r"""Return a callable for the create schema method over gRPC. - - Creates a schema. - - Returns: - Callable[[~.CreateSchemaRequest], - Awaitable[~.Schema]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'create_schema' not in self._stubs: - self._stubs['create_schema'] = self.grpc_channel.unary_unary( - '/google.pubsub.v1.SchemaService/CreateSchema', - request_serializer=gp_schema.CreateSchemaRequest.serialize, - response_deserializer=gp_schema.Schema.deserialize, - ) - return self._stubs['create_schema'] - - @property - def get_schema(self) -> Callable[ - [schema.GetSchemaRequest], - Awaitable[schema.Schema]]: - r"""Return a callable for the get schema method over gRPC. - - Gets a schema. - - Returns: - Callable[[~.GetSchemaRequest], - Awaitable[~.Schema]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'get_schema' not in self._stubs: - self._stubs['get_schema'] = self.grpc_channel.unary_unary( - '/google.pubsub.v1.SchemaService/GetSchema', - request_serializer=schema.GetSchemaRequest.serialize, - response_deserializer=schema.Schema.deserialize, - ) - return self._stubs['get_schema'] - - @property - def list_schemas(self) -> Callable[ - [schema.ListSchemasRequest], - Awaitable[schema.ListSchemasResponse]]: - r"""Return a callable for the list schemas method over gRPC. - - Lists schemas in a project. - - Returns: - Callable[[~.ListSchemasRequest], - Awaitable[~.ListSchemasResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'list_schemas' not in self._stubs: - self._stubs['list_schemas'] = self.grpc_channel.unary_unary( - '/google.pubsub.v1.SchemaService/ListSchemas', - request_serializer=schema.ListSchemasRequest.serialize, - response_deserializer=schema.ListSchemasResponse.deserialize, - ) - return self._stubs['list_schemas'] - - @property - def delete_schema(self) -> Callable[ - [schema.DeleteSchemaRequest], - Awaitable[empty.Empty]]: - r"""Return a callable for the delete schema method over gRPC. - - Deletes a schema. - - Returns: - Callable[[~.DeleteSchemaRequest], - Awaitable[~.Empty]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'delete_schema' not in self._stubs: - self._stubs['delete_schema'] = self.grpc_channel.unary_unary( - '/google.pubsub.v1.SchemaService/DeleteSchema', - request_serializer=schema.DeleteSchemaRequest.serialize, - response_deserializer=empty.Empty.FromString, - ) - return self._stubs['delete_schema'] - - @property - def validate_schema(self) -> Callable[ - [gp_schema.ValidateSchemaRequest], - Awaitable[gp_schema.ValidateSchemaResponse]]: - r"""Return a callable for the validate schema method over gRPC. - - Validates a schema. - - Returns: - Callable[[~.ValidateSchemaRequest], - Awaitable[~.ValidateSchemaResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'validate_schema' not in self._stubs: - self._stubs['validate_schema'] = self.grpc_channel.unary_unary( - '/google.pubsub.v1.SchemaService/ValidateSchema', - request_serializer=gp_schema.ValidateSchemaRequest.serialize, - response_deserializer=gp_schema.ValidateSchemaResponse.deserialize, - ) - return self._stubs['validate_schema'] - - @property - def validate_message(self) -> Callable[ - [schema.ValidateMessageRequest], - Awaitable[schema.ValidateMessageResponse]]: - r"""Return a callable for the validate message method over gRPC. - - Validates a message against a schema. - - Returns: - Callable[[~.ValidateMessageRequest], - Awaitable[~.ValidateMessageResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'validate_message' not in self._stubs: - self._stubs['validate_message'] = self.grpc_channel.unary_unary( - '/google.pubsub.v1.SchemaService/ValidateMessage', - request_serializer=schema.ValidateMessageRequest.serialize, - response_deserializer=schema.ValidateMessageResponse.deserialize, - ) - return self._stubs['validate_message'] - - @property - def set_iam_policy( - self, - ) -> Callable[[iam_policy.SetIamPolicyRequest], Awaitable[policy.Policy]]: - r"""Return a callable for the set iam policy method over gRPC. - Sets the IAM access control policy on the specified - function. Replaces any existing policy. - Returns: - Callable[[~.SetIamPolicyRequest], - Awaitable[~.Policy]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "set_iam_policy" not in self._stubs: - self._stubs["set_iam_policy"] = self.grpc_channel.unary_unary( - "/google.iam.v1.IAMPolicy/SetIamPolicy", - request_serializer=iam_policy.SetIamPolicyRequest.SerializeToString, - response_deserializer=policy.Policy.FromString, - ) - return self._stubs["set_iam_policy"] - - @property - def get_iam_policy( - self, - ) -> Callable[[iam_policy.GetIamPolicyRequest], Awaitable[policy.Policy]]: - r"""Return a callable for the get iam policy method over gRPC. - Gets the IAM access control policy for a function. - Returns an empty policy if the function exists and does - not have a policy set. - Returns: - Callable[[~.GetIamPolicyRequest], - Awaitable[~.Policy]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "get_iam_policy" not in self._stubs: - self._stubs["get_iam_policy"] = self.grpc_channel.unary_unary( - "/google.iam.v1.IAMPolicy/GetIamPolicy", - request_serializer=iam_policy.GetIamPolicyRequest.SerializeToString, - response_deserializer=policy.Policy.FromString, - ) - return self._stubs["get_iam_policy"] - - @property - def test_iam_permissions( - self, - ) -> Callable[ - [iam_policy.TestIamPermissionsRequest], - Awaitable[iam_policy.TestIamPermissionsResponse], - ]: - r"""Return a callable for the test iam permissions method over gRPC. - Tests the specified permissions against the IAM access control - policy for a function. If the function does not exist, this will - return an empty set of permissions, not a NOT_FOUND error. - Returns: - Callable[[~.TestIamPermissionsRequest], - Awaitable[~.TestIamPermissionsResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "test_iam_permissions" not in self._stubs: - self._stubs["test_iam_permissions"] = self.grpc_channel.unary_unary( - "/google.iam.v1.IAMPolicy/TestIamPermissions", - request_serializer=iam_policy.TestIamPermissionsRequest.SerializeToString, - response_deserializer=iam_policy.TestIamPermissionsResponse.FromString, - ) - return self._stubs["test_iam_permissions"] - - -__all__ = ( - 'SchemaServiceGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v1/google/pubsub_v1/services/subscriber/__init__.py b/owl-bot-staging/v1/google/pubsub_v1/services/subscriber/__init__.py deleted file mode 100644 index 0b9bda81d..000000000 --- a/owl-bot-staging/v1/google/pubsub_v1/services/subscriber/__init__.py +++ /dev/null @@ -1,24 +0,0 @@ -# -*- coding: utf-8 -*- - -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -from .client import SubscriberClient -from .async_client import SubscriberAsyncClient - -__all__ = ( - 'SubscriberClient', - 'SubscriberAsyncClient', -) diff --git a/owl-bot-staging/v1/google/pubsub_v1/services/subscriber/async_client.py b/owl-bot-staging/v1/google/pubsub_v1/services/subscriber/async_client.py deleted file mode 100644 index 326ec6d9a..000000000 --- a/owl-bot-staging/v1/google/pubsub_v1/services/subscriber/async_client.py +++ /dev/null @@ -1,1994 +0,0 @@ -# -*- coding: utf-8 -*- - -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -from collections import OrderedDict -import functools -import re -from typing import Dict, AsyncIterable, Awaitable, AsyncIterator, Sequence, Tuple, Type, Union -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 gapic_v1 # type: ignore -from google.api_core import retry as retries # type: ignore -from google.auth import 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.pubsub_v1.services.subscriber import pagers -from google.pubsub_v1.types import pubsub - -from .transports.base import SubscriberTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import SubscriberGrpcAsyncIOTransport -from .client import SubscriberClient - - -class SubscriberAsyncClient: - """The service that an application uses to manipulate subscriptions and - to consume messages from a subscription via the ``Pull`` method or - by establishing a bi-directional stream using the ``StreamingPull`` - method. - """ - - _client: SubscriberClient - - DEFAULT_ENDPOINT = SubscriberClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = SubscriberClient.DEFAULT_MTLS_ENDPOINT - - snapshot_path = staticmethod(SubscriberClient.snapshot_path) - parse_snapshot_path = staticmethod(SubscriberClient.parse_snapshot_path) - subscription_path = staticmethod(SubscriberClient.subscription_path) - parse_subscription_path = staticmethod(SubscriberClient.parse_subscription_path) - topic_path = staticmethod(SubscriberClient.topic_path) - parse_topic_path = staticmethod(SubscriberClient.parse_topic_path) - - common_billing_account_path = staticmethod(SubscriberClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(SubscriberClient.parse_common_billing_account_path) - - common_folder_path = staticmethod(SubscriberClient.common_folder_path) - parse_common_folder_path = staticmethod(SubscriberClient.parse_common_folder_path) - - common_organization_path = staticmethod(SubscriberClient.common_organization_path) - parse_common_organization_path = staticmethod(SubscriberClient.parse_common_organization_path) - - common_project_path = staticmethod(SubscriberClient.common_project_path) - parse_common_project_path = staticmethod(SubscriberClient.parse_common_project_path) - - common_location_path = staticmethod(SubscriberClient.common_location_path) - parse_common_location_path = staticmethod(SubscriberClient.parse_common_location_path) - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials info. - - Args: - info (dict): The service account private key info. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - SubscriberAsyncClient: The constructed client. - """ - return SubscriberClient.from_service_account_info.__func__(SubscriberAsyncClient, info, *args, **kwargs) # type: ignore - - @classmethod - def from_service_account_file(cls, filename: str, *args, **kwargs): - """Creates an instance of this client using the provided credentials - file. - - Args: - filename (str): The path to the service account private key json - file. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - SubscriberAsyncClient: The constructed client. - """ - return SubscriberClient.from_service_account_file.__func__(SubscriberAsyncClient, filename, *args, **kwargs) # type: ignore - - from_service_account_json = from_service_account_file - - @property - def transport(self) -> SubscriberTransport: - """Return the transport used by the client instance. - - Returns: - SubscriberTransport: The transport used by the client instance. - """ - return self._client.transport - - get_transport_class = functools.partial(type(SubscriberClient).get_transport_class, type(SubscriberClient)) - - def __init__(self, *, - credentials: credentials.Credentials = None, - transport: Union[str, SubscriberTransport] = 'grpc_asyncio', - client_options: ClientOptions = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiate the subscriber client. - - Args: - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - transport (Union[str, ~.SubscriberTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (ClientOptions): Custom options for the client. It - won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - """ - - self._client = SubscriberClient( - credentials=credentials, - transport=transport, - client_options=client_options, - client_info=client_info, - - ) - - async def create_subscription(self, - request: pubsub.Subscription = None, - *, - name: str = None, - topic: str = None, - push_config: pubsub.PushConfig = None, - ack_deadline_seconds: int = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pubsub.Subscription: - r"""Creates a subscription to a given topic. See the [resource name - rules] - (https://cloud.google.com/pubsub/docs/admin#resource_names). If - the subscription already exists, returns ``ALREADY_EXISTS``. If - the corresponding topic doesn't exist, returns ``NOT_FOUND``. - - If the name is not provided in the request, the server will - assign a random name for this subscription on the same project - as the topic, conforming to the [resource name format] - (https://cloud.google.com/pubsub/docs/admin#resource_names). The - generated name is populated in the returned Subscription object. - Note that for REST API requests, you must specify a name in the - request. - - Args: - request (:class:`google.pubsub_v1.types.Subscription`): - The request object. A subscription resource. - name (:class:`str`): - Required. The name of the subscription. It must have the - format - ``"projects/{project}/subscriptions/{subscription}"``. - ``{subscription}`` must start with a letter, and contain - only letters (``[A-Za-z]``), numbers (``[0-9]``), dashes - (``-``), underscores (``_``), periods (``.``), tildes - (``~``), plus (``+``) or percent signs (``%``). It must - be between 3 and 255 characters in length, and it must - not start with ``"goog"``. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - topic (:class:`str`): - Required. The name of the topic from which this - subscription is receiving messages. Format is - ``projects/{project}/topics/{topic}``. The value of this - field will be ``_deleted-topic_`` if the topic has been - deleted. - - This corresponds to the ``topic`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - push_config (:class:`google.pubsub_v1.types.PushConfig`): - If push delivery is used with this subscription, this - field is used to configure it. An empty ``pushConfig`` - signifies that the subscriber will pull and ack messages - using API methods. - - This corresponds to the ``push_config`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - ack_deadline_seconds (:class:`int`): - The approximate amount of time (on a best-effort basis) - Pub/Sub waits for the subscriber to acknowledge receipt - before resending the message. In the interval after the - message is delivered and before it is acknowledged, it - is considered to be outstanding. During that time - period, the message will not be redelivered (on a - best-effort basis). - - For pull subscriptions, this value is used as the - initial value for the ack deadline. To override this - value for a given message, call ``ModifyAckDeadline`` - with the corresponding ``ack_id`` if using non-streaming - pull or send the ``ack_id`` in a - ``StreamingModifyAckDeadlineRequest`` if using streaming - pull. The minimum custom deadline you can specify is 10 - seconds. The maximum custom deadline you can specify is - 600 seconds (10 minutes). If this parameter is 0, a - default value of 10 seconds is used. - - For push delivery, this value is also used to set the - request timeout for the call to the push endpoint. - - If the subscriber never acknowledges the message, the - Pub/Sub system will eventually redeliver the message. - - This corresponds to the ``ack_deadline_seconds`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.pubsub_v1.types.Subscription: - A subscription resource. - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name, topic, push_config, ack_deadline_seconds]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - request = pubsub.Subscription(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - - if name is not None: - request.name = name - if topic is not None: - request.topic = topic - if push_config is not None: - request.push_config = push_config - if ack_deadline_seconds is not None: - request.ack_deadline_seconds = ack_deadline_seconds - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.create_subscription, - default_retry=retries.Retry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - exceptions.Aborted, - exceptions.ServiceUnavailable, - exceptions.Unknown, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('name', request.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def get_subscription(self, - request: pubsub.GetSubscriptionRequest = None, - *, - subscription: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pubsub.Subscription: - r"""Gets the configuration details of a subscription. - - Args: - request (:class:`google.pubsub_v1.types.GetSubscriptionRequest`): - The request object. Request for the GetSubscription - method. - subscription (:class:`str`): - Required. The name of the subscription to get. Format is - ``projects/{project}/subscriptions/{sub}``. - - This corresponds to the ``subscription`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.pubsub_v1.types.Subscription: - A subscription resource. - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([subscription]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - request = pubsub.GetSubscriptionRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - - if subscription is not None: - request.subscription = subscription - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.get_subscription, - default_retry=retries.Retry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - exceptions.Aborted, - exceptions.ServiceUnavailable, - exceptions.Unknown, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('subscription', request.subscription), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def update_subscription(self, - request: pubsub.UpdateSubscriptionRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pubsub.Subscription: - r"""Updates an existing subscription. Note that certain - properties of a subscription, such as its topic, are not - modifiable. - - Args: - 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. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.pubsub_v1.types.Subscription: - A subscription resource. - """ - # Create or coerce a protobuf request object. - - request = pubsub.UpdateSubscriptionRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.update_subscription, - default_retry=retries.Retry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('subscription.name', request.subscription.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def list_subscriptions(self, - request: pubsub.ListSubscriptionsRequest = None, - *, - project: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListSubscriptionsAsyncPager: - r"""Lists matching subscriptions. - - Args: - request (:class:`google.pubsub_v1.types.ListSubscriptionsRequest`): - The request object. Request for the `ListSubscriptions` - method. - project (:class:`str`): - Required. The name of the project in which to list - subscriptions. Format is ``projects/{project-id}``. - - This corresponds to the ``project`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.pubsub_v1.services.subscriber.pagers.ListSubscriptionsAsyncPager: - Response for the ListSubscriptions method. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([project]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - request = pubsub.ListSubscriptionsRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - - if project is not None: - request.project = project - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.list_subscriptions, - default_retry=retries.Retry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - exceptions.Aborted, - exceptions.ServiceUnavailable, - exceptions.Unknown, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('project', request.project), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__aiter__` convenience method. - response = pagers.ListSubscriptionsAsyncPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def delete_subscription(self, - request: pubsub.DeleteSubscriptionRequest = None, - *, - subscription: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes an existing subscription. All messages retained in the - subscription are immediately dropped. Calls to ``Pull`` after - deletion will return ``NOT_FOUND``. After a subscription is - deleted, a new one may be created with the same name, but the - new one has no association with the old subscription or its - topic unless the same topic is specified. - - Args: - request (:class:`google.pubsub_v1.types.DeleteSubscriptionRequest`): - The request object. Request for the DeleteSubscription - method. - subscription (:class:`str`): - Required. The subscription to delete. Format is - ``projects/{project}/subscriptions/{sub}``. - - This corresponds to the ``subscription`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([subscription]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - request = pubsub.DeleteSubscriptionRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - - if subscription is not None: - request.subscription = subscription - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.delete_subscription, - default_retry=retries.Retry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('subscription', request.subscription), - )), - ) - - # Send the request. - await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - async def modify_ack_deadline(self, - request: pubsub.ModifyAckDeadlineRequest = None, - *, - subscription: str = None, - ack_ids: Sequence[str] = None, - ack_deadline_seconds: int = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Modifies the ack deadline for a specific message. This method is - useful to indicate that more time is needed to process a message - by the subscriber, or to make the message available for - redelivery if the processing was interrupted. Note that this - does not modify the subscription-level ``ackDeadlineSeconds`` - used for subsequent messages. - - Args: - request (:class:`google.pubsub_v1.types.ModifyAckDeadlineRequest`): - The request object. Request for the ModifyAckDeadline - method. - subscription (:class:`str`): - Required. The name of the subscription. Format is - ``projects/{project}/subscriptions/{sub}``. - - This corresponds to the ``subscription`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - ack_ids (:class:`Sequence[str]`): - Required. List of acknowledgment IDs. - This corresponds to the ``ack_ids`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - ack_deadline_seconds (:class:`int`): - Required. The new ack deadline with respect to the time - this request was sent to the Pub/Sub system. For - example, if the value is 10, the new ack deadline will - expire 10 seconds after the ``ModifyAckDeadline`` call - was made. Specifying zero might immediately make the - message available for delivery to another subscriber - client. This typically results in an increase in the - rate of message redeliveries (that is, duplicates). The - minimum deadline you can specify is 0 seconds. The - maximum deadline you can specify is 600 seconds (10 - minutes). - - This corresponds to the ``ack_deadline_seconds`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([subscription, ack_ids, ack_deadline_seconds]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - request = pubsub.ModifyAckDeadlineRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - - if subscription is not None: - request.subscription = subscription - if ack_deadline_seconds is not None: - request.ack_deadline_seconds = ack_deadline_seconds - - if ack_ids: - request.ack_ids.extend(ack_ids) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.modify_ack_deadline, - default_retry=retries.Retry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('subscription', request.subscription), - )), - ) - - # Send the request. - await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - async def acknowledge(self, - request: pubsub.AcknowledgeRequest = None, - *, - subscription: str = None, - ack_ids: Sequence[str] = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Acknowledges the messages associated with the ``ack_ids`` in the - ``AcknowledgeRequest``. The Pub/Sub system can remove the - relevant messages from the subscription. - - Acknowledging a message whose ack deadline has expired may - succeed, but such a message may be redelivered later. - Acknowledging a message more than once will not result in an - error. - - Args: - request (:class:`google.pubsub_v1.types.AcknowledgeRequest`): - The request object. Request for the Acknowledge method. - subscription (:class:`str`): - Required. The subscription whose message is being - acknowledged. Format is - ``projects/{project}/subscriptions/{sub}``. - - This corresponds to the ``subscription`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - ack_ids (:class:`Sequence[str]`): - Required. The acknowledgment ID for the messages being - acknowledged that was returned by the Pub/Sub system in - the ``Pull`` response. Must not be empty. - - This corresponds to the ``ack_ids`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([subscription, ack_ids]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - request = pubsub.AcknowledgeRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - - if subscription is not None: - request.subscription = subscription - - if ack_ids: - request.ack_ids.extend(ack_ids) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.acknowledge, - default_retry=retries.Retry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('subscription', request.subscription), - )), - ) - - # Send the request. - await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - async def pull(self, - request: pubsub.PullRequest = None, - *, - subscription: str = None, - return_immediately: bool = None, - max_messages: int = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pubsub.PullResponse: - r"""Pulls messages from the server. The server may return - ``UNAVAILABLE`` if there are too many concurrent pull requests - pending for the given subscription. - - Args: - request (:class:`google.pubsub_v1.types.PullRequest`): - The request object. Request for the `Pull` method. - subscription (:class:`str`): - Required. The subscription from which messages should be - pulled. Format is - ``projects/{project}/subscriptions/{sub}``. - - This corresponds to the ``subscription`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - return_immediately (:class:`bool`): - Optional. If this field set to true, the system will - respond immediately even if it there are no messages - available to return in the ``Pull`` response. Otherwise, - the system may wait (for a bounded amount of time) until - at least one message is available, rather than returning - no messages. Warning: setting this field to ``true`` is - discouraged because it adversely impacts the performance - of ``Pull`` operations. We recommend that users do not - set this field. - - This corresponds to the ``return_immediately`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - max_messages (:class:`int`): - Required. The maximum number of - messages to return for this request. - Must be a positive integer. The Pub/Sub - system may return fewer than the number - specified. - - This corresponds to the ``max_messages`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.pubsub_v1.types.PullResponse: - Response for the Pull method. - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([subscription, return_immediately, max_messages]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - request = pubsub.PullRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - - if subscription is not None: - request.subscription = subscription - if return_immediately is not None: - request.return_immediately = return_immediately - if max_messages is not None: - request.max_messages = max_messages - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.pull, - default_retry=retries.Retry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - exceptions.Aborted, - exceptions.ServiceUnavailable, - exceptions.Unknown, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('subscription', request.subscription), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def streaming_pull(self, - requests: AsyncIterator[pubsub.StreamingPullRequest] = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> Awaitable[AsyncIterable[pubsub.StreamingPullResponse]]: - r"""Establishes a stream with the server, which sends messages down - to the client. The client streams acknowledgements and ack - deadline modifications back to the server. The server will close - the stream and return the status on any error. The server may - close the stream with status ``UNAVAILABLE`` to reassign - server-side resources, in which case, the client should - re-establish the stream. Flow control can be achieved by - configuring the underlying RPC channel. - - Args: - requests (AsyncIterator[`google.pubsub_v1.types.StreamingPullRequest`]): - The request object AsyncIterator. Request for the `StreamingPull` - streaming RPC method. This request is used to establish - the initial stream as well as to stream acknowledgements - and ack deadline modifications from the client to the - server. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - AsyncIterable[google.pubsub_v1.types.StreamingPullResponse]: - Response for the StreamingPull method. This response is used to stream - messages from the server to the client. - - """ - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.streaming_pull, - default_retry=retries.Retry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - exceptions.Aborted, - exceptions.DeadlineExceeded, - exceptions.InternalServerError, - exceptions.ResourceExhausted, - exceptions.ServiceUnavailable, - ), - deadline=900.0, - ), - default_timeout=900.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Send the request. - response = rpc( - requests, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def modify_push_config(self, - request: pubsub.ModifyPushConfigRequest = None, - *, - subscription: str = None, - push_config: pubsub.PushConfig = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Modifies the ``PushConfig`` for a specified subscription. - - This may be used to change a push subscription to a pull one - (signified by an empty ``PushConfig``) or vice versa, or change - the endpoint URL and other attributes of a push subscription. - Messages will accumulate for delivery continuously through the - call regardless of changes to the ``PushConfig``. - - Args: - request (:class:`google.pubsub_v1.types.ModifyPushConfigRequest`): - The request object. Request for the ModifyPushConfig - method. - subscription (:class:`str`): - Required. The name of the subscription. Format is - ``projects/{project}/subscriptions/{sub}``. - - This corresponds to the ``subscription`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - push_config (:class:`google.pubsub_v1.types.PushConfig`): - Required. The push configuration for future deliveries. - - An empty ``pushConfig`` indicates that the Pub/Sub - system should stop pushing messages from the given - subscription and allow messages to be pulled and - acknowledged - effectively pausing the subscription if - ``Pull`` or ``StreamingPull`` is not called. - - This corresponds to the ``push_config`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([subscription, push_config]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - request = pubsub.ModifyPushConfigRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - - if subscription is not None: - request.subscription = subscription - if push_config is not None: - request.push_config = push_config - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.modify_push_config, - default_retry=retries.Retry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('subscription', request.subscription), - )), - ) - - # Send the request. - await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - async def get_snapshot(self, - request: pubsub.GetSnapshotRequest = None, - *, - snapshot: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pubsub.Snapshot: - r"""Gets the configuration details of a snapshot. - Snapshots are used in Seek operations, which allow you to manage - message acknowledgments in bulk. That is, you can set - the acknowledgment state of messages in an existing - subscription to the state captured by a snapshot. - - Args: - request (:class:`google.pubsub_v1.types.GetSnapshotRequest`): - The request object. Request for the GetSnapshot method. - snapshot (:class:`str`): - Required. The name of the snapshot to get. Format is - ``projects/{project}/snapshots/{snap}``. - - This corresponds to the ``snapshot`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.pubsub_v1.types.Snapshot: - A snapshot resource. Snapshots are used in - [Seek](https://cloud.google.com/pubsub/docs/replay-overview) - operations, which allow you to manage message - acknowledgments in bulk. That is, you can set the - acknowledgment state of messages in an existing - subscription to the state captured by a snapshot. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([snapshot]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - request = pubsub.GetSnapshotRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - - if snapshot is not None: - request.snapshot = snapshot - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.get_snapshot, - default_retry=retries.Retry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - exceptions.Aborted, - exceptions.ServiceUnavailable, - exceptions.Unknown, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('snapshot', request.snapshot), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def list_snapshots(self, - request: pubsub.ListSnapshotsRequest = None, - *, - project: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListSnapshotsAsyncPager: - r"""Lists the existing snapshots. Snapshots are used in - `Seek `__ - operations, which allow you to manage message acknowledgments in - bulk. That is, you can set the acknowledgment state of messages - in an existing subscription to the state captured by a snapshot. - - Args: - request (:class:`google.pubsub_v1.types.ListSnapshotsRequest`): - The request object. Request for the `ListSnapshots` - method. - project (:class:`str`): - Required. The name of the project in which to list - snapshots. Format is ``projects/{project-id}``. - - This corresponds to the ``project`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.pubsub_v1.services.subscriber.pagers.ListSnapshotsAsyncPager: - Response for the ListSnapshots method. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([project]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - request = pubsub.ListSnapshotsRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - - if project is not None: - request.project = project - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.list_snapshots, - default_retry=retries.Retry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - exceptions.Aborted, - exceptions.ServiceUnavailable, - exceptions.Unknown, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('project', request.project), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__aiter__` convenience method. - response = pagers.ListSnapshotsAsyncPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def create_snapshot(self, - request: pubsub.CreateSnapshotRequest = None, - *, - name: str = None, - subscription: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pubsub.Snapshot: - r"""Creates a snapshot from the requested subscription. Snapshots - are used in - `Seek `__ - operations, which allow you to manage message acknowledgments in - bulk. That is, you can set the acknowledgment state of messages - in an existing subscription to the state captured by a snapshot. - If the snapshot already exists, returns ``ALREADY_EXISTS``. If - the requested subscription doesn't exist, returns ``NOT_FOUND``. - If the backlog in the subscription is too old -- and the - resulting snapshot would expire in less than 1 hour -- then - ``FAILED_PRECONDITION`` is returned. See also the - ``Snapshot.expire_time`` field. If the name is not provided in - the request, the server will assign a random name for this - snapshot on the same project as the subscription, conforming to - the [resource name format] - (https://cloud.google.com/pubsub/docs/admin#resource_names). The - generated name is populated in the returned Snapshot object. - Note that for REST API requests, you must specify a name in the - request. - - Args: - request (:class:`google.pubsub_v1.types.CreateSnapshotRequest`): - The request object. Request for the `CreateSnapshot` - method. - name (:class:`str`): - Required. User-provided name for this snapshot. If the - name is not provided in the request, the server will - assign a random name for this snapshot on the same - project as the subscription. Note that for REST API - requests, you must specify a name. See the resource name - rules. Format is - ``projects/{project}/snapshots/{snap}``. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - subscription (:class:`str`): - Required. The subscription whose backlog the snapshot - retains. Specifically, the created snapshot is - guaranteed to retain: (a) The existing backlog on the - subscription. More precisely, this is defined as the - messages in the subscription's backlog that are - unacknowledged upon the successful completion of the - ``CreateSnapshot`` request; as well as: (b) Any messages - published to the subscription's topic following the - successful completion of the CreateSnapshot request. - Format is ``projects/{project}/subscriptions/{sub}``. - - This corresponds to the ``subscription`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.pubsub_v1.types.Snapshot: - A snapshot resource. Snapshots are used in - [Seek](https://cloud.google.com/pubsub/docs/replay-overview) - operations, which allow you to manage message - acknowledgments in bulk. That is, you can set the - acknowledgment state of messages in an existing - subscription to the state captured by a snapshot. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name, subscription]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - request = pubsub.CreateSnapshotRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - - if name is not None: - request.name = name - if subscription is not None: - request.subscription = subscription - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.create_snapshot, - default_retry=retries.Retry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('name', request.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def update_snapshot(self, - request: pubsub.UpdateSnapshotRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pubsub.Snapshot: - r"""Updates an existing snapshot. Snapshots are used in - Seek operations, which allow - you to manage message acknowledgments in bulk. That is, - you can set the acknowledgment state of messages in an - existing subscription to the state captured by a - snapshot. - - Args: - 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. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.pubsub_v1.types.Snapshot: - A snapshot resource. Snapshots are used in - [Seek](https://cloud.google.com/pubsub/docs/replay-overview) - operations, which allow you to manage message - acknowledgments in bulk. That is, you can set the - acknowledgment state of messages in an existing - subscription to the state captured by a snapshot. - - """ - # Create or coerce a protobuf request object. - - request = pubsub.UpdateSnapshotRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.update_snapshot, - default_retry=retries.Retry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('snapshot.name', request.snapshot.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def delete_snapshot(self, - request: pubsub.DeleteSnapshotRequest = None, - *, - snapshot: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Removes an existing snapshot. Snapshots are used in [Seek] - (https://cloud.google.com/pubsub/docs/replay-overview) - operations, which allow you to manage message acknowledgments in - bulk. That is, you can set the acknowledgment state of messages - in an existing subscription to the state captured by a snapshot. - When the snapshot is deleted, all messages retained in the - snapshot are immediately dropped. After a snapshot is deleted, a - new one may be created with the same name, but the new one has - no association with the old snapshot or its subscription, unless - the same subscription is specified. - - Args: - request (:class:`google.pubsub_v1.types.DeleteSnapshotRequest`): - The request object. Request for the `DeleteSnapshot` - method. - snapshot (:class:`str`): - Required. The name of the snapshot to delete. Format is - ``projects/{project}/snapshots/{snap}``. - - This corresponds to the ``snapshot`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([snapshot]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - request = pubsub.DeleteSnapshotRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - - if snapshot is not None: - request.snapshot = snapshot - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.delete_snapshot, - default_retry=retries.Retry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('snapshot', request.snapshot), - )), - ) - - # Send the request. - await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - async def seek(self, - request: pubsub.SeekRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pubsub.SeekResponse: - r"""Seeks an existing subscription to a point in time or to a given - snapshot, whichever is provided in the request. Snapshots are - used in [Seek] - (https://cloud.google.com/pubsub/docs/replay-overview) - operations, which allow you to manage message acknowledgments in - bulk. That is, you can set the acknowledgment state of messages - in an existing subscription to the state captured by a snapshot. - Note that both the subscription and the snapshot must be on the - same topic. - - 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. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.pubsub_v1.types.SeekResponse: - Response for the Seek method (this response is empty). - """ - # Create or coerce a protobuf request object. - - request = pubsub.SeekRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.seek, - default_retry=retries.Retry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - exceptions.Aborted, - exceptions.ServiceUnavailable, - exceptions.Unknown, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('subscription', request.subscription), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def set_iam_policy( - self, - request: iam_policy.SetIamPolicyRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> policy.Policy: - r"""Sets the IAM access control policy on the specified - function. Replaces any existing policy. - Args: - request (:class:`~.iam_policy.SetIamPolicyRequest`): - The request object. Request message for `SetIamPolicy` - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.policy.Policy: - Defines an Identity and Access Management (IAM) policy. - It is used to specify access control policies for Cloud - Platform resources. - A ``Policy`` is a collection of ``bindings``. A - ``binding`` binds one or more ``members`` to a single - ``role``. Members can be user accounts, service - accounts, Google groups, and domains (such as G Suite). - A ``role`` is a named list of permissions (defined by - IAM or configured by users). A ``binding`` can - optionally specify a ``condition``, which is a logic - expression that further constrains the role binding - based on attributes about the request and/or target - resource. - **JSON Example** - :: - { - "bindings": [ - { - "role": "roles/resourcemanager.organizationAdmin", - "members": [ - "user:mike@example.com", - "group:admins@example.com", - "domain:google.com", - "serviceAccount:my-project-id@appspot.gserviceaccount.com" - ] - }, - { - "role": "roles/resourcemanager.organizationViewer", - "members": ["user:eve@example.com"], - "condition": { - "title": "expirable access", - "description": "Does not grant access after Sep 2020", - "expression": "request.time < - timestamp('2020-10-01T00:00:00.000Z')", - } - } - ] - } - **YAML Example** - :: - bindings: - - members: - - user:mike@example.com - - group:admins@example.com - - domain:google.com - - serviceAccount:my-project-id@appspot.gserviceaccount.com - role: roles/resourcemanager.organizationAdmin - - members: - - user:eve@example.com - role: roles/resourcemanager.organizationViewer - condition: - title: expirable access - description: Does not grant access after Sep 2020 - expression: request.time < timestamp('2020-10-01T00:00:00.000Z') - For a description of IAM and its features, see the `IAM - developer's - guide `__. - """ - # Create or coerce a protobuf request object. - - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = iam_policy.SetIamPolicyRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.set_iam_policy, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("resource", request.resource),)), - ) - - # Send the request. - response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - async def get_iam_policy( - self, - request: iam_policy.GetIamPolicyRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> policy.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`): - The request object. Request message for `GetIamPolicy` - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.policy.Policy: - Defines an Identity and Access Management (IAM) policy. - It is used to specify access control policies for Cloud - Platform resources. - A ``Policy`` is a collection of ``bindings``. A - ``binding`` binds one or more ``members`` to a single - ``role``. Members can be user accounts, service - accounts, Google groups, and domains (such as G Suite). - A ``role`` is a named list of permissions (defined by - IAM or configured by users). A ``binding`` can - optionally specify a ``condition``, which is a logic - expression that further constrains the role binding - based on attributes about the request and/or target - resource. - **JSON Example** - :: - { - "bindings": [ - { - "role": "roles/resourcemanager.organizationAdmin", - "members": [ - "user:mike@example.com", - "group:admins@example.com", - "domain:google.com", - "serviceAccount:my-project-id@appspot.gserviceaccount.com" - ] - }, - { - "role": "roles/resourcemanager.organizationViewer", - "members": ["user:eve@example.com"], - "condition": { - "title": "expirable access", - "description": "Does not grant access after Sep 2020", - "expression": "request.time < - timestamp('2020-10-01T00:00:00.000Z')", - } - } - ] - } - **YAML Example** - :: - bindings: - - members: - - user:mike@example.com - - group:admins@example.com - - domain:google.com - - serviceAccount:my-project-id@appspot.gserviceaccount.com - role: roles/resourcemanager.organizationAdmin - - members: - - user:eve@example.com - role: roles/resourcemanager.organizationViewer - condition: - title: expirable access - description: Does not grant access after Sep 2020 - expression: request.time < timestamp('2020-10-01T00:00:00.000Z') - For a description of IAM and its features, see the `IAM - developer's - guide `__. - """ - # Create or coerce a protobuf request object. - - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = iam_policy.GetIamPolicyRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.get_iam_policy, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("resource", request.resource),)), - ) - - # Send the request. - response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - async def test_iam_permissions( - self, - request: iam_policy.TestIamPermissionsRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> iam_policy.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`): - The request object. Request message for - `TestIamPermissions` method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.iam_policy.TestIamPermissionsResponse: - Response message for ``TestIamPermissions`` method. - """ - # Create or coerce a protobuf request object. - - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = iam_policy.TestIamPermissionsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.test_iam_permissions, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("resource", request.resource),)), - ) - - # Send the request. - response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - 'google-pubsub', - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - 'SubscriberAsyncClient', -) diff --git a/owl-bot-staging/v1/google/pubsub_v1/services/subscriber/client.py b/owl-bot-staging/v1/google/pubsub_v1/services/subscriber/client.py deleted file mode 100644 index be3d1d5f1..000000000 --- a/owl-bot-staging/v1/google/pubsub_v1/services/subscriber/client.py +++ /dev/null @@ -1,2032 +0,0 @@ -# -*- coding: utf-8 -*- - -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -from collections import OrderedDict -from distutils import util -import os -import re -from typing import Callable, Dict, Optional, Iterable, Iterator, Sequence, Tuple, Type, Union -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 gapic_v1 # type: ignore -from google.api_core import retry as retries # type: ignore -from google.auth import 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.pubsub_v1.services.subscriber import pagers -from google.pubsub_v1.types import pubsub - -from .transports.base import SubscriberTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import SubscriberGrpcTransport -from .transports.grpc_asyncio import SubscriberGrpcAsyncIOTransport - - -class SubscriberClientMeta(type): - """Metaclass for the Subscriber client. - - This provides class-level methods for building and retrieving - support objects (e.g. transport) without polluting the client instance - objects. - """ - _transport_registry = OrderedDict() # type: Dict[str, Type[SubscriberTransport]] - _transport_registry['grpc'] = SubscriberGrpcTransport - _transport_registry['grpc_asyncio'] = SubscriberGrpcAsyncIOTransport - - def get_transport_class(cls, - label: str = None, - ) -> Type[SubscriberTransport]: - """Return an appropriate transport class. - - Args: - label: The name of the desired transport. If none is - provided, then the first transport in the registry is used. - - Returns: - The transport class to use. - """ - # If a specific transport is requested, return that one. - if label: - return cls._transport_registry[label] - - # No transport is requested; return the default (that is, the first one - # in the dictionary). - return next(iter(cls._transport_registry.values())) - - -class SubscriberClient(metaclass=SubscriberClientMeta): - """The service that an application uses to manipulate subscriptions and - to consume messages from a subscription via the ``Pull`` method or - by establishing a bi-directional stream using the ``StreamingPull`` - method. - """ - - @staticmethod - def _get_default_mtls_endpoint(api_endpoint): - """Convert api endpoint to mTLS endpoint. - Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to - "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. - Args: - api_endpoint (Optional[str]): the api endpoint to convert. - Returns: - str: converted mTLS api endpoint. - """ - if not api_endpoint: - return api_endpoint - - mtls_endpoint_re = re.compile( - r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" - ) - - m = mtls_endpoint_re.match(api_endpoint) - name, mtls, sandbox, googledomain = m.groups() - if mtls or not googledomain: - return api_endpoint - - if sandbox: - return api_endpoint.replace( - "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" - ) - - return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") - - DEFAULT_ENDPOINT = 'pubsub.googleapis.com' - DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore - DEFAULT_ENDPOINT - ) - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials info. - - Args: - info (dict): The service account private key info. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - SubscriberClient: The constructed client. - """ - credentials = service_account.Credentials.from_service_account_info(info) - kwargs["credentials"] = credentials - return cls(*args, **kwargs) - - @classmethod - def from_service_account_file(cls, filename: str, *args, **kwargs): - """Creates an instance of this client using the provided credentials - file. - - Args: - filename (str): The path to the service account private key json - file. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - SubscriberClient: The constructed client. - """ - credentials = service_account.Credentials.from_service_account_file( - filename) - kwargs['credentials'] = credentials - return cls(*args, **kwargs) - - from_service_account_json = from_service_account_file - - @property - def transport(self) -> SubscriberTransport: - """Return the transport used by the client instance. - - Returns: - SubscriberTransport: The transport used by the client instance. - """ - return self._transport - - @staticmethod - def snapshot_path(project: str,snapshot: str,) -> str: - """Return 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.""" - 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.""" - 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.""" - m = re.match(r"^projects/(?P.+?)/subscriptions/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def topic_path(project: str,topic: str,) -> str: - """Return 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.""" - 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.""" - return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - - @staticmethod - def parse_common_billing_account_path(path: str) -> Dict[str,str]: - """Parse a billing_account path into its component segments.""" - m = re.match(r"^billingAccounts/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_folder_path(folder: str, ) -> str: - """Return a fully-qualified folder string.""" - return "folders/{folder}".format(folder=folder, ) - - @staticmethod - def parse_common_folder_path(path: str) -> Dict[str,str]: - """Parse a folder path into its component segments.""" - m = re.match(r"^folders/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_organization_path(organization: str, ) -> str: - """Return a fully-qualified organization string.""" - return "organizations/{organization}".format(organization=organization, ) - - @staticmethod - def parse_common_organization_path(path: str) -> Dict[str,str]: - """Parse a organization path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_project_path(project: str, ) -> str: - """Return a fully-qualified project string.""" - return "projects/{project}".format(project=project, ) - - @staticmethod - def parse_common_project_path(path: str) -> Dict[str,str]: - """Parse a project path into its component segments.""" - m = re.match(r"^projects/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_location_path(project: str, location: str, ) -> str: - """Return a fully-qualified location string.""" - return "projects/{project}/locations/{location}".format(project=project, location=location, ) - - @staticmethod - def parse_common_location_path(path: str) -> Dict[str,str]: - """Parse a location path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) - return m.groupdict() if m else {} - - def __init__(self, *, - credentials: Optional[credentials.Credentials] = None, - transport: Union[str, SubscriberTransport, None] = None, - client_options: Optional[client_options_lib.ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiate the subscriber client. - - Args: - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - transport (Union[str, SubscriberTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. It won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - """ - if isinstance(client_options, dict): - client_options = client_options_lib.from_dict(client_options) - if client_options is None: - client_options = client_options_lib.ClientOptions() - - # Create SSL credentials for mutual TLS if needed. - use_client_cert = bool(util.strtobool(os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false"))) - - client_cert_source_func = None - is_mtls = False - if use_client_cert: - if client_options.client_cert_source: - is_mtls = True - 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 - - # Figure out which api endpoint to use. - if client_options.api_endpoint is not None: - api_endpoint = client_options.api_endpoint - else: - use_mtls_env = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_mtls_env == "never": - api_endpoint = self.DEFAULT_ENDPOINT - 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 - else: - raise MutualTLSChannelError( - "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted values: never, auto, always" - ) - - # Save or instantiate the transport. - # Ordinarily, we provide the transport, but allowing a custom transport - # instance provides an extensibility point for unusual situations. - if isinstance(transport, SubscriberTransport): - # transport is a SubscriberTransport instance. - if credentials or client_options.credentials_file: - raise ValueError('When providing a transport instance, ' - 'provide its credentials directly.') - if client_options.scopes: - raise ValueError( - "When providing a transport instance, " - "provide its scopes directly." - ) - self._transport = transport - else: - Transport = type(self).get_transport_class(transport) - self._transport = Transport( - credentials=credentials, - credentials_file=client_options.credentials_file, - host=api_endpoint, - scopes=client_options.scopes, - client_cert_source_for_mtls=client_cert_source_func, - quota_project_id=client_options.quota_project_id, - client_info=client_info, - ) - - def create_subscription(self, - request: pubsub.Subscription = None, - *, - name: str = None, - topic: str = None, - push_config: pubsub.PushConfig = None, - ack_deadline_seconds: int = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pubsub.Subscription: - r"""Creates a subscription to a given topic. See the [resource name - rules] - (https://cloud.google.com/pubsub/docs/admin#resource_names). If - the subscription already exists, returns ``ALREADY_EXISTS``. If - the corresponding topic doesn't exist, returns ``NOT_FOUND``. - - If the name is not provided in the request, the server will - assign a random name for this subscription on the same project - as the topic, conforming to the [resource name format] - (https://cloud.google.com/pubsub/docs/admin#resource_names). The - generated name is populated in the returned Subscription object. - Note that for REST API requests, you must specify a name in the - request. - - Args: - request (google.pubsub_v1.types.Subscription): - The request object. A subscription resource. - name (str): - Required. The name of the subscription. It must have the - format - ``"projects/{project}/subscriptions/{subscription}"``. - ``{subscription}`` must start with a letter, and contain - only letters (``[A-Za-z]``), numbers (``[0-9]``), dashes - (``-``), underscores (``_``), periods (``.``), tildes - (``~``), plus (``+``) or percent signs (``%``). It must - be between 3 and 255 characters in length, and it must - not start with ``"goog"``. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - topic (str): - Required. The name of the topic from which this - subscription is receiving messages. Format is - ``projects/{project}/topics/{topic}``. The value of this - field will be ``_deleted-topic_`` if the topic has been - deleted. - - This corresponds to the ``topic`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - push_config (google.pubsub_v1.types.PushConfig): - If push delivery is used with this subscription, this - field is used to configure it. An empty ``pushConfig`` - signifies that the subscriber will pull and ack messages - using API methods. - - This corresponds to the ``push_config`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - ack_deadline_seconds (int): - The approximate amount of time (on a best-effort basis) - Pub/Sub waits for the subscriber to acknowledge receipt - before resending the message. In the interval after the - message is delivered and before it is acknowledged, it - is considered to be outstanding. During that time - period, the message will not be redelivered (on a - best-effort basis). - - For pull subscriptions, this value is used as the - initial value for the ack deadline. To override this - value for a given message, call ``ModifyAckDeadline`` - with the corresponding ``ack_id`` if using non-streaming - pull or send the ``ack_id`` in a - ``StreamingModifyAckDeadlineRequest`` if using streaming - pull. The minimum custom deadline you can specify is 10 - seconds. The maximum custom deadline you can specify is - 600 seconds (10 minutes). If this parameter is 0, a - default value of 10 seconds is used. - - For push delivery, this value is also used to set the - request timeout for the call to the push endpoint. - - If the subscriber never acknowledges the message, the - Pub/Sub system will eventually redeliver the message. - - This corresponds to the ``ack_deadline_seconds`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.pubsub_v1.types.Subscription: - A subscription resource. - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name, topic, push_config, ack_deadline_seconds]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a pubsub.Subscription. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, pubsub.Subscription): - request = pubsub.Subscription(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - - if name is not None: - request.name = name - if topic is not None: - request.topic = topic - if push_config is not None: - request.push_config = push_config - if ack_deadline_seconds is not None: - request.ack_deadline_seconds = ack_deadline_seconds - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_subscription] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('name', request.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def get_subscription(self, - request: pubsub.GetSubscriptionRequest = None, - *, - subscription: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pubsub.Subscription: - r"""Gets the configuration details of a subscription. - - Args: - request (google.pubsub_v1.types.GetSubscriptionRequest): - The request object. Request for the GetSubscription - method. - subscription (str): - Required. The name of the subscription to get. Format is - ``projects/{project}/subscriptions/{sub}``. - - This corresponds to the ``subscription`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.pubsub_v1.types.Subscription: - A subscription resource. - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([subscription]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a pubsub.GetSubscriptionRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, pubsub.GetSubscriptionRequest): - request = pubsub.GetSubscriptionRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - - if subscription is not None: - request.subscription = subscription - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.get_subscription] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('subscription', request.subscription), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def update_subscription(self, - request: pubsub.UpdateSubscriptionRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pubsub.Subscription: - r"""Updates an existing subscription. Note that certain - properties of a subscription, such as its topic, are not - modifiable. - - Args: - 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. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.pubsub_v1.types.Subscription: - A subscription resource. - """ - # Create or coerce a protobuf request object. - - # Minor optimization to avoid making a copy if the user passes - # in a pubsub.UpdateSubscriptionRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, pubsub.UpdateSubscriptionRequest): - request = pubsub.UpdateSubscriptionRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.update_subscription] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('subscription.name', request.subscription.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def list_subscriptions(self, - request: pubsub.ListSubscriptionsRequest = None, - *, - project: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListSubscriptionsPager: - r"""Lists matching subscriptions. - - Args: - request (google.pubsub_v1.types.ListSubscriptionsRequest): - The request object. Request for the `ListSubscriptions` - method. - project (str): - Required. The name of the project in which to list - subscriptions. Format is ``projects/{project-id}``. - - This corresponds to the ``project`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.pubsub_v1.services.subscriber.pagers.ListSubscriptionsPager: - Response for the ListSubscriptions method. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([project]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a pubsub.ListSubscriptionsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, pubsub.ListSubscriptionsRequest): - request = pubsub.ListSubscriptionsRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - - if project is not None: - request.project = project - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.list_subscriptions] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('project', request.project), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__iter__` convenience method. - response = pagers.ListSubscriptionsPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - def delete_subscription(self, - request: pubsub.DeleteSubscriptionRequest = None, - *, - subscription: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes an existing subscription. All messages retained in the - subscription are immediately dropped. Calls to ``Pull`` after - deletion will return ``NOT_FOUND``. After a subscription is - deleted, a new one may be created with the same name, but the - new one has no association with the old subscription or its - topic unless the same topic is specified. - - Args: - request (google.pubsub_v1.types.DeleteSubscriptionRequest): - The request object. Request for the DeleteSubscription - method. - subscription (str): - Required. The subscription to delete. Format is - ``projects/{project}/subscriptions/{sub}``. - - This corresponds to the ``subscription`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([subscription]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a pubsub.DeleteSubscriptionRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, pubsub.DeleteSubscriptionRequest): - request = pubsub.DeleteSubscriptionRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - - if subscription is not None: - request.subscription = subscription - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.delete_subscription] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('subscription', request.subscription), - )), - ) - - # Send the request. - rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - def modify_ack_deadline(self, - request: pubsub.ModifyAckDeadlineRequest = None, - *, - subscription: str = None, - ack_ids: Sequence[str] = None, - ack_deadline_seconds: int = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Modifies the ack deadline for a specific message. This method is - useful to indicate that more time is needed to process a message - by the subscriber, or to make the message available for - redelivery if the processing was interrupted. Note that this - does not modify the subscription-level ``ackDeadlineSeconds`` - used for subsequent messages. - - Args: - request (google.pubsub_v1.types.ModifyAckDeadlineRequest): - The request object. Request for the ModifyAckDeadline - method. - subscription (str): - Required. The name of the subscription. Format is - ``projects/{project}/subscriptions/{sub}``. - - This corresponds to the ``subscription`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - ack_ids (Sequence[str]): - Required. List of acknowledgment IDs. - This corresponds to the ``ack_ids`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - ack_deadline_seconds (int): - Required. The new ack deadline with respect to the time - this request was sent to the Pub/Sub system. For - example, if the value is 10, the new ack deadline will - expire 10 seconds after the ``ModifyAckDeadline`` call - was made. Specifying zero might immediately make the - message available for delivery to another subscriber - client. This typically results in an increase in the - rate of message redeliveries (that is, duplicates). The - minimum deadline you can specify is 0 seconds. The - maximum deadline you can specify is 600 seconds (10 - minutes). - - This corresponds to the ``ack_deadline_seconds`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([subscription, ack_ids, ack_deadline_seconds]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a pubsub.ModifyAckDeadlineRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, pubsub.ModifyAckDeadlineRequest): - request = pubsub.ModifyAckDeadlineRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - - if subscription is not None: - request.subscription = subscription - if ack_ids is not None: - request.ack_ids = ack_ids - if ack_deadline_seconds is not None: - request.ack_deadline_seconds = ack_deadline_seconds - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.modify_ack_deadline] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('subscription', request.subscription), - )), - ) - - # Send the request. - rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - def acknowledge(self, - request: pubsub.AcknowledgeRequest = None, - *, - subscription: str = None, - ack_ids: Sequence[str] = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Acknowledges the messages associated with the ``ack_ids`` in the - ``AcknowledgeRequest``. The Pub/Sub system can remove the - relevant messages from the subscription. - - Acknowledging a message whose ack deadline has expired may - succeed, but such a message may be redelivered later. - Acknowledging a message more than once will not result in an - error. - - Args: - request (google.pubsub_v1.types.AcknowledgeRequest): - The request object. Request for the Acknowledge method. - subscription (str): - Required. The subscription whose message is being - acknowledged. Format is - ``projects/{project}/subscriptions/{sub}``. - - This corresponds to the ``subscription`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - ack_ids (Sequence[str]): - Required. The acknowledgment ID for the messages being - acknowledged that was returned by the Pub/Sub system in - the ``Pull`` response. Must not be empty. - - This corresponds to the ``ack_ids`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([subscription, ack_ids]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a pubsub.AcknowledgeRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, pubsub.AcknowledgeRequest): - request = pubsub.AcknowledgeRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - - if subscription is not None: - request.subscription = subscription - if ack_ids is not None: - request.ack_ids = ack_ids - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.acknowledge] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('subscription', request.subscription), - )), - ) - - # Send the request. - rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - def pull(self, - request: pubsub.PullRequest = None, - *, - subscription: str = None, - return_immediately: bool = None, - max_messages: int = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pubsub.PullResponse: - r"""Pulls messages from the server. The server may return - ``UNAVAILABLE`` if there are too many concurrent pull requests - pending for the given subscription. - - Args: - request (google.pubsub_v1.types.PullRequest): - The request object. Request for the `Pull` method. - subscription (str): - Required. The subscription from which messages should be - pulled. Format is - ``projects/{project}/subscriptions/{sub}``. - - This corresponds to the ``subscription`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - return_immediately (bool): - Optional. If this field set to true, the system will - respond immediately even if it there are no messages - available to return in the ``Pull`` response. Otherwise, - the system may wait (for a bounded amount of time) until - at least one message is available, rather than returning - no messages. Warning: setting this field to ``true`` is - discouraged because it adversely impacts the performance - of ``Pull`` operations. We recommend that users do not - set this field. - - This corresponds to the ``return_immediately`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - max_messages (int): - Required. The maximum number of - messages to return for this request. - Must be a positive integer. The Pub/Sub - system may return fewer than the number - specified. - - This corresponds to the ``max_messages`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.pubsub_v1.types.PullResponse: - Response for the Pull method. - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([subscription, return_immediately, max_messages]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a pubsub.PullRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, pubsub.PullRequest): - request = pubsub.PullRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - - if subscription is not None: - request.subscription = subscription - if return_immediately is not None: - request.return_immediately = return_immediately - if max_messages is not None: - request.max_messages = max_messages - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.pull] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('subscription', request.subscription), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def streaming_pull(self, - requests: Iterator[pubsub.StreamingPullRequest] = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> Iterable[pubsub.StreamingPullResponse]: - r"""Establishes a stream with the server, which sends messages down - to the client. The client streams acknowledgements and ack - deadline modifications back to the server. The server will close - the stream and return the status on any error. The server may - close the stream with status ``UNAVAILABLE`` to reassign - server-side resources, in which case, the client should - re-establish the stream. Flow control can be achieved by - configuring the underlying RPC channel. - - Args: - requests (Iterator[google.pubsub_v1.types.StreamingPullRequest]): - The request object iterator. Request for the `StreamingPull` - streaming RPC method. This request is used to establish - the initial stream as well as to stream acknowledgements - and ack deadline modifications from the client to the - server. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - Iterable[google.pubsub_v1.types.StreamingPullResponse]: - Response for the StreamingPull method. This response is used to stream - messages from the server to the client. - - """ - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.streaming_pull] - - # Send the request. - response = rpc( - requests, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def modify_push_config(self, - request: pubsub.ModifyPushConfigRequest = None, - *, - subscription: str = None, - push_config: pubsub.PushConfig = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Modifies the ``PushConfig`` for a specified subscription. - - This may be used to change a push subscription to a pull one - (signified by an empty ``PushConfig``) or vice versa, or change - the endpoint URL and other attributes of a push subscription. - Messages will accumulate for delivery continuously through the - call regardless of changes to the ``PushConfig``. - - Args: - request (google.pubsub_v1.types.ModifyPushConfigRequest): - The request object. Request for the ModifyPushConfig - method. - subscription (str): - Required. The name of the subscription. Format is - ``projects/{project}/subscriptions/{sub}``. - - This corresponds to the ``subscription`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - push_config (google.pubsub_v1.types.PushConfig): - Required. The push configuration for future deliveries. - - An empty ``pushConfig`` indicates that the Pub/Sub - system should stop pushing messages from the given - subscription and allow messages to be pulled and - acknowledged - effectively pausing the subscription if - ``Pull`` or ``StreamingPull`` is not called. - - This corresponds to the ``push_config`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([subscription, push_config]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a pubsub.ModifyPushConfigRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, pubsub.ModifyPushConfigRequest): - request = pubsub.ModifyPushConfigRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - - if subscription is not None: - request.subscription = subscription - if push_config is not None: - request.push_config = push_config - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.modify_push_config] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('subscription', request.subscription), - )), - ) - - # Send the request. - rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - def get_snapshot(self, - request: pubsub.GetSnapshotRequest = None, - *, - snapshot: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pubsub.Snapshot: - r"""Gets the configuration details of a snapshot. - Snapshots are used in Seek operations, which allow you to manage - message acknowledgments in bulk. That is, you can set - the acknowledgment state of messages in an existing - subscription to the state captured by a snapshot. - - Args: - request (google.pubsub_v1.types.GetSnapshotRequest): - The request object. Request for the GetSnapshot method. - snapshot (str): - Required. The name of the snapshot to get. Format is - ``projects/{project}/snapshots/{snap}``. - - This corresponds to the ``snapshot`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.pubsub_v1.types.Snapshot: - A snapshot resource. Snapshots are used in - [Seek](https://cloud.google.com/pubsub/docs/replay-overview) - operations, which allow you to manage message - acknowledgments in bulk. That is, you can set the - acknowledgment state of messages in an existing - subscription to the state captured by a snapshot. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([snapshot]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a pubsub.GetSnapshotRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, pubsub.GetSnapshotRequest): - request = pubsub.GetSnapshotRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - - if snapshot is not None: - request.snapshot = snapshot - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.get_snapshot] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('snapshot', request.snapshot), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def list_snapshots(self, - request: pubsub.ListSnapshotsRequest = None, - *, - project: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListSnapshotsPager: - r"""Lists the existing snapshots. Snapshots are used in - `Seek `__ - operations, which allow you to manage message acknowledgments in - bulk. That is, you can set the acknowledgment state of messages - in an existing subscription to the state captured by a snapshot. - - Args: - request (google.pubsub_v1.types.ListSnapshotsRequest): - The request object. Request for the `ListSnapshots` - method. - project (str): - Required. The name of the project in which to list - snapshots. Format is ``projects/{project-id}``. - - This corresponds to the ``project`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.pubsub_v1.services.subscriber.pagers.ListSnapshotsPager: - Response for the ListSnapshots method. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([project]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a pubsub.ListSnapshotsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, pubsub.ListSnapshotsRequest): - request = pubsub.ListSnapshotsRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - - if project is not None: - request.project = project - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.list_snapshots] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('project', request.project), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__iter__` convenience method. - response = pagers.ListSnapshotsPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - def create_snapshot(self, - request: pubsub.CreateSnapshotRequest = None, - *, - name: str = None, - subscription: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pubsub.Snapshot: - r"""Creates a snapshot from the requested subscription. Snapshots - are used in - `Seek `__ - operations, which allow you to manage message acknowledgments in - bulk. That is, you can set the acknowledgment state of messages - in an existing subscription to the state captured by a snapshot. - If the snapshot already exists, returns ``ALREADY_EXISTS``. If - the requested subscription doesn't exist, returns ``NOT_FOUND``. - If the backlog in the subscription is too old -- and the - resulting snapshot would expire in less than 1 hour -- then - ``FAILED_PRECONDITION`` is returned. See also the - ``Snapshot.expire_time`` field. If the name is not provided in - the request, the server will assign a random name for this - snapshot on the same project as the subscription, conforming to - the [resource name format] - (https://cloud.google.com/pubsub/docs/admin#resource_names). The - generated name is populated in the returned Snapshot object. - Note that for REST API requests, you must specify a name in the - request. - - Args: - request (google.pubsub_v1.types.CreateSnapshotRequest): - The request object. Request for the `CreateSnapshot` - method. - name (str): - Required. User-provided name for this snapshot. If the - name is not provided in the request, the server will - assign a random name for this snapshot on the same - project as the subscription. Note that for REST API - requests, you must specify a name. See the resource name - rules. Format is - ``projects/{project}/snapshots/{snap}``. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - subscription (str): - Required. The subscription whose backlog the snapshot - retains. Specifically, the created snapshot is - guaranteed to retain: (a) The existing backlog on the - subscription. More precisely, this is defined as the - messages in the subscription's backlog that are - unacknowledged upon the successful completion of the - ``CreateSnapshot`` request; as well as: (b) Any messages - published to the subscription's topic following the - successful completion of the CreateSnapshot request. - Format is ``projects/{project}/subscriptions/{sub}``. - - This corresponds to the ``subscription`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.pubsub_v1.types.Snapshot: - A snapshot resource. Snapshots are used in - [Seek](https://cloud.google.com/pubsub/docs/replay-overview) - operations, which allow you to manage message - acknowledgments in bulk. That is, you can set the - acknowledgment state of messages in an existing - subscription to the state captured by a snapshot. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name, subscription]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a pubsub.CreateSnapshotRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, pubsub.CreateSnapshotRequest): - request = pubsub.CreateSnapshotRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - - if name is not None: - request.name = name - if subscription is not None: - request.subscription = subscription - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_snapshot] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('name', request.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def update_snapshot(self, - request: pubsub.UpdateSnapshotRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pubsub.Snapshot: - r"""Updates an existing snapshot. Snapshots are used in - Seek operations, which allow - you to manage message acknowledgments in bulk. That is, - you can set the acknowledgment state of messages in an - existing subscription to the state captured by a - snapshot. - - Args: - 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. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.pubsub_v1.types.Snapshot: - A snapshot resource. Snapshots are used in - [Seek](https://cloud.google.com/pubsub/docs/replay-overview) - operations, which allow you to manage message - acknowledgments in bulk. That is, you can set the - acknowledgment state of messages in an existing - subscription to the state captured by a snapshot. - - """ - # Create or coerce a protobuf request object. - - # Minor optimization to avoid making a copy if the user passes - # in a pubsub.UpdateSnapshotRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, pubsub.UpdateSnapshotRequest): - request = pubsub.UpdateSnapshotRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.update_snapshot] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('snapshot.name', request.snapshot.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def delete_snapshot(self, - request: pubsub.DeleteSnapshotRequest = None, - *, - snapshot: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Removes an existing snapshot. Snapshots are used in [Seek] - (https://cloud.google.com/pubsub/docs/replay-overview) - operations, which allow you to manage message acknowledgments in - bulk. That is, you can set the acknowledgment state of messages - in an existing subscription to the state captured by a snapshot. - When the snapshot is deleted, all messages retained in the - snapshot are immediately dropped. After a snapshot is deleted, a - new one may be created with the same name, but the new one has - no association with the old snapshot or its subscription, unless - the same subscription is specified. - - Args: - request (google.pubsub_v1.types.DeleteSnapshotRequest): - The request object. Request for the `DeleteSnapshot` - method. - snapshot (str): - Required. The name of the snapshot to delete. Format is - ``projects/{project}/snapshots/{snap}``. - - This corresponds to the ``snapshot`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([snapshot]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a pubsub.DeleteSnapshotRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, pubsub.DeleteSnapshotRequest): - request = pubsub.DeleteSnapshotRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - - if snapshot is not None: - request.snapshot = snapshot - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.delete_snapshot] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('snapshot', request.snapshot), - )), - ) - - # Send the request. - rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - def seek(self, - request: pubsub.SeekRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pubsub.SeekResponse: - r"""Seeks an existing subscription to a point in time or to a given - snapshot, whichever is provided in the request. Snapshots are - used in [Seek] - (https://cloud.google.com/pubsub/docs/replay-overview) - operations, which allow you to manage message acknowledgments in - bulk. That is, you can set the acknowledgment state of messages - in an existing subscription to the state captured by a snapshot. - Note that both the subscription and the snapshot must be on the - same topic. - - 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. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.pubsub_v1.types.SeekResponse: - Response for the Seek method (this response is empty). - """ - # Create or coerce a protobuf request object. - - # Minor optimization to avoid making a copy if the user passes - # in a pubsub.SeekRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, pubsub.SeekRequest): - request = pubsub.SeekRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.seek] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('subscription', request.subscription), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def set_iam_policy( - self, - request: iam_policy.SetIamPolicyRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> policy.Policy: - r"""Sets the IAM access control policy on the specified - function. Replaces any existing policy. - Args: - request (:class:`~.iam_policy.SetIamPolicyRequest`): - The request object. Request message for `SetIamPolicy` - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.policy.Policy: - Defines an Identity and Access Management (IAM) policy. - It is used to specify access control policies for Cloud - Platform resources. - A ``Policy`` is a collection of ``bindings``. A - ``binding`` binds one or more ``members`` to a single - ``role``. Members can be user accounts, service - accounts, Google groups, and domains (such as G Suite). - A ``role`` is a named list of permissions (defined by - IAM or configured by users). A ``binding`` can - optionally specify a ``condition``, which is a logic - expression that further constrains the role binding - based on attributes about the request and/or target - resource. - **JSON Example** - :: - { - "bindings": [ - { - "role": "roles/resourcemanager.organizationAdmin", - "members": [ - "user:mike@example.com", - "group:admins@example.com", - "domain:google.com", - "serviceAccount:my-project-id@appspot.gserviceaccount.com" - ] - }, - { - "role": "roles/resourcemanager.organizationViewer", - "members": ["user:eve@example.com"], - "condition": { - "title": "expirable access", - "description": "Does not grant access after Sep 2020", - "expression": "request.time < - timestamp('2020-10-01T00:00:00.000Z')", - } - } - ] - } - **YAML Example** - :: - bindings: - - members: - - user:mike@example.com - - group:admins@example.com - - domain:google.com - - serviceAccount:my-project-id@appspot.gserviceaccount.com - role: roles/resourcemanager.organizationAdmin - - members: - - user:eve@example.com - role: roles/resourcemanager.organizationViewer - condition: - title: expirable access - description: Does not grant access after Sep 2020 - expression: request.time < timestamp('2020-10-01T00:00:00.000Z') - For a description of IAM and its features, see the `IAM - developer's - guide `__. - """ - # Create or coerce a protobuf request object. - - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = iam_policy.SetIamPolicyRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.set_iam_policy, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("resource", request.resource),)), - ) - - # Send the request. - response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - def get_iam_policy( - self, - request: iam_policy.GetIamPolicyRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> policy.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`): - The request object. Request message for `GetIamPolicy` - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.policy.Policy: - Defines an Identity and Access Management (IAM) policy. - It is used to specify access control policies for Cloud - Platform resources. - A ``Policy`` is a collection of ``bindings``. A - ``binding`` binds one or more ``members`` to a single - ``role``. Members can be user accounts, service - accounts, Google groups, and domains (such as G Suite). - A ``role`` is a named list of permissions (defined by - IAM or configured by users). A ``binding`` can - optionally specify a ``condition``, which is a logic - expression that further constrains the role binding - based on attributes about the request and/or target - resource. - **JSON Example** - :: - { - "bindings": [ - { - "role": "roles/resourcemanager.organizationAdmin", - "members": [ - "user:mike@example.com", - "group:admins@example.com", - "domain:google.com", - "serviceAccount:my-project-id@appspot.gserviceaccount.com" - ] - }, - { - "role": "roles/resourcemanager.organizationViewer", - "members": ["user:eve@example.com"], - "condition": { - "title": "expirable access", - "description": "Does not grant access after Sep 2020", - "expression": "request.time < - timestamp('2020-10-01T00:00:00.000Z')", - } - } - ] - } - **YAML Example** - :: - bindings: - - members: - - user:mike@example.com - - group:admins@example.com - - domain:google.com - - serviceAccount:my-project-id@appspot.gserviceaccount.com - role: roles/resourcemanager.organizationAdmin - - members: - - user:eve@example.com - role: roles/resourcemanager.organizationViewer - condition: - title: expirable access - description: Does not grant access after Sep 2020 - expression: request.time < timestamp('2020-10-01T00:00:00.000Z') - For a description of IAM and its features, see the `IAM - developer's - guide `__. - """ - # Create or coerce a protobuf request object. - - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = iam_policy.GetIamPolicyRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.get_iam_policy, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("resource", request.resource),)), - ) - - # Send the request. - response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - def test_iam_permissions( - self, - request: iam_policy.TestIamPermissionsRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> iam_policy.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`): - The request object. Request message for - `TestIamPermissions` method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.iam_policy.TestIamPermissionsResponse: - Response message for ``TestIamPermissions`` method. - """ - # Create or coerce a protobuf request object. - - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = iam_policy.TestIamPermissionsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.test_iam_permissions, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("resource", request.resource),)), - ) - - # Send the request. - response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - 'google-pubsub', - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - 'SubscriberClient', -) diff --git a/owl-bot-staging/v1/google/pubsub_v1/services/subscriber/pagers.py b/owl-bot-staging/v1/google/pubsub_v1/services/subscriber/pagers.py deleted file mode 100644 index feaf40169..000000000 --- a/owl-bot-staging/v1/google/pubsub_v1/services/subscriber/pagers.py +++ /dev/null @@ -1,264 +0,0 @@ -# -*- coding: utf-8 -*- - -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -from typing import Any, AsyncIterable, Awaitable, Callable, Iterable, Sequence, Tuple, Optional - -from google.pubsub_v1.types import pubsub - - -class ListSubscriptionsPager: - """A pager for iterating through ``list_subscriptions`` requests. - - This class thinly wraps an initial - :class:`google.pubsub_v1.types.ListSubscriptionsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``subscriptions`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListSubscriptions`` requests and continue to iterate - through the ``subscriptions`` field on the - corresponding responses. - - All the usual :class:`google.pubsub_v1.types.ListSubscriptionsResponse` - attributes are available on the pager. If multiple requests are made, only - the most recent response is retained, and thus used for attribute lookup. - """ - def __init__(self, - method: Callable[..., pubsub.ListSubscriptionsResponse], - request: pubsub.ListSubscriptionsRequest, - response: pubsub.ListSubscriptionsResponse, - *, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiate the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.pubsub_v1.types.ListSubscriptionsRequest): - The initial request object. - response (google.pubsub_v1.types.ListSubscriptionsResponse): - The initial response object. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = pubsub.ListSubscriptionsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterable[pubsub.ListSubscriptionsResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = self._method(self._request, metadata=self._metadata) - yield self._response - - def __iter__(self) -> Iterable[pubsub.Subscription]: - for page in self.pages: - yield from page.subscriptions - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListSubscriptionsAsyncPager: - """A pager for iterating through ``list_subscriptions`` requests. - - This class thinly wraps an initial - :class:`google.pubsub_v1.types.ListSubscriptionsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``subscriptions`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListSubscriptions`` requests and continue to iterate - through the ``subscriptions`` field on the - corresponding responses. - - All the usual :class:`google.pubsub_v1.types.ListSubscriptionsResponse` - attributes are available on the pager. If multiple requests are made, only - the most recent response is retained, and thus used for attribute lookup. - """ - def __init__(self, - method: Callable[..., Awaitable[pubsub.ListSubscriptionsResponse]], - request: pubsub.ListSubscriptionsRequest, - response: pubsub.ListSubscriptionsResponse, - *, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiate the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.pubsub_v1.types.ListSubscriptionsRequest): - The initial request object. - response (google.pubsub_v1.types.ListSubscriptionsResponse): - The initial response object. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = pubsub.ListSubscriptionsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterable[pubsub.ListSubscriptionsResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = await self._method(self._request, metadata=self._metadata) - yield self._response - - def __aiter__(self) -> AsyncIterable[pubsub.Subscription]: - async def async_generator(): - async for page in self.pages: - for response in page.subscriptions: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListSnapshotsPager: - """A pager for iterating through ``list_snapshots`` requests. - - This class thinly wraps an initial - :class:`google.pubsub_v1.types.ListSnapshotsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``snapshots`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListSnapshots`` requests and continue to iterate - through the ``snapshots`` field on the - corresponding responses. - - All the usual :class:`google.pubsub_v1.types.ListSnapshotsResponse` - attributes are available on the pager. If multiple requests are made, only - the most recent response is retained, and thus used for attribute lookup. - """ - def __init__(self, - method: Callable[..., pubsub.ListSnapshotsResponse], - request: pubsub.ListSnapshotsRequest, - response: pubsub.ListSnapshotsResponse, - *, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiate the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.pubsub_v1.types.ListSnapshotsRequest): - The initial request object. - response (google.pubsub_v1.types.ListSnapshotsResponse): - The initial response object. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = pubsub.ListSnapshotsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterable[pubsub.ListSnapshotsResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = self._method(self._request, metadata=self._metadata) - yield self._response - - def __iter__(self) -> Iterable[pubsub.Snapshot]: - for page in self.pages: - yield from page.snapshots - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListSnapshotsAsyncPager: - """A pager for iterating through ``list_snapshots`` requests. - - This class thinly wraps an initial - :class:`google.pubsub_v1.types.ListSnapshotsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``snapshots`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListSnapshots`` requests and continue to iterate - through the ``snapshots`` field on the - corresponding responses. - - All the usual :class:`google.pubsub_v1.types.ListSnapshotsResponse` - attributes are available on the pager. If multiple requests are made, only - the most recent response is retained, and thus used for attribute lookup. - """ - def __init__(self, - method: Callable[..., Awaitable[pubsub.ListSnapshotsResponse]], - request: pubsub.ListSnapshotsRequest, - response: pubsub.ListSnapshotsResponse, - *, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiate the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.pubsub_v1.types.ListSnapshotsRequest): - The initial request object. - response (google.pubsub_v1.types.ListSnapshotsResponse): - The initial response object. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = pubsub.ListSnapshotsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterable[pubsub.ListSnapshotsResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = await self._method(self._request, metadata=self._metadata) - yield self._response - - def __aiter__(self) -> AsyncIterable[pubsub.Snapshot]: - async def async_generator(): - async for page in self.pages: - for response in page.snapshots: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) diff --git a/owl-bot-staging/v1/google/pubsub_v1/services/subscriber/transports/__init__.py b/owl-bot-staging/v1/google/pubsub_v1/services/subscriber/transports/__init__.py deleted file mode 100644 index 45b2d01e4..000000000 --- a/owl-bot-staging/v1/google/pubsub_v1/services/subscriber/transports/__init__.py +++ /dev/null @@ -1,35 +0,0 @@ -# -*- coding: utf-8 -*- - -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -from collections import OrderedDict -from typing import Dict, Type - -from .base import SubscriberTransport -from .grpc import SubscriberGrpcTransport -from .grpc_asyncio import SubscriberGrpcAsyncIOTransport - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[SubscriberTransport]] -_transport_registry['grpc'] = SubscriberGrpcTransport -_transport_registry['grpc_asyncio'] = SubscriberGrpcAsyncIOTransport - -__all__ = ( - 'SubscriberTransport', - 'SubscriberGrpcTransport', - 'SubscriberGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v1/google/pubsub_v1/services/subscriber/transports/base.py b/owl-bot-staging/v1/google/pubsub_v1/services/subscriber/transports/base.py deleted file mode 100644 index ad9d8f37c..000000000 --- a/owl-bot-staging/v1/google/pubsub_v1/services/subscriber/transports/base.py +++ /dev/null @@ -1,533 +0,0 @@ -# -*- coding: utf-8 -*- - -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -import abc -import typing -import pkg_resources - -from google import auth # 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 -from google.auth import 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.pubsub_v1.types import pubsub - - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - 'google-pubsub', - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - -class SubscriberTransport(abc.ABC): - """Abstract transport class for Subscriber.""" - - AUTH_SCOPES = ( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/pubsub', - ) - - 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, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - **kwargs, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - 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): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - """ - # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ':' not in host: - host += ':443' - self._host = host - - # 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("'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 - ) - - elif credentials is None: - credentials, _ = auth.default(scopes=self._scopes, quota_project_id=quota_project_id) - - # Save the credentials. - self._credentials = credentials - - def _prep_wrapped_messages(self, client_info): - # Precompute the wrapped methods. - self._wrapped_methods = { - self.create_subscription: gapic_v1.method.wrap_method( - self.create_subscription, - default_retry=retries.Retry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - exceptions.Aborted, - exceptions.ServiceUnavailable, - exceptions.Unknown, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.get_subscription: gapic_v1.method.wrap_method( - self.get_subscription, - default_retry=retries.Retry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - exceptions.Aborted, - exceptions.ServiceUnavailable, - exceptions.Unknown, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.update_subscription: gapic_v1.method.wrap_method( - self.update_subscription, - default_retry=retries.Retry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.list_subscriptions: gapic_v1.method.wrap_method( - self.list_subscriptions, - default_retry=retries.Retry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - exceptions.Aborted, - exceptions.ServiceUnavailable, - exceptions.Unknown, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.delete_subscription: gapic_v1.method.wrap_method( - self.delete_subscription, - default_retry=retries.Retry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.modify_ack_deadline: gapic_v1.method.wrap_method( - self.modify_ack_deadline, - default_retry=retries.Retry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.acknowledge: gapic_v1.method.wrap_method( - self.acknowledge, - default_retry=retries.Retry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.pull: gapic_v1.method.wrap_method( - self.pull, - default_retry=retries.Retry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - exceptions.Aborted, - exceptions.ServiceUnavailable, - exceptions.Unknown, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.streaming_pull: gapic_v1.method.wrap_method( - self.streaming_pull, - default_retry=retries.Retry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - exceptions.Aborted, - exceptions.DeadlineExceeded, - exceptions.InternalServerError, - exceptions.ResourceExhausted, - exceptions.ServiceUnavailable, - ), - deadline=900.0, - ), - default_timeout=900.0, - client_info=client_info, - ), - self.modify_push_config: gapic_v1.method.wrap_method( - self.modify_push_config, - default_retry=retries.Retry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.get_snapshot: gapic_v1.method.wrap_method( - self.get_snapshot, - default_retry=retries.Retry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - exceptions.Aborted, - exceptions.ServiceUnavailable, - exceptions.Unknown, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.list_snapshots: gapic_v1.method.wrap_method( - self.list_snapshots, - default_retry=retries.Retry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - exceptions.Aborted, - exceptions.ServiceUnavailable, - exceptions.Unknown, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.create_snapshot: gapic_v1.method.wrap_method( - self.create_snapshot, - default_retry=retries.Retry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.update_snapshot: gapic_v1.method.wrap_method( - self.update_snapshot, - default_retry=retries.Retry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.delete_snapshot: gapic_v1.method.wrap_method( - self.delete_snapshot, - default_retry=retries.Retry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.seek: gapic_v1.method.wrap_method( - self.seek, - default_retry=retries.Retry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - exceptions.Aborted, - exceptions.ServiceUnavailable, - exceptions.Unknown, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - - } - - @property - def create_subscription(self) -> typing.Callable[ - [pubsub.Subscription], - typing.Union[ - pubsub.Subscription, - typing.Awaitable[pubsub.Subscription] - ]]: - raise NotImplementedError() - - @property - def get_subscription(self) -> typing.Callable[ - [pubsub.GetSubscriptionRequest], - typing.Union[ - pubsub.Subscription, - typing.Awaitable[pubsub.Subscription] - ]]: - raise NotImplementedError() - - @property - def update_subscription(self) -> typing.Callable[ - [pubsub.UpdateSubscriptionRequest], - typing.Union[ - pubsub.Subscription, - typing.Awaitable[pubsub.Subscription] - ]]: - raise NotImplementedError() - - @property - def list_subscriptions(self) -> typing.Callable[ - [pubsub.ListSubscriptionsRequest], - typing.Union[ - pubsub.ListSubscriptionsResponse, - typing.Awaitable[pubsub.ListSubscriptionsResponse] - ]]: - raise NotImplementedError() - - @property - def delete_subscription(self) -> typing.Callable[ - [pubsub.DeleteSubscriptionRequest], - typing.Union[ - empty.Empty, - typing.Awaitable[empty.Empty] - ]]: - raise NotImplementedError() - - @property - def modify_ack_deadline(self) -> typing.Callable[ - [pubsub.ModifyAckDeadlineRequest], - typing.Union[ - empty.Empty, - typing.Awaitable[empty.Empty] - ]]: - raise NotImplementedError() - - @property - def acknowledge(self) -> typing.Callable[ - [pubsub.AcknowledgeRequest], - typing.Union[ - empty.Empty, - typing.Awaitable[empty.Empty] - ]]: - raise NotImplementedError() - - @property - def pull(self) -> typing.Callable[ - [pubsub.PullRequest], - typing.Union[ - pubsub.PullResponse, - typing.Awaitable[pubsub.PullResponse] - ]]: - raise NotImplementedError() - - @property - def streaming_pull(self) -> typing.Callable[ - [pubsub.StreamingPullRequest], - typing.Union[ - pubsub.StreamingPullResponse, - typing.Awaitable[pubsub.StreamingPullResponse] - ]]: - raise NotImplementedError() - - @property - def modify_push_config(self) -> typing.Callable[ - [pubsub.ModifyPushConfigRequest], - typing.Union[ - empty.Empty, - typing.Awaitable[empty.Empty] - ]]: - raise NotImplementedError() - - @property - def get_snapshot(self) -> typing.Callable[ - [pubsub.GetSnapshotRequest], - typing.Union[ - pubsub.Snapshot, - typing.Awaitable[pubsub.Snapshot] - ]]: - raise NotImplementedError() - - @property - def list_snapshots(self) -> typing.Callable[ - [pubsub.ListSnapshotsRequest], - typing.Union[ - pubsub.ListSnapshotsResponse, - typing.Awaitable[pubsub.ListSnapshotsResponse] - ]]: - raise NotImplementedError() - - @property - def create_snapshot(self) -> typing.Callable[ - [pubsub.CreateSnapshotRequest], - typing.Union[ - pubsub.Snapshot, - typing.Awaitable[pubsub.Snapshot] - ]]: - raise NotImplementedError() - - @property - def update_snapshot(self) -> typing.Callable[ - [pubsub.UpdateSnapshotRequest], - typing.Union[ - pubsub.Snapshot, - typing.Awaitable[pubsub.Snapshot] - ]]: - raise NotImplementedError() - - @property - def delete_snapshot(self) -> typing.Callable[ - [pubsub.DeleteSnapshotRequest], - typing.Union[ - empty.Empty, - typing.Awaitable[empty.Empty] - ]]: - raise NotImplementedError() - - @property - def seek(self) -> typing.Callable[ - [pubsub.SeekRequest], - typing.Union[ - pubsub.SeekResponse, - typing.Awaitable[pubsub.SeekResponse] - ]]: - raise NotImplementedError() - - @property - def set_iam_policy( - self, - ) -> typing.Callable[ - [iam_policy.SetIamPolicyRequest], - typing.Union[policy.Policy, typing.Awaitable[policy.Policy]], - ]: - raise NotImplementedError() - - @property - def get_iam_policy( - self, - ) -> typing.Callable[ - [iam_policy.GetIamPolicyRequest], - typing.Union[policy.Policy, typing.Awaitable[policy.Policy]], - ]: - raise NotImplementedError() - - @property - def test_iam_permissions( - self, - ) -> typing.Callable[ - [iam_policy.TestIamPermissionsRequest], - typing.Union[ - iam_policy.TestIamPermissionsResponse, - typing.Awaitable[iam_policy.TestIamPermissionsResponse], - ], - ]: - raise NotImplementedError() - - -__all__ = ( - 'SubscriberTransport', -) diff --git a/owl-bot-staging/v1/google/pubsub_v1/services/subscriber/transports/grpc.py b/owl-bot-staging/v1/google/pubsub_v1/services/subscriber/transports/grpc.py deleted file mode 100644 index c91bd85ab..000000000 --- a/owl-bot-staging/v1/google/pubsub_v1/services/subscriber/transports/grpc.py +++ /dev/null @@ -1,820 +0,0 @@ -# -*- coding: utf-8 -*- - -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple - -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 -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.pubsub_v1.types import pubsub - -from .base import SubscriberTransport, DEFAULT_CLIENT_INFO - - -class SubscriberGrpcTransport(SubscriberTransport): - """gRPC backend transport for Subscriber. - - The service that an application uses to manipulate subscriptions and - to consume messages from a subscription via the ``Pull`` method or - by establishing a bi-directional stream using the ``StreamingPull`` - method. - - This class defines the same methods as the primary client, so the - primary client can load the underlying transport implementation - and call it. - - It sends protocol buffers over the wire using gRPC (which is built on - top of HTTP/2); the ``grpcio`` package must be installed. - """ - _stubs: Dict[str, Callable] - - def __init__(self, *, - host: str = 'pubsub.googleapis.com', - credentials: credentials.Credentials = None, - credentials_file: str = None, - scopes: Sequence[str] = None, - channel: grpc.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - channel (Optional[grpc.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or applicatin default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - credentials=self._credentials, - credentials_file=credentials_file, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @classmethod - def create_channel(cls, - host: str = 'pubsub.googleapis.com', - credentials: credentials.Credentials = None, - credentials_file: str = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> grpc.Channel: - """Create and return a gRPC channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - grpc.Channel: A gRPC channel object. - - Raises: - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - 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, - **kwargs - ) - - @property - def grpc_channel(self) -> grpc.Channel: - """Return the channel designed to connect to this service. - """ - return self._grpc_channel - - @property - def create_subscription(self) -> Callable[ - [pubsub.Subscription], - pubsub.Subscription]: - r"""Return a callable for the create subscription method over gRPC. - - Creates a subscription to a given topic. See the [resource name - rules] - (https://cloud.google.com/pubsub/docs/admin#resource_names). If - the subscription already exists, returns ``ALREADY_EXISTS``. If - the corresponding topic doesn't exist, returns ``NOT_FOUND``. - - If the name is not provided in the request, the server will - assign a random name for this subscription on the same project - as the topic, conforming to the [resource name format] - (https://cloud.google.com/pubsub/docs/admin#resource_names). The - generated name is populated in the returned Subscription object. - Note that for REST API requests, you must specify a name in the - request. - - Returns: - Callable[[~.Subscription], - ~.Subscription]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'create_subscription' not in self._stubs: - self._stubs['create_subscription'] = self.grpc_channel.unary_unary( - '/google.pubsub.v1.Subscriber/CreateSubscription', - request_serializer=pubsub.Subscription.serialize, - response_deserializer=pubsub.Subscription.deserialize, - ) - return self._stubs['create_subscription'] - - @property - def get_subscription(self) -> Callable[ - [pubsub.GetSubscriptionRequest], - pubsub.Subscription]: - r"""Return a callable for the get subscription method over gRPC. - - Gets the configuration details of a subscription. - - Returns: - Callable[[~.GetSubscriptionRequest], - ~.Subscription]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'get_subscription' not in self._stubs: - self._stubs['get_subscription'] = self.grpc_channel.unary_unary( - '/google.pubsub.v1.Subscriber/GetSubscription', - request_serializer=pubsub.GetSubscriptionRequest.serialize, - response_deserializer=pubsub.Subscription.deserialize, - ) - return self._stubs['get_subscription'] - - @property - def update_subscription(self) -> Callable[ - [pubsub.UpdateSubscriptionRequest], - pubsub.Subscription]: - r"""Return a callable for the update subscription method over gRPC. - - Updates an existing subscription. Note that certain - properties of a subscription, such as its topic, are not - modifiable. - - Returns: - Callable[[~.UpdateSubscriptionRequest], - ~.Subscription]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'update_subscription' not in self._stubs: - self._stubs['update_subscription'] = self.grpc_channel.unary_unary( - '/google.pubsub.v1.Subscriber/UpdateSubscription', - request_serializer=pubsub.UpdateSubscriptionRequest.serialize, - response_deserializer=pubsub.Subscription.deserialize, - ) - return self._stubs['update_subscription'] - - @property - def list_subscriptions(self) -> Callable[ - [pubsub.ListSubscriptionsRequest], - pubsub.ListSubscriptionsResponse]: - r"""Return a callable for the list subscriptions method over gRPC. - - Lists matching subscriptions. - - Returns: - Callable[[~.ListSubscriptionsRequest], - ~.ListSubscriptionsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'list_subscriptions' not in self._stubs: - self._stubs['list_subscriptions'] = self.grpc_channel.unary_unary( - '/google.pubsub.v1.Subscriber/ListSubscriptions', - request_serializer=pubsub.ListSubscriptionsRequest.serialize, - response_deserializer=pubsub.ListSubscriptionsResponse.deserialize, - ) - return self._stubs['list_subscriptions'] - - @property - def delete_subscription(self) -> Callable[ - [pubsub.DeleteSubscriptionRequest], - empty.Empty]: - r"""Return a callable for the delete subscription method over gRPC. - - Deletes an existing subscription. All messages retained in the - subscription are immediately dropped. Calls to ``Pull`` after - deletion will return ``NOT_FOUND``. After a subscription is - deleted, a new one may be created with the same name, but the - new one has no association with the old subscription or its - topic unless the same topic is specified. - - Returns: - Callable[[~.DeleteSubscriptionRequest], - ~.Empty]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'delete_subscription' not in self._stubs: - self._stubs['delete_subscription'] = self.grpc_channel.unary_unary( - '/google.pubsub.v1.Subscriber/DeleteSubscription', - request_serializer=pubsub.DeleteSubscriptionRequest.serialize, - response_deserializer=empty.Empty.FromString, - ) - return self._stubs['delete_subscription'] - - @property - def modify_ack_deadline(self) -> Callable[ - [pubsub.ModifyAckDeadlineRequest], - empty.Empty]: - r"""Return a callable for the modify ack deadline method over gRPC. - - Modifies the ack deadline for a specific message. This method is - useful to indicate that more time is needed to process a message - by the subscriber, or to make the message available for - redelivery if the processing was interrupted. Note that this - does not modify the subscription-level ``ackDeadlineSeconds`` - used for subsequent messages. - - Returns: - Callable[[~.ModifyAckDeadlineRequest], - ~.Empty]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'modify_ack_deadline' not in self._stubs: - self._stubs['modify_ack_deadline'] = self.grpc_channel.unary_unary( - '/google.pubsub.v1.Subscriber/ModifyAckDeadline', - request_serializer=pubsub.ModifyAckDeadlineRequest.serialize, - response_deserializer=empty.Empty.FromString, - ) - return self._stubs['modify_ack_deadline'] - - @property - def acknowledge(self) -> Callable[ - [pubsub.AcknowledgeRequest], - empty.Empty]: - r"""Return a callable for the acknowledge method over gRPC. - - Acknowledges the messages associated with the ``ack_ids`` in the - ``AcknowledgeRequest``. The Pub/Sub system can remove the - relevant messages from the subscription. - - Acknowledging a message whose ack deadline has expired may - succeed, but such a message may be redelivered later. - Acknowledging a message more than once will not result in an - error. - - Returns: - Callable[[~.AcknowledgeRequest], - ~.Empty]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'acknowledge' not in self._stubs: - self._stubs['acknowledge'] = self.grpc_channel.unary_unary( - '/google.pubsub.v1.Subscriber/Acknowledge', - request_serializer=pubsub.AcknowledgeRequest.serialize, - response_deserializer=empty.Empty.FromString, - ) - return self._stubs['acknowledge'] - - @property - def pull(self) -> Callable[ - [pubsub.PullRequest], - pubsub.PullResponse]: - r"""Return a callable for the pull method over gRPC. - - Pulls messages from the server. The server may return - ``UNAVAILABLE`` if there are too many concurrent pull requests - pending for the given subscription. - - Returns: - Callable[[~.PullRequest], - ~.PullResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'pull' not in self._stubs: - self._stubs['pull'] = self.grpc_channel.unary_unary( - '/google.pubsub.v1.Subscriber/Pull', - request_serializer=pubsub.PullRequest.serialize, - response_deserializer=pubsub.PullResponse.deserialize, - ) - return self._stubs['pull'] - - @property - def streaming_pull(self) -> Callable[ - [pubsub.StreamingPullRequest], - pubsub.StreamingPullResponse]: - r"""Return a callable for the streaming pull method over gRPC. - - Establishes a stream with the server, which sends messages down - to the client. The client streams acknowledgements and ack - deadline modifications back to the server. The server will close - the stream and return the status on any error. The server may - close the stream with status ``UNAVAILABLE`` to reassign - server-side resources, in which case, the client should - re-establish the stream. Flow control can be achieved by - configuring the underlying RPC channel. - - Returns: - Callable[[~.StreamingPullRequest], - ~.StreamingPullResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'streaming_pull' not in self._stubs: - self._stubs['streaming_pull'] = self.grpc_channel.stream_stream( - '/google.pubsub.v1.Subscriber/StreamingPull', - request_serializer=pubsub.StreamingPullRequest.serialize, - response_deserializer=pubsub.StreamingPullResponse.deserialize, - ) - return self._stubs['streaming_pull'] - - @property - def modify_push_config(self) -> Callable[ - [pubsub.ModifyPushConfigRequest], - empty.Empty]: - r"""Return a callable for the modify push config method over gRPC. - - Modifies the ``PushConfig`` for a specified subscription. - - This may be used to change a push subscription to a pull one - (signified by an empty ``PushConfig``) or vice versa, or change - the endpoint URL and other attributes of a push subscription. - Messages will accumulate for delivery continuously through the - call regardless of changes to the ``PushConfig``. - - Returns: - Callable[[~.ModifyPushConfigRequest], - ~.Empty]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'modify_push_config' not in self._stubs: - self._stubs['modify_push_config'] = self.grpc_channel.unary_unary( - '/google.pubsub.v1.Subscriber/ModifyPushConfig', - request_serializer=pubsub.ModifyPushConfigRequest.serialize, - response_deserializer=empty.Empty.FromString, - ) - return self._stubs['modify_push_config'] - - @property - def get_snapshot(self) -> Callable[ - [pubsub.GetSnapshotRequest], - pubsub.Snapshot]: - r"""Return a callable for the get snapshot method over gRPC. - - Gets the configuration details of a snapshot. - Snapshots are used in Seek operations, which allow you to manage - message acknowledgments in bulk. That is, you can set - the acknowledgment state of messages in an existing - subscription to the state captured by a snapshot. - - Returns: - Callable[[~.GetSnapshotRequest], - ~.Snapshot]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'get_snapshot' not in self._stubs: - self._stubs['get_snapshot'] = self.grpc_channel.unary_unary( - '/google.pubsub.v1.Subscriber/GetSnapshot', - request_serializer=pubsub.GetSnapshotRequest.serialize, - response_deserializer=pubsub.Snapshot.deserialize, - ) - return self._stubs['get_snapshot'] - - @property - def list_snapshots(self) -> Callable[ - [pubsub.ListSnapshotsRequest], - pubsub.ListSnapshotsResponse]: - r"""Return a callable for the list snapshots method over gRPC. - - Lists the existing snapshots. Snapshots are used in - `Seek `__ - operations, which allow you to manage message acknowledgments in - bulk. That is, you can set the acknowledgment state of messages - in an existing subscription to the state captured by a snapshot. - - Returns: - Callable[[~.ListSnapshotsRequest], - ~.ListSnapshotsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'list_snapshots' not in self._stubs: - self._stubs['list_snapshots'] = self.grpc_channel.unary_unary( - '/google.pubsub.v1.Subscriber/ListSnapshots', - request_serializer=pubsub.ListSnapshotsRequest.serialize, - response_deserializer=pubsub.ListSnapshotsResponse.deserialize, - ) - return self._stubs['list_snapshots'] - - @property - def create_snapshot(self) -> Callable[ - [pubsub.CreateSnapshotRequest], - pubsub.Snapshot]: - r"""Return a callable for the create snapshot method over gRPC. - - Creates a snapshot from the requested subscription. Snapshots - are used in - `Seek `__ - operations, which allow you to manage message acknowledgments in - bulk. That is, you can set the acknowledgment state of messages - in an existing subscription to the state captured by a snapshot. - If the snapshot already exists, returns ``ALREADY_EXISTS``. If - the requested subscription doesn't exist, returns ``NOT_FOUND``. - If the backlog in the subscription is too old -- and the - resulting snapshot would expire in less than 1 hour -- then - ``FAILED_PRECONDITION`` is returned. See also the - ``Snapshot.expire_time`` field. If the name is not provided in - the request, the server will assign a random name for this - snapshot on the same project as the subscription, conforming to - the [resource name format] - (https://cloud.google.com/pubsub/docs/admin#resource_names). The - generated name is populated in the returned Snapshot object. - Note that for REST API requests, you must specify a name in the - request. - - Returns: - Callable[[~.CreateSnapshotRequest], - ~.Snapshot]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'create_snapshot' not in self._stubs: - self._stubs['create_snapshot'] = self.grpc_channel.unary_unary( - '/google.pubsub.v1.Subscriber/CreateSnapshot', - request_serializer=pubsub.CreateSnapshotRequest.serialize, - response_deserializer=pubsub.Snapshot.deserialize, - ) - return self._stubs['create_snapshot'] - - @property - def update_snapshot(self) -> Callable[ - [pubsub.UpdateSnapshotRequest], - pubsub.Snapshot]: - r"""Return a callable for the update snapshot method over gRPC. - - Updates an existing snapshot. Snapshots are used in - Seek operations, which allow - you to manage message acknowledgments in bulk. That is, - you can set the acknowledgment state of messages in an - existing subscription to the state captured by a - snapshot. - - Returns: - Callable[[~.UpdateSnapshotRequest], - ~.Snapshot]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'update_snapshot' not in self._stubs: - self._stubs['update_snapshot'] = self.grpc_channel.unary_unary( - '/google.pubsub.v1.Subscriber/UpdateSnapshot', - request_serializer=pubsub.UpdateSnapshotRequest.serialize, - response_deserializer=pubsub.Snapshot.deserialize, - ) - return self._stubs['update_snapshot'] - - @property - def delete_snapshot(self) -> Callable[ - [pubsub.DeleteSnapshotRequest], - empty.Empty]: - r"""Return a callable for the delete snapshot method over gRPC. - - Removes an existing snapshot. Snapshots are used in [Seek] - (https://cloud.google.com/pubsub/docs/replay-overview) - operations, which allow you to manage message acknowledgments in - bulk. That is, you can set the acknowledgment state of messages - in an existing subscription to the state captured by a snapshot. - When the snapshot is deleted, all messages retained in the - snapshot are immediately dropped. After a snapshot is deleted, a - new one may be created with the same name, but the new one has - no association with the old snapshot or its subscription, unless - the same subscription is specified. - - Returns: - Callable[[~.DeleteSnapshotRequest], - ~.Empty]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'delete_snapshot' not in self._stubs: - self._stubs['delete_snapshot'] = self.grpc_channel.unary_unary( - '/google.pubsub.v1.Subscriber/DeleteSnapshot', - request_serializer=pubsub.DeleteSnapshotRequest.serialize, - response_deserializer=empty.Empty.FromString, - ) - return self._stubs['delete_snapshot'] - - @property - def seek(self) -> Callable[ - [pubsub.SeekRequest], - pubsub.SeekResponse]: - r"""Return a callable for the seek method over gRPC. - - Seeks an existing subscription to a point in time or to a given - snapshot, whichever is provided in the request. Snapshots are - used in [Seek] - (https://cloud.google.com/pubsub/docs/replay-overview) - operations, which allow you to manage message acknowledgments in - bulk. That is, you can set the acknowledgment state of messages - in an existing subscription to the state captured by a snapshot. - Note that both the subscription and the snapshot must be on the - same topic. - - Returns: - Callable[[~.SeekRequest], - ~.SeekResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'seek' not in self._stubs: - self._stubs['seek'] = self.grpc_channel.unary_unary( - '/google.pubsub.v1.Subscriber/Seek', - request_serializer=pubsub.SeekRequest.serialize, - response_deserializer=pubsub.SeekResponse.deserialize, - ) - return self._stubs['seek'] - - @property - def set_iam_policy( - self, - ) -> Callable[[iam_policy.SetIamPolicyRequest], policy.Policy]: - r"""Return a callable for the set iam policy method over gRPC. - Sets the IAM access control policy on the specified - function. Replaces any existing policy. - Returns: - Callable[[~.SetIamPolicyRequest], - ~.Policy]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "set_iam_policy" not in self._stubs: - self._stubs["set_iam_policy"] = self.grpc_channel.unary_unary( - "/google.iam.v1.IAMPolicy/SetIamPolicy", - request_serializer=iam_policy.SetIamPolicyRequest.SerializeToString, - response_deserializer=policy.Policy.FromString, - ) - return self._stubs["set_iam_policy"] - - @property - def get_iam_policy( - self, - ) -> Callable[[iam_policy.GetIamPolicyRequest], policy.Policy]: - r"""Return a callable for the get iam policy method over gRPC. - Gets the IAM access control policy for a function. - Returns an empty policy if the function exists and does - not have a policy set. - Returns: - Callable[[~.GetIamPolicyRequest], - ~.Policy]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "get_iam_policy" not in self._stubs: - self._stubs["get_iam_policy"] = self.grpc_channel.unary_unary( - "/google.iam.v1.IAMPolicy/GetIamPolicy", - request_serializer=iam_policy.GetIamPolicyRequest.SerializeToString, - response_deserializer=policy.Policy.FromString, - ) - return self._stubs["get_iam_policy"] - - @property - def test_iam_permissions( - self, - ) -> Callable[ - [iam_policy.TestIamPermissionsRequest], iam_policy.TestIamPermissionsResponse - ]: - r"""Return a callable for the test iam permissions method over gRPC. - Tests the specified permissions against the IAM access control - policy for a function. If the function does not exist, this will - return an empty set of permissions, not a NOT_FOUND error. - Returns: - Callable[[~.TestIamPermissionsRequest], - ~.TestIamPermissionsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "test_iam_permissions" not in self._stubs: - self._stubs["test_iam_permissions"] = self.grpc_channel.unary_unary( - "/google.iam.v1.IAMPolicy/TestIamPermissions", - request_serializer=iam_policy.TestIamPermissionsRequest.SerializeToString, - response_deserializer=iam_policy.TestIamPermissionsResponse.FromString, - ) - return self._stubs["test_iam_permissions"] - - -__all__ = ( - 'SubscriberGrpcTransport', -) diff --git a/owl-bot-staging/v1/google/pubsub_v1/services/subscriber/transports/grpc_asyncio.py b/owl-bot-staging/v1/google/pubsub_v1/services/subscriber/transports/grpc_asyncio.py deleted file mode 100644 index 174d9d93d..000000000 --- a/owl-bot-staging/v1/google/pubsub_v1/services/subscriber/transports/grpc_asyncio.py +++ /dev/null @@ -1,826 +0,0 @@ -# -*- coding: utf-8 -*- - -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -import warnings -from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple - -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 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.pubsub_v1.types import pubsub - -from .base import SubscriberTransport, DEFAULT_CLIENT_INFO -from .grpc import SubscriberGrpcTransport - - -class SubscriberGrpcAsyncIOTransport(SubscriberTransport): - """gRPC AsyncIO backend transport for Subscriber. - - The service that an application uses to manipulate subscriptions and - to consume messages from a subscription via the ``Pull`` method or - by establishing a bi-directional stream using the ``StreamingPull`` - method. - - This class defines the same methods as the primary client, so the - primary client can load the underlying transport implementation - and call it. - - It sends protocol buffers over the wire using gRPC (which is built on - top of HTTP/2); the ``grpcio`` package must be installed. - """ - - _grpc_channel: aio.Channel - _stubs: Dict[str, Callable] = {} - - @classmethod - def create_channel(cls, - host: str = 'pubsub.googleapis.com', - credentials: credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> aio.Channel: - """Create and return a gRPC AsyncIO channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - aio.Channel: A gRPC AsyncIO channel object. - """ - 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, - **kwargs - ) - - def __init__(self, *, - host: str = 'pubsub.googleapis.com', - credentials: credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: aio.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, - quota_project_id=None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - channel (Optional[aio.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or applicatin default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - credentials=self._credentials, - credentials_file=credentials_file, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @property - def grpc_channel(self) -> aio.Channel: - """Create the channel designed to connect to this service. - - This property caches on the instance; repeated calls return - the same channel. - """ - # Return the channel from cache. - return self._grpc_channel - - @property - def create_subscription(self) -> Callable[ - [pubsub.Subscription], - Awaitable[pubsub.Subscription]]: - r"""Return a callable for the create subscription method over gRPC. - - Creates a subscription to a given topic. See the [resource name - rules] - (https://cloud.google.com/pubsub/docs/admin#resource_names). If - the subscription already exists, returns ``ALREADY_EXISTS``. If - the corresponding topic doesn't exist, returns ``NOT_FOUND``. - - If the name is not provided in the request, the server will - assign a random name for this subscription on the same project - as the topic, conforming to the [resource name format] - (https://cloud.google.com/pubsub/docs/admin#resource_names). The - generated name is populated in the returned Subscription object. - Note that for REST API requests, you must specify a name in the - request. - - Returns: - Callable[[~.Subscription], - Awaitable[~.Subscription]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'create_subscription' not in self._stubs: - self._stubs['create_subscription'] = self.grpc_channel.unary_unary( - '/google.pubsub.v1.Subscriber/CreateSubscription', - request_serializer=pubsub.Subscription.serialize, - response_deserializer=pubsub.Subscription.deserialize, - ) - return self._stubs['create_subscription'] - - @property - def get_subscription(self) -> Callable[ - [pubsub.GetSubscriptionRequest], - Awaitable[pubsub.Subscription]]: - r"""Return a callable for the get subscription method over gRPC. - - Gets the configuration details of a subscription. - - Returns: - Callable[[~.GetSubscriptionRequest], - Awaitable[~.Subscription]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'get_subscription' not in self._stubs: - self._stubs['get_subscription'] = self.grpc_channel.unary_unary( - '/google.pubsub.v1.Subscriber/GetSubscription', - request_serializer=pubsub.GetSubscriptionRequest.serialize, - response_deserializer=pubsub.Subscription.deserialize, - ) - return self._stubs['get_subscription'] - - @property - def update_subscription(self) -> Callable[ - [pubsub.UpdateSubscriptionRequest], - Awaitable[pubsub.Subscription]]: - r"""Return a callable for the update subscription method over gRPC. - - Updates an existing subscription. Note that certain - properties of a subscription, such as its topic, are not - modifiable. - - Returns: - Callable[[~.UpdateSubscriptionRequest], - Awaitable[~.Subscription]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'update_subscription' not in self._stubs: - self._stubs['update_subscription'] = self.grpc_channel.unary_unary( - '/google.pubsub.v1.Subscriber/UpdateSubscription', - request_serializer=pubsub.UpdateSubscriptionRequest.serialize, - response_deserializer=pubsub.Subscription.deserialize, - ) - return self._stubs['update_subscription'] - - @property - def list_subscriptions(self) -> Callable[ - [pubsub.ListSubscriptionsRequest], - Awaitable[pubsub.ListSubscriptionsResponse]]: - r"""Return a callable for the list subscriptions method over gRPC. - - Lists matching subscriptions. - - Returns: - Callable[[~.ListSubscriptionsRequest], - Awaitable[~.ListSubscriptionsResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'list_subscriptions' not in self._stubs: - self._stubs['list_subscriptions'] = self.grpc_channel.unary_unary( - '/google.pubsub.v1.Subscriber/ListSubscriptions', - request_serializer=pubsub.ListSubscriptionsRequest.serialize, - response_deserializer=pubsub.ListSubscriptionsResponse.deserialize, - ) - return self._stubs['list_subscriptions'] - - @property - def delete_subscription(self) -> Callable[ - [pubsub.DeleteSubscriptionRequest], - Awaitable[empty.Empty]]: - r"""Return a callable for the delete subscription method over gRPC. - - Deletes an existing subscription. All messages retained in the - subscription are immediately dropped. Calls to ``Pull`` after - deletion will return ``NOT_FOUND``. After a subscription is - deleted, a new one may be created with the same name, but the - new one has no association with the old subscription or its - topic unless the same topic is specified. - - Returns: - Callable[[~.DeleteSubscriptionRequest], - Awaitable[~.Empty]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'delete_subscription' not in self._stubs: - self._stubs['delete_subscription'] = self.grpc_channel.unary_unary( - '/google.pubsub.v1.Subscriber/DeleteSubscription', - request_serializer=pubsub.DeleteSubscriptionRequest.serialize, - response_deserializer=empty.Empty.FromString, - ) - return self._stubs['delete_subscription'] - - @property - def modify_ack_deadline(self) -> Callable[ - [pubsub.ModifyAckDeadlineRequest], - Awaitable[empty.Empty]]: - r"""Return a callable for the modify ack deadline method over gRPC. - - Modifies the ack deadline for a specific message. This method is - useful to indicate that more time is needed to process a message - by the subscriber, or to make the message available for - redelivery if the processing was interrupted. Note that this - does not modify the subscription-level ``ackDeadlineSeconds`` - used for subsequent messages. - - Returns: - Callable[[~.ModifyAckDeadlineRequest], - Awaitable[~.Empty]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'modify_ack_deadline' not in self._stubs: - self._stubs['modify_ack_deadline'] = self.grpc_channel.unary_unary( - '/google.pubsub.v1.Subscriber/ModifyAckDeadline', - request_serializer=pubsub.ModifyAckDeadlineRequest.serialize, - response_deserializer=empty.Empty.FromString, - ) - return self._stubs['modify_ack_deadline'] - - @property - def acknowledge(self) -> Callable[ - [pubsub.AcknowledgeRequest], - Awaitable[empty.Empty]]: - r"""Return a callable for the acknowledge method over gRPC. - - Acknowledges the messages associated with the ``ack_ids`` in the - ``AcknowledgeRequest``. The Pub/Sub system can remove the - relevant messages from the subscription. - - Acknowledging a message whose ack deadline has expired may - succeed, but such a message may be redelivered later. - Acknowledging a message more than once will not result in an - error. - - Returns: - Callable[[~.AcknowledgeRequest], - Awaitable[~.Empty]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'acknowledge' not in self._stubs: - self._stubs['acknowledge'] = self.grpc_channel.unary_unary( - '/google.pubsub.v1.Subscriber/Acknowledge', - request_serializer=pubsub.AcknowledgeRequest.serialize, - response_deserializer=empty.Empty.FromString, - ) - return self._stubs['acknowledge'] - - @property - def pull(self) -> Callable[ - [pubsub.PullRequest], - Awaitable[pubsub.PullResponse]]: - r"""Return a callable for the pull method over gRPC. - - Pulls messages from the server. The server may return - ``UNAVAILABLE`` if there are too many concurrent pull requests - pending for the given subscription. - - Returns: - Callable[[~.PullRequest], - Awaitable[~.PullResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'pull' not in self._stubs: - self._stubs['pull'] = self.grpc_channel.unary_unary( - '/google.pubsub.v1.Subscriber/Pull', - request_serializer=pubsub.PullRequest.serialize, - response_deserializer=pubsub.PullResponse.deserialize, - ) - return self._stubs['pull'] - - @property - def streaming_pull(self) -> Callable[ - [pubsub.StreamingPullRequest], - Awaitable[pubsub.StreamingPullResponse]]: - r"""Return a callable for the streaming pull method over gRPC. - - Establishes a stream with the server, which sends messages down - to the client. The client streams acknowledgements and ack - deadline modifications back to the server. The server will close - the stream and return the status on any error. The server may - close the stream with status ``UNAVAILABLE`` to reassign - server-side resources, in which case, the client should - re-establish the stream. Flow control can be achieved by - configuring the underlying RPC channel. - - Returns: - Callable[[~.StreamingPullRequest], - Awaitable[~.StreamingPullResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'streaming_pull' not in self._stubs: - self._stubs['streaming_pull'] = self.grpc_channel.stream_stream( - '/google.pubsub.v1.Subscriber/StreamingPull', - request_serializer=pubsub.StreamingPullRequest.serialize, - response_deserializer=pubsub.StreamingPullResponse.deserialize, - ) - return self._stubs['streaming_pull'] - - @property - def modify_push_config(self) -> Callable[ - [pubsub.ModifyPushConfigRequest], - Awaitable[empty.Empty]]: - r"""Return a callable for the modify push config method over gRPC. - - Modifies the ``PushConfig`` for a specified subscription. - - This may be used to change a push subscription to a pull one - (signified by an empty ``PushConfig``) or vice versa, or change - the endpoint URL and other attributes of a push subscription. - Messages will accumulate for delivery continuously through the - call regardless of changes to the ``PushConfig``. - - Returns: - Callable[[~.ModifyPushConfigRequest], - Awaitable[~.Empty]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'modify_push_config' not in self._stubs: - self._stubs['modify_push_config'] = self.grpc_channel.unary_unary( - '/google.pubsub.v1.Subscriber/ModifyPushConfig', - request_serializer=pubsub.ModifyPushConfigRequest.serialize, - response_deserializer=empty.Empty.FromString, - ) - return self._stubs['modify_push_config'] - - @property - def get_snapshot(self) -> Callable[ - [pubsub.GetSnapshotRequest], - Awaitable[pubsub.Snapshot]]: - r"""Return a callable for the get snapshot method over gRPC. - - Gets the configuration details of a snapshot. - Snapshots are used in Seek operations, which allow you to manage - message acknowledgments in bulk. That is, you can set - the acknowledgment state of messages in an existing - subscription to the state captured by a snapshot. - - Returns: - Callable[[~.GetSnapshotRequest], - Awaitable[~.Snapshot]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'get_snapshot' not in self._stubs: - self._stubs['get_snapshot'] = self.grpc_channel.unary_unary( - '/google.pubsub.v1.Subscriber/GetSnapshot', - request_serializer=pubsub.GetSnapshotRequest.serialize, - response_deserializer=pubsub.Snapshot.deserialize, - ) - return self._stubs['get_snapshot'] - - @property - def list_snapshots(self) -> Callable[ - [pubsub.ListSnapshotsRequest], - Awaitable[pubsub.ListSnapshotsResponse]]: - r"""Return a callable for the list snapshots method over gRPC. - - Lists the existing snapshots. Snapshots are used in - `Seek `__ - operations, which allow you to manage message acknowledgments in - bulk. That is, you can set the acknowledgment state of messages - in an existing subscription to the state captured by a snapshot. - - Returns: - Callable[[~.ListSnapshotsRequest], - Awaitable[~.ListSnapshotsResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'list_snapshots' not in self._stubs: - self._stubs['list_snapshots'] = self.grpc_channel.unary_unary( - '/google.pubsub.v1.Subscriber/ListSnapshots', - request_serializer=pubsub.ListSnapshotsRequest.serialize, - response_deserializer=pubsub.ListSnapshotsResponse.deserialize, - ) - return self._stubs['list_snapshots'] - - @property - def create_snapshot(self) -> Callable[ - [pubsub.CreateSnapshotRequest], - Awaitable[pubsub.Snapshot]]: - r"""Return a callable for the create snapshot method over gRPC. - - Creates a snapshot from the requested subscription. Snapshots - are used in - `Seek `__ - operations, which allow you to manage message acknowledgments in - bulk. That is, you can set the acknowledgment state of messages - in an existing subscription to the state captured by a snapshot. - If the snapshot already exists, returns ``ALREADY_EXISTS``. If - the requested subscription doesn't exist, returns ``NOT_FOUND``. - If the backlog in the subscription is too old -- and the - resulting snapshot would expire in less than 1 hour -- then - ``FAILED_PRECONDITION`` is returned. See also the - ``Snapshot.expire_time`` field. If the name is not provided in - the request, the server will assign a random name for this - snapshot on the same project as the subscription, conforming to - the [resource name format] - (https://cloud.google.com/pubsub/docs/admin#resource_names). The - generated name is populated in the returned Snapshot object. - Note that for REST API requests, you must specify a name in the - request. - - Returns: - Callable[[~.CreateSnapshotRequest], - Awaitable[~.Snapshot]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'create_snapshot' not in self._stubs: - self._stubs['create_snapshot'] = self.grpc_channel.unary_unary( - '/google.pubsub.v1.Subscriber/CreateSnapshot', - request_serializer=pubsub.CreateSnapshotRequest.serialize, - response_deserializer=pubsub.Snapshot.deserialize, - ) - return self._stubs['create_snapshot'] - - @property - def update_snapshot(self) -> Callable[ - [pubsub.UpdateSnapshotRequest], - Awaitable[pubsub.Snapshot]]: - r"""Return a callable for the update snapshot method over gRPC. - - Updates an existing snapshot. Snapshots are used in - Seek operations, which allow - you to manage message acknowledgments in bulk. That is, - you can set the acknowledgment state of messages in an - existing subscription to the state captured by a - snapshot. - - Returns: - Callable[[~.UpdateSnapshotRequest], - Awaitable[~.Snapshot]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'update_snapshot' not in self._stubs: - self._stubs['update_snapshot'] = self.grpc_channel.unary_unary( - '/google.pubsub.v1.Subscriber/UpdateSnapshot', - request_serializer=pubsub.UpdateSnapshotRequest.serialize, - response_deserializer=pubsub.Snapshot.deserialize, - ) - return self._stubs['update_snapshot'] - - @property - def delete_snapshot(self) -> Callable[ - [pubsub.DeleteSnapshotRequest], - Awaitable[empty.Empty]]: - r"""Return a callable for the delete snapshot method over gRPC. - - Removes an existing snapshot. Snapshots are used in [Seek] - (https://cloud.google.com/pubsub/docs/replay-overview) - operations, which allow you to manage message acknowledgments in - bulk. That is, you can set the acknowledgment state of messages - in an existing subscription to the state captured by a snapshot. - When the snapshot is deleted, all messages retained in the - snapshot are immediately dropped. After a snapshot is deleted, a - new one may be created with the same name, but the new one has - no association with the old snapshot or its subscription, unless - the same subscription is specified. - - Returns: - Callable[[~.DeleteSnapshotRequest], - Awaitable[~.Empty]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'delete_snapshot' not in self._stubs: - self._stubs['delete_snapshot'] = self.grpc_channel.unary_unary( - '/google.pubsub.v1.Subscriber/DeleteSnapshot', - request_serializer=pubsub.DeleteSnapshotRequest.serialize, - response_deserializer=empty.Empty.FromString, - ) - return self._stubs['delete_snapshot'] - - @property - def seek(self) -> Callable[ - [pubsub.SeekRequest], - Awaitable[pubsub.SeekResponse]]: - r"""Return a callable for the seek method over gRPC. - - Seeks an existing subscription to a point in time or to a given - snapshot, whichever is provided in the request. Snapshots are - used in [Seek] - (https://cloud.google.com/pubsub/docs/replay-overview) - operations, which allow you to manage message acknowledgments in - bulk. That is, you can set the acknowledgment state of messages - in an existing subscription to the state captured by a snapshot. - Note that both the subscription and the snapshot must be on the - same topic. - - Returns: - Callable[[~.SeekRequest], - Awaitable[~.SeekResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'seek' not in self._stubs: - self._stubs['seek'] = self.grpc_channel.unary_unary( - '/google.pubsub.v1.Subscriber/Seek', - request_serializer=pubsub.SeekRequest.serialize, - response_deserializer=pubsub.SeekResponse.deserialize, - ) - return self._stubs['seek'] - - @property - def set_iam_policy( - self, - ) -> Callable[[iam_policy.SetIamPolicyRequest], Awaitable[policy.Policy]]: - r"""Return a callable for the set iam policy method over gRPC. - Sets the IAM access control policy on the specified - function. Replaces any existing policy. - Returns: - Callable[[~.SetIamPolicyRequest], - Awaitable[~.Policy]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "set_iam_policy" not in self._stubs: - self._stubs["set_iam_policy"] = self.grpc_channel.unary_unary( - "/google.iam.v1.IAMPolicy/SetIamPolicy", - request_serializer=iam_policy.SetIamPolicyRequest.SerializeToString, - response_deserializer=policy.Policy.FromString, - ) - return self._stubs["set_iam_policy"] - - @property - def get_iam_policy( - self, - ) -> Callable[[iam_policy.GetIamPolicyRequest], Awaitable[policy.Policy]]: - r"""Return a callable for the get iam policy method over gRPC. - Gets the IAM access control policy for a function. - Returns an empty policy if the function exists and does - not have a policy set. - Returns: - Callable[[~.GetIamPolicyRequest], - Awaitable[~.Policy]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "get_iam_policy" not in self._stubs: - self._stubs["get_iam_policy"] = self.grpc_channel.unary_unary( - "/google.iam.v1.IAMPolicy/GetIamPolicy", - request_serializer=iam_policy.GetIamPolicyRequest.SerializeToString, - response_deserializer=policy.Policy.FromString, - ) - return self._stubs["get_iam_policy"] - - @property - def test_iam_permissions( - self, - ) -> Callable[ - [iam_policy.TestIamPermissionsRequest], - Awaitable[iam_policy.TestIamPermissionsResponse], - ]: - r"""Return a callable for the test iam permissions method over gRPC. - Tests the specified permissions against the IAM access control - policy for a function. If the function does not exist, this will - return an empty set of permissions, not a NOT_FOUND error. - Returns: - Callable[[~.TestIamPermissionsRequest], - Awaitable[~.TestIamPermissionsResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "test_iam_permissions" not in self._stubs: - self._stubs["test_iam_permissions"] = self.grpc_channel.unary_unary( - "/google.iam.v1.IAMPolicy/TestIamPermissions", - request_serializer=iam_policy.TestIamPermissionsRequest.SerializeToString, - response_deserializer=iam_policy.TestIamPermissionsResponse.FromString, - ) - return self._stubs["test_iam_permissions"] - - -__all__ = ( - 'SubscriberGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v1/google/pubsub_v1/types/__init__.py b/owl-bot-staging/v1/google/pubsub_v1/types/__init__.py deleted file mode 100644 index 2e91f37fa..000000000 --- a/owl-bot-staging/v1/google/pubsub_v1/types/__init__.py +++ /dev/null @@ -1,136 +0,0 @@ -# -*- coding: utf-8 -*- - -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -from .pubsub import ( - AcknowledgeRequest, - CreateSnapshotRequest, - DeadLetterPolicy, - DeleteSnapshotRequest, - DeleteSubscriptionRequest, - DeleteTopicRequest, - DetachSubscriptionRequest, - DetachSubscriptionResponse, - ExpirationPolicy, - GetSnapshotRequest, - GetSubscriptionRequest, - GetTopicRequest, - ListSnapshotsRequest, - ListSnapshotsResponse, - ListSubscriptionsRequest, - ListSubscriptionsResponse, - ListTopicSnapshotsRequest, - ListTopicSnapshotsResponse, - ListTopicsRequest, - ListTopicsResponse, - ListTopicSubscriptionsRequest, - ListTopicSubscriptionsResponse, - MessageStoragePolicy, - ModifyAckDeadlineRequest, - ModifyPushConfigRequest, - PublishRequest, - PublishResponse, - PubsubMessage, - PullRequest, - PullResponse, - PushConfig, - ReceivedMessage, - RetryPolicy, - SchemaSettings, - SeekRequest, - SeekResponse, - Snapshot, - StreamingPullRequest, - StreamingPullResponse, - Subscription, - Topic, - UpdateSnapshotRequest, - UpdateSubscriptionRequest, - UpdateTopicRequest, -) -from .schema import ( - CreateSchemaRequest, - DeleteSchemaRequest, - GetSchemaRequest, - ListSchemasRequest, - ListSchemasResponse, - Schema, - ValidateMessageRequest, - ValidateMessageResponse, - ValidateSchemaRequest, - ValidateSchemaResponse, - Encoding, - SchemaView, -) - -__all__ = ( - 'AcknowledgeRequest', - 'CreateSnapshotRequest', - 'DeadLetterPolicy', - 'DeleteSnapshotRequest', - 'DeleteSubscriptionRequest', - 'DeleteTopicRequest', - 'DetachSubscriptionRequest', - 'DetachSubscriptionResponse', - 'ExpirationPolicy', - 'GetSnapshotRequest', - 'GetSubscriptionRequest', - 'GetTopicRequest', - 'ListSnapshotsRequest', - 'ListSnapshotsResponse', - 'ListSubscriptionsRequest', - 'ListSubscriptionsResponse', - 'ListTopicSnapshotsRequest', - 'ListTopicSnapshotsResponse', - 'ListTopicsRequest', - 'ListTopicsResponse', - 'ListTopicSubscriptionsRequest', - 'ListTopicSubscriptionsResponse', - 'MessageStoragePolicy', - 'ModifyAckDeadlineRequest', - 'ModifyPushConfigRequest', - 'PublishRequest', - 'PublishResponse', - 'PubsubMessage', - 'PullRequest', - 'PullResponse', - 'PushConfig', - 'ReceivedMessage', - 'RetryPolicy', - 'SchemaSettings', - 'SeekRequest', - 'SeekResponse', - 'Snapshot', - 'StreamingPullRequest', - 'StreamingPullResponse', - 'Subscription', - 'Topic', - 'UpdateSnapshotRequest', - 'UpdateSubscriptionRequest', - 'UpdateTopicRequest', - 'CreateSchemaRequest', - 'DeleteSchemaRequest', - 'GetSchemaRequest', - 'ListSchemasRequest', - 'ListSchemasResponse', - 'Schema', - 'ValidateMessageRequest', - 'ValidateMessageResponse', - 'ValidateSchemaRequest', - 'ValidateSchemaResponse', - 'Encoding', - 'SchemaView', -) diff --git a/owl-bot-staging/v1/google/pubsub_v1/types/pubsub.py b/owl-bot-staging/v1/google/pubsub_v1/types/pubsub.py deleted file mode 100644 index eb7f3f83a..000000000 --- a/owl-bot-staging/v1/google/pubsub_v1/types/pubsub.py +++ /dev/null @@ -1,1372 +0,0 @@ -# -*- coding: utf-8 -*- - -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -import proto # type: ignore - - -from google.protobuf import duration_pb2 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.pubsub_v1.types import schema as gp_schema - - -__protobuf__ = proto.module( - package='google.pubsub.v1', - manifest={ - 'MessageStoragePolicy', - 'SchemaSettings', - 'Topic', - 'PubsubMessage', - 'GetTopicRequest', - 'UpdateTopicRequest', - 'PublishRequest', - 'PublishResponse', - 'ListTopicsRequest', - 'ListTopicsResponse', - 'ListTopicSubscriptionsRequest', - 'ListTopicSubscriptionsResponse', - 'ListTopicSnapshotsRequest', - 'ListTopicSnapshotsResponse', - 'DeleteTopicRequest', - 'DetachSubscriptionRequest', - 'DetachSubscriptionResponse', - 'Subscription', - 'RetryPolicy', - 'DeadLetterPolicy', - 'ExpirationPolicy', - 'PushConfig', - 'ReceivedMessage', - 'GetSubscriptionRequest', - 'UpdateSubscriptionRequest', - 'ListSubscriptionsRequest', - 'ListSubscriptionsResponse', - 'DeleteSubscriptionRequest', - 'ModifyPushConfigRequest', - 'PullRequest', - 'PullResponse', - 'ModifyAckDeadlineRequest', - 'AcknowledgeRequest', - 'StreamingPullRequest', - 'StreamingPullResponse', - 'CreateSnapshotRequest', - 'UpdateSnapshotRequest', - 'Snapshot', - 'GetSnapshotRequest', - 'ListSnapshotsRequest', - 'ListSnapshotsResponse', - 'DeleteSnapshotRequest', - 'SeekRequest', - 'SeekResponse', - }, -) - - -class MessageStoragePolicy(proto.Message): - r"""A policy constraining the storage of messages published to - the topic. - - Attributes: - allowed_persistence_regions (Sequence[str]): - A list of IDs of GCP regions where messages - that are published to the topic may be persisted - in storage. Messages published by publishers - running in non-allowed GCP regions (or running - outside of GCP altogether) will be routed for - storage in one of the allowed regions. An empty - list means that no regions are allowed, and is - not a valid configuration. - """ - - allowed_persistence_regions = proto.RepeatedField(proto.STRING, number=1) - - -class SchemaSettings(proto.Message): - r"""Settings for validating messages published against a schema. - - Attributes: - schema (str): - Required. The name of the schema that messages published - should be validated against. Format is - ``projects/{project}/schemas/{schema}``. The value of this - field will be ``_deleted-schema_`` if the schema has been - deleted. - encoding (google.pubsub_v1.types.Encoding): - The encoding of messages validated against ``schema``. - """ - - schema = proto.Field(proto.STRING, number=1) - - encoding = proto.Field(proto.ENUM, number=2, - enum=gp_schema.Encoding, - ) - - -class Topic(proto.Message): - r"""A topic resource. - - Attributes: - name (str): - Required. The name of the topic. It must have the format - ``"projects/{project}/topics/{topic}"``. ``{topic}`` must - start with a letter, and contain only letters - (``[A-Za-z]``), numbers (``[0-9]``), dashes (``-``), - underscores (``_``), periods (``.``), tildes (``~``), plus - (``+``) or percent signs (``%``). It must be between 3 and - 255 characters in length, and it must not start with - ``"goog"``. - labels (Sequence[google.pubsub_v1.types.Topic.LabelsEntry]): - See [Creating and managing labels] - (https://cloud.google.com/pubsub/docs/labels). - message_storage_policy (google.pubsub_v1.types.MessageStoragePolicy): - Policy constraining the set of Google Cloud - Platform regions where messages published to the - topic may be stored. If not present, then no - constraints are in effect. - kms_key_name (str): - The resource name of the Cloud KMS CryptoKey to be used to - protect access to messages published on this topic. - - The expected format is - ``projects/*/locations/*/keyRings/*/cryptoKeys/*``. - schema_settings (google.pubsub_v1.types.SchemaSettings): - Settings for validating messages published - against a schema. - satisfies_pzs (bool): - Reserved for future use. This field is set - only in responses from the server; it is ignored - if it is set in any requests. - """ - - name = proto.Field(proto.STRING, number=1) - - labels = proto.MapField(proto.STRING, proto.STRING, number=2) - - message_storage_policy = proto.Field(proto.MESSAGE, number=3, - message='MessageStoragePolicy', - ) - - kms_key_name = proto.Field(proto.STRING, number=5) - - schema_settings = proto.Field(proto.MESSAGE, number=6, - message='SchemaSettings', - ) - - satisfies_pzs = proto.Field(proto.BOOL, number=7) - - -class PubsubMessage(proto.Message): - r"""A message that is published by publishers and consumed by - subscribers. The message must contain either a non-empty data field - or at least one attribute. Note that client libraries represent this - object differently depending on the language. See the corresponding - `client library - documentation `__ - for more information. See [quotas and limits] - (https://cloud.google.com/pubsub/quotas) for more information about - message limits. - - Attributes: - data (bytes): - The message data field. If this field is - empty, the message must contain at least one - attribute. - attributes (Sequence[google.pubsub_v1.types.PubsubMessage.AttributesEntry]): - Attributes for this message. If this field is - empty, the message must contain non-empty data. - This can be used to filter messages on the - subscription. - message_id (str): - ID of this message, assigned by the server when the message - is published. Guaranteed to be unique within the topic. This - value may be read by a subscriber that receives a - ``PubsubMessage`` via a ``Pull`` call or a push delivery. It - must not be populated by the publisher in a ``Publish`` - call. - publish_time (google.protobuf.timestamp_pb2.Timestamp): - The time at which the message was published, populated by - the server when it receives the ``Publish`` call. It must - not be populated by the publisher in a ``Publish`` call. - ordering_key (str): - If non-empty, identifies related messages for which publish - order should be respected. If a ``Subscription`` has - ``enable_message_ordering`` set to ``true``, messages - published with the same non-empty ``ordering_key`` value - will be delivered to subscribers in the order in which they - are received by the Pub/Sub system. All ``PubsubMessage``\ s - published in a given ``PublishRequest`` must specify the - same ``ordering_key`` value. - """ - - data = proto.Field(proto.BYTES, number=1) - - attributes = proto.MapField(proto.STRING, proto.STRING, number=2) - - message_id = proto.Field(proto.STRING, number=3) - - publish_time = proto.Field(proto.MESSAGE, number=4, - message=timestamp.Timestamp, - ) - - ordering_key = proto.Field(proto.STRING, number=5) - - -class GetTopicRequest(proto.Message): - r"""Request for the GetTopic method. - - Attributes: - topic (str): - Required. The name of the topic to get. Format is - ``projects/{project}/topics/{topic}``. - """ - - topic = proto.Field(proto.STRING, number=1) - - -class UpdateTopicRequest(proto.Message): - r"""Request for the UpdateTopic method. - - Attributes: - topic (google.pubsub_v1.types.Topic): - Required. The updated topic object. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Required. Indicates which fields in the provided topic to - update. Must be specified and non-empty. Note that if - ``update_mask`` contains "message_storage_policy" but the - ``message_storage_policy`` is not set in the ``topic`` - provided above, then the updated value is determined by the - policy configured at the project or organization level. - """ - - topic = proto.Field(proto.MESSAGE, number=1, - message='Topic', - ) - - update_mask = proto.Field(proto.MESSAGE, number=2, - message=field_mask.FieldMask, - ) - - -class PublishRequest(proto.Message): - r"""Request for the Publish method. - - Attributes: - topic (str): - Required. The messages in the request will be published on - this topic. Format is ``projects/{project}/topics/{topic}``. - messages (Sequence[google.pubsub_v1.types.PubsubMessage]): - Required. The messages to publish. - """ - - topic = proto.Field(proto.STRING, number=1) - - messages = proto.RepeatedField(proto.MESSAGE, number=2, - message='PubsubMessage', - ) - - -class PublishResponse(proto.Message): - r"""Response for the ``Publish`` method. - - Attributes: - message_ids (Sequence[str]): - The server-assigned ID of each published - message, in the same order as the messages in - the request. IDs are guaranteed to be unique - within the topic. - """ - - message_ids = proto.RepeatedField(proto.STRING, number=1) - - -class ListTopicsRequest(proto.Message): - r"""Request for the ``ListTopics`` method. - - Attributes: - project (str): - Required. The name of the project in which to list topics. - Format is ``projects/{project-id}``. - page_size (int): - Maximum number of topics to return. - page_token (str): - The value returned by the last ``ListTopicsResponse``; - indicates that this is a continuation of a prior - ``ListTopics`` call, and that the system should return the - next page of data. - """ - - project = proto.Field(proto.STRING, number=1) - - page_size = proto.Field(proto.INT32, number=2) - - page_token = proto.Field(proto.STRING, number=3) - - -class ListTopicsResponse(proto.Message): - r"""Response for the ``ListTopics`` method. - - Attributes: - topics (Sequence[google.pubsub_v1.types.Topic]): - The resulting topics. - next_page_token (str): - If not empty, indicates that there may be more topics that - match the request; this value should be passed in a new - ``ListTopicsRequest``. - """ - - @property - def raw_page(self): - return self - - topics = proto.RepeatedField(proto.MESSAGE, number=1, - message='Topic', - ) - - next_page_token = proto.Field(proto.STRING, number=2) - - -class ListTopicSubscriptionsRequest(proto.Message): - r"""Request for the ``ListTopicSubscriptions`` method. - - Attributes: - topic (str): - Required. The name of the topic that subscriptions are - attached to. Format is - ``projects/{project}/topics/{topic}``. - page_size (int): - Maximum number of subscription names to - return. - page_token (str): - The value returned by the last - ``ListTopicSubscriptionsResponse``; indicates that this is a - continuation of a prior ``ListTopicSubscriptions`` call, and - that the system should return the next page of data. - """ - - topic = proto.Field(proto.STRING, number=1) - - page_size = proto.Field(proto.INT32, number=2) - - page_token = proto.Field(proto.STRING, number=3) - - -class ListTopicSubscriptionsResponse(proto.Message): - r"""Response for the ``ListTopicSubscriptions`` method. - - Attributes: - subscriptions (Sequence[str]): - The names of subscriptions attached to the - topic specified in the request. - next_page_token (str): - If not empty, indicates that there may be more subscriptions - that match the request; this value should be passed in a new - ``ListTopicSubscriptionsRequest`` to get more subscriptions. - """ - - @property - def raw_page(self): - return self - - subscriptions = proto.RepeatedField(proto.STRING, number=1) - - next_page_token = proto.Field(proto.STRING, number=2) - - -class ListTopicSnapshotsRequest(proto.Message): - r"""Request for the ``ListTopicSnapshots`` method. - - Attributes: - topic (str): - Required. The name of the topic that snapshots are attached - to. Format is ``projects/{project}/topics/{topic}``. - page_size (int): - Maximum number of snapshot names to return. - page_token (str): - The value returned by the last - ``ListTopicSnapshotsResponse``; indicates that this is a - continuation of a prior ``ListTopicSnapshots`` call, and - that the system should return the next page of data. - """ - - topic = proto.Field(proto.STRING, number=1) - - page_size = proto.Field(proto.INT32, number=2) - - page_token = proto.Field(proto.STRING, number=3) - - -class ListTopicSnapshotsResponse(proto.Message): - r"""Response for the ``ListTopicSnapshots`` method. - - Attributes: - snapshots (Sequence[str]): - The names of the snapshots that match the - request. - next_page_token (str): - If not empty, indicates that there may be more snapshots - that match the request; this value should be passed in a new - ``ListTopicSnapshotsRequest`` to get more snapshots. - """ - - @property - def raw_page(self): - return self - - snapshots = proto.RepeatedField(proto.STRING, number=1) - - next_page_token = proto.Field(proto.STRING, number=2) - - -class DeleteTopicRequest(proto.Message): - r"""Request for the ``DeleteTopic`` method. - - Attributes: - topic (str): - Required. Name of the topic to delete. Format is - ``projects/{project}/topics/{topic}``. - """ - - topic = proto.Field(proto.STRING, number=1) - - -class DetachSubscriptionRequest(proto.Message): - r"""Request for the DetachSubscription method. - - Attributes: - subscription (str): - Required. The subscription to detach. Format is - ``projects/{project}/subscriptions/{subscription}``. - """ - - subscription = proto.Field(proto.STRING, number=1) - - -class DetachSubscriptionResponse(proto.Message): - r"""Response for the DetachSubscription method. - Reserved for future use. - """ - - -class Subscription(proto.Message): - r"""A subscription resource. - - Attributes: - name (str): - Required. The name of the subscription. It must have the - format - ``"projects/{project}/subscriptions/{subscription}"``. - ``{subscription}`` must start with a letter, and contain - only letters (``[A-Za-z]``), numbers (``[0-9]``), dashes - (``-``), underscores (``_``), periods (``.``), tildes - (``~``), plus (``+``) or percent signs (``%``). It must be - between 3 and 255 characters in length, and it must not - start with ``"goog"``. - topic (str): - Required. The name of the topic from which this subscription - is receiving messages. Format is - ``projects/{project}/topics/{topic}``. The value of this - field will be ``_deleted-topic_`` if the topic has been - deleted. - push_config (google.pubsub_v1.types.PushConfig): - If push delivery is used with this subscription, this field - is used to configure it. An empty ``pushConfig`` signifies - that the subscriber will pull and ack messages using API - methods. - ack_deadline_seconds (int): - The approximate amount of time (on a best-effort basis) - Pub/Sub waits for the subscriber to acknowledge receipt - before resending the message. In the interval after the - message is delivered and before it is acknowledged, it is - considered to be outstanding. During that time period, the - message will not be redelivered (on a best-effort basis). - - For pull subscriptions, this value is used as the initial - value for the ack deadline. To override this value for a - given message, call ``ModifyAckDeadline`` with the - corresponding ``ack_id`` if using non-streaming pull or send - the ``ack_id`` in a ``StreamingModifyAckDeadlineRequest`` if - using streaming pull. The minimum custom deadline you can - specify is 10 seconds. The maximum custom deadline you can - specify is 600 seconds (10 minutes). If this parameter is 0, - a default value of 10 seconds is used. - - For push delivery, this value is also used to set the - request timeout for the call to the push endpoint. - - If the subscriber never acknowledges the message, the - Pub/Sub system will eventually redeliver the message. - retain_acked_messages (bool): - Indicates whether to retain acknowledged messages. If true, - then messages are not expunged from the subscription's - backlog, even if they are acknowledged, until they fall out - of the ``message_retention_duration`` window. This must be - true if you would like to [Seek to a timestamp] - (https://cloud.google.com/pubsub/docs/replay-overview#seek_to_a_time). - message_retention_duration (google.protobuf.duration_pb2.Duration): - How long to retain unacknowledged messages in the - subscription's backlog, from the moment a message is - published. If ``retain_acked_messages`` is true, then this - also configures the retention of acknowledged messages, and - thus configures how far back in time a ``Seek`` can be done. - Defaults to 7 days. Cannot be more than 7 days or less than - 10 minutes. - labels (Sequence[google.pubsub_v1.types.Subscription.LabelsEntry]): - See - Creating and managing labels. - enable_message_ordering (bool): - If true, messages published with the same ``ordering_key`` - in ``PubsubMessage`` will be delivered to the subscribers in - the order in which they are received by the Pub/Sub system. - Otherwise, they may be delivered in any order. - expiration_policy (google.pubsub_v1.types.ExpirationPolicy): - A policy that specifies the conditions for this - subscription's expiration. A subscription is considered - active as long as any connected subscriber is successfully - consuming messages from the subscription or is issuing - operations on the subscription. If ``expiration_policy`` is - not set, a *default policy* with ``ttl`` of 31 days will be - used. The minimum allowed value for - ``expiration_policy.ttl`` is 1 day. - filter (str): - An expression written in the Pub/Sub `filter - language `__. - If non-empty, then only ``PubsubMessage``\ s whose - ``attributes`` field matches the filter are delivered on - this subscription. If empty, then no messages are filtered - out. - dead_letter_policy (google.pubsub_v1.types.DeadLetterPolicy): - A policy that specifies the conditions for dead lettering - messages in this subscription. If dead_letter_policy is not - set, dead lettering is disabled. - - The Cloud Pub/Sub service account associated with this - subscriptions's parent project (i.e., - service-{project_number}@gcp-sa-pubsub.iam.gserviceaccount.com) - must have permission to Acknowledge() messages on this - subscription. - retry_policy (google.pubsub_v1.types.RetryPolicy): - A policy that specifies how Pub/Sub retries - message delivery for this subscription. - - If not set, the default retry policy is applied. - This generally implies that messages will be - retried as soon as possible for healthy - subscribers. RetryPolicy will be triggered on - NACKs or acknowledgement deadline exceeded - events for a given message. - detached (bool): - Indicates whether the subscription is detached from its - topic. Detached subscriptions don't receive messages from - their topic and don't retain any backlog. ``Pull`` and - ``StreamingPull`` requests will return FAILED_PRECONDITION. - If the subscription is a push subscription, pushes to the - endpoint will not be made. - """ - - name = proto.Field(proto.STRING, number=1) - - topic = proto.Field(proto.STRING, number=2) - - push_config = proto.Field(proto.MESSAGE, number=4, - message='PushConfig', - ) - - ack_deadline_seconds = proto.Field(proto.INT32, number=5) - - retain_acked_messages = proto.Field(proto.BOOL, number=7) - - message_retention_duration = proto.Field(proto.MESSAGE, number=8, - message=duration.Duration, - ) - - labels = proto.MapField(proto.STRING, proto.STRING, number=9) - - enable_message_ordering = proto.Field(proto.BOOL, number=10) - - expiration_policy = proto.Field(proto.MESSAGE, number=11, - message='ExpirationPolicy', - ) - - filter = proto.Field(proto.STRING, number=12) - - dead_letter_policy = proto.Field(proto.MESSAGE, number=13, - message='DeadLetterPolicy', - ) - - retry_policy = proto.Field(proto.MESSAGE, number=14, - message='RetryPolicy', - ) - - detached = proto.Field(proto.BOOL, number=15) - - -class RetryPolicy(proto.Message): - r"""A policy that specifies how Cloud Pub/Sub retries message delivery. - - Retry delay will be exponential based on provided minimum and - maximum backoffs. https://en.wikipedia.org/wiki/Exponential_backoff. - - RetryPolicy will be triggered on NACKs or acknowledgement deadline - exceeded events for a given message. - - Retry Policy is implemented on a best effort basis. At times, the - delay between consecutive deliveries may not match the - configuration. That is, delay can be more or less than configured - backoff. - - Attributes: - minimum_backoff (google.protobuf.duration_pb2.Duration): - The minimum delay between consecutive - deliveries of a given message. Value should be - between 0 and 600 seconds. Defaults to 10 - seconds. - maximum_backoff (google.protobuf.duration_pb2.Duration): - The maximum delay between consecutive - deliveries of a given message. Value should be - between 0 and 600 seconds. Defaults to 600 - seconds. - """ - - minimum_backoff = proto.Field(proto.MESSAGE, number=1, - message=duration.Duration, - ) - - maximum_backoff = proto.Field(proto.MESSAGE, number=2, - message=duration.Duration, - ) - - -class DeadLetterPolicy(proto.Message): - r"""Dead lettering is done on a best effort basis. The same - message might be dead lettered multiple times. - - If validation on any of the fields fails at subscription - creation/updation, the create/update subscription request will - fail. - - Attributes: - dead_letter_topic (str): - The name of the topic to which dead letter messages should - be published. Format is - ``projects/{project}/topics/{topic}``.The Cloud Pub/Sub - service account associated with the enclosing subscription's - parent project (i.e., - service-{project_number}@gcp-sa-pubsub.iam.gserviceaccount.com) - must have permission to Publish() to this topic. - - The operation will fail if the topic does not exist. Users - should ensure that there is a subscription attached to this - topic since messages published to a topic with no - subscriptions are lost. - max_delivery_attempts (int): - The maximum number of delivery attempts for any message. The - value must be between 5 and 100. - - The number of delivery attempts is defined as 1 + (the sum - of number of NACKs and number of times the acknowledgement - deadline has been exceeded for the message). - - A NACK is any call to ModifyAckDeadline with a 0 deadline. - Note that client libraries may automatically extend - ack_deadlines. - - This field will be honored on a best effort basis. - - If this parameter is 0, a default value of 5 is used. - """ - - dead_letter_topic = proto.Field(proto.STRING, number=1) - - max_delivery_attempts = proto.Field(proto.INT32, number=2) - - -class ExpirationPolicy(proto.Message): - r"""A policy that specifies the conditions for resource - expiration (i.e., automatic resource deletion). - - Attributes: - ttl (google.protobuf.duration_pb2.Duration): - Specifies the "time-to-live" duration for an associated - resource. The resource expires if it is not active for a - period of ``ttl``. The definition of "activity" depends on - the type of the associated resource. The minimum and maximum - allowed values for ``ttl`` depend on the type of the - associated resource, as well. If ``ttl`` is not set, the - associated resource never expires. - """ - - ttl = proto.Field(proto.MESSAGE, number=1, - message=duration.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 - pushed. For example, a Webhook endpoint might use - ``https://example.com/push``. - attributes (Sequence[google.pubsub_v1.types.PushConfig.AttributesEntry]): - Endpoint configuration attributes that can be used to - control different aspects of the message delivery. - - The only currently supported attribute is - ``x-goog-version``, which you can use to change the format - of the pushed message. This attribute indicates the version - of the data expected by the endpoint. This controls the - shape of the pushed message (i.e., its fields and metadata). - - If not present during the ``CreateSubscription`` call, it - will default to the version of the Pub/Sub API used to make - such call. If not present in a ``ModifyPushConfig`` call, - its value will not be changed. ``GetSubscription`` calls - will always return a valid version, even if the subscription - was created without this attribute. - - The only supported values for the ``x-goog-version`` - attribute are: - - - ``v1beta1``: uses the push format defined in the v1beta1 - Pub/Sub API. - - ``v1`` or ``v1beta2``: uses the push format defined in - the v1 Pub/Sub API. - - For example: - - .. raw:: html - -
attributes { "x-goog-version": "v1" } 
- oidc_token (google.pubsub_v1.types.PushConfig.OidcToken): - If specified, Pub/Sub will generate and attach an OIDC JWT - token as an ``Authorization`` header in the HTTP request for - every pushed message. - """ - class OidcToken(proto.Message): - r"""Contains information needed for generating an `OpenID Connect - token `__. - - Attributes: - service_account_email (str): - `Service account - email `__ - to be used for generating the OIDC token. The caller (for - CreateSubscription, UpdateSubscription, and ModifyPushConfig - RPCs) must have the iam.serviceAccounts.actAs permission for - the service account. - audience (str): - Audience to be used when generating OIDC - token. The audience claim identifies the - recipients that the JWT is intended for. The - audience value is a single case-sensitive - string. Having multiple values (array) for the - audience field is not supported. More info about - the OIDC JWT token audience here: - https://tools.ietf.org/html/rfc7519#section-4.1.3 - Note: if not specified, the Push endpoint URL - will be used. - """ - - service_account_email = proto.Field(proto.STRING, number=1) - - audience = proto.Field(proto.STRING, number=2) - - push_endpoint = proto.Field(proto.STRING, number=1) - - attributes = proto.MapField(proto.STRING, proto.STRING, number=2) - - oidc_token = proto.Field(proto.MESSAGE, number=3, oneof='authentication_method', - message=OidcToken, - ) - - -class ReceivedMessage(proto.Message): - r"""A message and its corresponding acknowledgment ID. - - Attributes: - ack_id (str): - This ID can be used to acknowledge the - received message. - message (google.pubsub_v1.types.PubsubMessage): - The message. - delivery_attempt (int): - The approximate number of times that Cloud Pub/Sub has - attempted to deliver the associated message to a subscriber. - - More precisely, this is 1 + (number of NACKs) + (number of - ack_deadline exceeds) for this message. - - A NACK is any call to ModifyAckDeadline with a 0 deadline. - An ack_deadline exceeds event is whenever a message is not - acknowledged within ack_deadline. Note that ack_deadline is - initially Subscription.ackDeadlineSeconds, but may get - extended automatically by the client library. - - Upon the first delivery of a given message, - ``delivery_attempt`` will have a value of 1. The value is - calculated at best effort and is approximate. - - If a DeadLetterPolicy is not set on the subscription, this - will be 0. - """ - - ack_id = proto.Field(proto.STRING, number=1) - - message = proto.Field(proto.MESSAGE, number=2, - message='PubsubMessage', - ) - - delivery_attempt = proto.Field(proto.INT32, number=3) - - -class GetSubscriptionRequest(proto.Message): - r"""Request for the GetSubscription method. - - Attributes: - subscription (str): - Required. The name of the subscription to get. Format is - ``projects/{project}/subscriptions/{sub}``. - """ - - subscription = proto.Field(proto.STRING, number=1) - - -class UpdateSubscriptionRequest(proto.Message): - r"""Request for the UpdateSubscription method. - - Attributes: - subscription (google.pubsub_v1.types.Subscription): - Required. The updated subscription object. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Required. Indicates which fields in the - provided subscription to update. Must be - specified and non-empty. - """ - - subscription = proto.Field(proto.MESSAGE, number=1, - message='Subscription', - ) - - update_mask = proto.Field(proto.MESSAGE, number=2, - message=field_mask.FieldMask, - ) - - -class ListSubscriptionsRequest(proto.Message): - r"""Request for the ``ListSubscriptions`` method. - - Attributes: - project (str): - Required. The name of the project in which to list - subscriptions. Format is ``projects/{project-id}``. - page_size (int): - Maximum number of subscriptions to return. - page_token (str): - The value returned by the last - ``ListSubscriptionsResponse``; indicates that this is a - continuation of a prior ``ListSubscriptions`` call, and that - the system should return the next page of data. - """ - - project = proto.Field(proto.STRING, number=1) - - page_size = proto.Field(proto.INT32, number=2) - - page_token = proto.Field(proto.STRING, number=3) - - -class ListSubscriptionsResponse(proto.Message): - r"""Response for the ``ListSubscriptions`` method. - - Attributes: - subscriptions (Sequence[google.pubsub_v1.types.Subscription]): - The subscriptions that match the request. - next_page_token (str): - If not empty, indicates that there may be more subscriptions - that match the request; this value should be passed in a new - ``ListSubscriptionsRequest`` to get more subscriptions. - """ - - @property - def raw_page(self): - return self - - subscriptions = proto.RepeatedField(proto.MESSAGE, number=1, - message='Subscription', - ) - - next_page_token = proto.Field(proto.STRING, number=2) - - -class DeleteSubscriptionRequest(proto.Message): - r"""Request for the DeleteSubscription method. - - Attributes: - subscription (str): - Required. The subscription to delete. Format is - ``projects/{project}/subscriptions/{sub}``. - """ - - subscription = proto.Field(proto.STRING, number=1) - - -class ModifyPushConfigRequest(proto.Message): - r"""Request for the ModifyPushConfig method. - - Attributes: - subscription (str): - Required. The name of the subscription. Format is - ``projects/{project}/subscriptions/{sub}``. - push_config (google.pubsub_v1.types.PushConfig): - Required. The push configuration for future deliveries. - - An empty ``pushConfig`` indicates that the Pub/Sub system - should stop pushing messages from the given subscription and - allow messages to be pulled and acknowledged - effectively - pausing the subscription if ``Pull`` or ``StreamingPull`` is - not called. - """ - - subscription = proto.Field(proto.STRING, number=1) - - push_config = proto.Field(proto.MESSAGE, number=2, - message='PushConfig', - ) - - -class PullRequest(proto.Message): - r"""Request for the ``Pull`` method. - - Attributes: - subscription (str): - Required. The subscription from which messages should be - pulled. Format is - ``projects/{project}/subscriptions/{sub}``. - return_immediately (bool): - Optional. If this field set to true, the system will respond - immediately even if it there are no messages available to - return in the ``Pull`` response. Otherwise, the system may - wait (for a bounded amount of time) until at least one - message is available, rather than returning no messages. - Warning: setting this field to ``true`` is discouraged - because it adversely impacts the performance of ``Pull`` - operations. We recommend that users do not set this field. - max_messages (int): - Required. The maximum number of messages to - return for this request. Must be a positive - integer. The Pub/Sub system may return fewer - than the number specified. - """ - - subscription = proto.Field(proto.STRING, number=1) - - return_immediately = proto.Field(proto.BOOL, number=2) - - max_messages = proto.Field(proto.INT32, number=3) - - -class PullResponse(proto.Message): - r"""Response for the ``Pull`` method. - - Attributes: - received_messages (Sequence[google.pubsub_v1.types.ReceivedMessage]): - Received Pub/Sub messages. The list will be empty if there - are no more messages available in the backlog. For JSON, the - response can be entirely empty. The Pub/Sub system may - return fewer than the ``maxMessages`` requested even if - there are more messages available in the backlog. - """ - - received_messages = proto.RepeatedField(proto.MESSAGE, number=1, - message='ReceivedMessage', - ) - - -class ModifyAckDeadlineRequest(proto.Message): - r"""Request for the ModifyAckDeadline method. - - Attributes: - subscription (str): - Required. The name of the subscription. Format is - ``projects/{project}/subscriptions/{sub}``. - ack_ids (Sequence[str]): - Required. List of acknowledgment IDs. - ack_deadline_seconds (int): - Required. The new ack deadline with respect to the time this - request was sent to the Pub/Sub system. For example, if the - value is 10, the new ack deadline will expire 10 seconds - after the ``ModifyAckDeadline`` call was made. Specifying - zero might immediately make the message available for - delivery to another subscriber client. This typically - results in an increase in the rate of message redeliveries - (that is, duplicates). The minimum deadline you can specify - is 0 seconds. The maximum deadline you can specify is 600 - seconds (10 minutes). - """ - - subscription = proto.Field(proto.STRING, number=1) - - ack_ids = proto.RepeatedField(proto.STRING, number=4) - - ack_deadline_seconds = proto.Field(proto.INT32, number=3) - - -class AcknowledgeRequest(proto.Message): - r"""Request for the Acknowledge method. - - Attributes: - subscription (str): - Required. The subscription whose message is being - acknowledged. Format is - ``projects/{project}/subscriptions/{sub}``. - ack_ids (Sequence[str]): - Required. The acknowledgment ID for the messages being - acknowledged that was returned by the Pub/Sub system in the - ``Pull`` response. Must not be empty. - """ - - subscription = proto.Field(proto.STRING, number=1) - - ack_ids = proto.RepeatedField(proto.STRING, number=2) - - -class StreamingPullRequest(proto.Message): - r"""Request for the ``StreamingPull`` streaming RPC method. This request - is used to establish the initial stream as well as to stream - acknowledgements and ack deadline modifications from the client to - the server. - - Attributes: - subscription (str): - Required. The subscription for which to initialize the new - stream. This must be provided in the first request on the - stream, and must not be set in subsequent requests from - client to server. Format is - ``projects/{project}/subscriptions/{sub}``. - ack_ids (Sequence[str]): - List of acknowledgement IDs for acknowledging previously - received messages (received on this stream or a different - stream). If an ack ID has expired, the corresponding message - may be redelivered later. Acknowledging a message more than - once will not result in an error. If the acknowledgement ID - is malformed, the stream will be aborted with status - ``INVALID_ARGUMENT``. - modify_deadline_seconds (Sequence[int]): - The list of new ack deadlines for the IDs listed in - ``modify_deadline_ack_ids``. The size of this list must be - the same as the size of ``modify_deadline_ack_ids``. If it - differs the stream will be aborted with - ``INVALID_ARGUMENT``. Each element in this list is applied - to the element in the same position in - ``modify_deadline_ack_ids``. The new ack deadline is with - respect to the time this request was sent to the Pub/Sub - system. Must be >= 0. For example, if the value is 10, the - new ack deadline will expire 10 seconds after this request - is received. If the value is 0, the message is immediately - made available for another streaming or non-streaming pull - request. If the value is < 0 (an error), the stream will be - aborted with status ``INVALID_ARGUMENT``. - modify_deadline_ack_ids (Sequence[str]): - List of acknowledgement IDs whose deadline will be modified - based on the corresponding element in - ``modify_deadline_seconds``. This field can be used to - indicate that more time is needed to process a message by - the subscriber, or to make the message available for - redelivery if the processing was interrupted. - stream_ack_deadline_seconds (int): - Required. The ack deadline to use for the - stream. This must be provided in the first - request on the stream, but it can also be - updated on subsequent requests from client to - server. The minimum deadline you can specify is - 10 seconds. The maximum deadline you can specify - is 600 seconds (10 minutes). - client_id (str): - A unique identifier that is used to distinguish client - instances from each other. Only needs to be provided on the - initial request. When a stream disconnects and reconnects - for the same stream, the client_id should be set to the same - value so that state associated with the old stream can be - transferred to the new stream. The same client_id should not - be used for different client instances. - max_outstanding_messages (int): - Flow control settings for the maximum number of outstanding - messages. When there are ``max_outstanding_messages`` or - more currently sent to the streaming pull client that have - not yet been acked or nacked, the server stops sending more - messages. The sending of messages resumes once the number of - outstanding messages is less than this value. If the value - is <= 0, there is no limit to the number of outstanding - messages. This property can only be set on the initial - StreamingPullRequest. If it is set on a subsequent request, - the stream will be aborted with status ``INVALID_ARGUMENT``. - max_outstanding_bytes (int): - Flow control settings for the maximum number of outstanding - bytes. When there are ``max_outstanding_bytes`` or more - worth of messages currently sent to the streaming pull - client that have not yet been acked or nacked, the server - will stop sending more messages. The sending of messages - resumes once the number of outstanding bytes is less than - this value. If the value is <= 0, there is no limit to the - number of outstanding bytes. This property can only be set - on the initial StreamingPullRequest. If it is set on a - subsequent request, the stream will be aborted with status - ``INVALID_ARGUMENT``. - """ - - subscription = proto.Field(proto.STRING, number=1) - - ack_ids = proto.RepeatedField(proto.STRING, number=2) - - modify_deadline_seconds = proto.RepeatedField(proto.INT32, number=3) - - modify_deadline_ack_ids = proto.RepeatedField(proto.STRING, number=4) - - stream_ack_deadline_seconds = proto.Field(proto.INT32, number=5) - - client_id = proto.Field(proto.STRING, number=6) - - max_outstanding_messages = proto.Field(proto.INT64, number=7) - - max_outstanding_bytes = proto.Field(proto.INT64, number=8) - - -class StreamingPullResponse(proto.Message): - r"""Response for the ``StreamingPull`` method. This response is used to - stream messages from the server to the client. - - Attributes: - received_messages (Sequence[google.pubsub_v1.types.ReceivedMessage]): - Received Pub/Sub messages. This will not be - empty. - """ - - received_messages = proto.RepeatedField(proto.MESSAGE, number=1, - message='ReceivedMessage', - ) - - -class CreateSnapshotRequest(proto.Message): - r"""Request for the ``CreateSnapshot`` method. - - Attributes: - name (str): - Required. User-provided name for this snapshot. If the name - is not provided in the request, the server will assign a - random name for this snapshot on the same project as the - subscription. Note that for REST API requests, you must - specify a name. See the resource name rules. Format is - ``projects/{project}/snapshots/{snap}``. - subscription (str): - Required. The subscription whose backlog the snapshot - retains. Specifically, the created snapshot is guaranteed to - retain: (a) The existing backlog on the subscription. More - precisely, this is defined as the messages in the - subscription's backlog that are unacknowledged upon the - successful completion of the ``CreateSnapshot`` request; as - well as: (b) Any messages published to the subscription's - topic following the successful completion of the - CreateSnapshot request. Format is - ``projects/{project}/subscriptions/{sub}``. - labels (Sequence[google.pubsub_v1.types.CreateSnapshotRequest.LabelsEntry]): - See - Creating and managing labels. - """ - - name = proto.Field(proto.STRING, number=1) - - subscription = proto.Field(proto.STRING, number=2) - - labels = proto.MapField(proto.STRING, proto.STRING, number=3) - - -class UpdateSnapshotRequest(proto.Message): - r"""Request for the UpdateSnapshot method. - - Attributes: - snapshot (google.pubsub_v1.types.Snapshot): - Required. The updated snapshot object. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Required. Indicates which fields in the - provided snapshot to update. Must be specified - and non-empty. - """ - - snapshot = proto.Field(proto.MESSAGE, number=1, - message='Snapshot', - ) - - update_mask = proto.Field(proto.MESSAGE, number=2, - message=field_mask.FieldMask, - ) - - -class Snapshot(proto.Message): - r"""A snapshot resource. Snapshots are used in - `Seek `__ - operations, which allow you to manage message acknowledgments in - bulk. That is, you can set the acknowledgment state of messages in - an existing subscription to the state captured by a snapshot. - - Attributes: - name (str): - The name of the snapshot. - topic (str): - The name of the topic from which this - snapshot is retaining messages. - expire_time (google.protobuf.timestamp_pb2.Timestamp): - The snapshot is guaranteed to exist up until this time. A - newly-created snapshot expires no later than 7 days from the - time of its creation. Its exact lifetime is determined at - creation by the existing backlog in the source subscription. - Specifically, the lifetime of the snapshot is - ``7 days - (age of oldest unacked message in the subscription)``. - For example, consider a subscription whose oldest unacked - message is 3 days old. If a snapshot is created from this - subscription, the snapshot -- which will always capture this - 3-day-old backlog as long as the snapshot exists -- will - expire in 4 days. The service will refuse to create a - snapshot that would expire in less than 1 hour after - creation. - labels (Sequence[google.pubsub_v1.types.Snapshot.LabelsEntry]): - See [Creating and managing labels] - (https://cloud.google.com/pubsub/docs/labels). - """ - - name = proto.Field(proto.STRING, number=1) - - topic = proto.Field(proto.STRING, number=2) - - expire_time = proto.Field(proto.MESSAGE, number=3, - message=timestamp.Timestamp, - ) - - labels = proto.MapField(proto.STRING, proto.STRING, number=4) - - -class GetSnapshotRequest(proto.Message): - r"""Request for the GetSnapshot method. - - Attributes: - snapshot (str): - Required. The name of the snapshot to get. Format is - ``projects/{project}/snapshots/{snap}``. - """ - - snapshot = proto.Field(proto.STRING, number=1) - - -class ListSnapshotsRequest(proto.Message): - r"""Request for the ``ListSnapshots`` method. - - Attributes: - project (str): - Required. The name of the project in which to list - snapshots. Format is ``projects/{project-id}``. - page_size (int): - Maximum number of snapshots to return. - page_token (str): - The value returned by the last ``ListSnapshotsResponse``; - indicates that this is a continuation of a prior - ``ListSnapshots`` call, and that the system should return - the next page of data. - """ - - project = proto.Field(proto.STRING, number=1) - - page_size = proto.Field(proto.INT32, number=2) - - page_token = proto.Field(proto.STRING, number=3) - - -class ListSnapshotsResponse(proto.Message): - r"""Response for the ``ListSnapshots`` method. - - Attributes: - snapshots (Sequence[google.pubsub_v1.types.Snapshot]): - The resulting snapshots. - next_page_token (str): - If not empty, indicates that there may be more snapshot that - match the request; this value should be passed in a new - ``ListSnapshotsRequest``. - """ - - @property - def raw_page(self): - return self - - snapshots = proto.RepeatedField(proto.MESSAGE, number=1, - message='Snapshot', - ) - - next_page_token = proto.Field(proto.STRING, number=2) - - -class DeleteSnapshotRequest(proto.Message): - r"""Request for the ``DeleteSnapshot`` method. - - Attributes: - snapshot (str): - Required. The name of the snapshot to delete. Format is - ``projects/{project}/snapshots/{snap}``. - """ - - snapshot = proto.Field(proto.STRING, number=1) - - -class SeekRequest(proto.Message): - r"""Request for the ``Seek`` method. - - Attributes: - subscription (str): - Required. The subscription to affect. - time (google.protobuf.timestamp_pb2.Timestamp): - The time to seek to. Messages retained in the subscription - that were published before this time are marked as - acknowledged, and messages retained in the subscription that - were published after this time are marked as unacknowledged. - Note that this operation affects only those messages - retained in the subscription (configured by the combination - of ``message_retention_duration`` and - ``retain_acked_messages``). For example, if ``time`` - corresponds to a point before the message retention window - (or to a point before the system's notion of the - subscription creation time), only retained messages will be - marked as unacknowledged, and already-expunged messages will - not be restored. - snapshot (str): - The snapshot to seek to. The snapshot's topic must be the - same as that of the provided subscription. Format is - ``projects/{project}/snapshots/{snap}``. - """ - - 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') - - -class SeekResponse(proto.Message): - r"""Response for the ``Seek`` method (this response is empty).""" - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1/google/pubsub_v1/types/schema.py b/owl-bot-staging/v1/google/pubsub_v1/types/schema.py deleted file mode 100644 index aae04e48d..000000000 --- a/owl-bot-staging/v1/google/pubsub_v1/types/schema.py +++ /dev/null @@ -1,262 +0,0 @@ -# -*- coding: utf-8 -*- - -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -import proto # type: ignore - - -__protobuf__ = proto.module( - package='google.pubsub.v1', - manifest={ - 'SchemaView', - 'Encoding', - 'Schema', - 'CreateSchemaRequest', - 'GetSchemaRequest', - 'ListSchemasRequest', - 'ListSchemasResponse', - 'DeleteSchemaRequest', - 'ValidateSchemaRequest', - 'ValidateSchemaResponse', - 'ValidateMessageRequest', - 'ValidateMessageResponse', - }, -) - - -class SchemaView(proto.Enum): - r"""View of Schema object fields to be returned by GetSchema and - ListSchemas. - """ - SCHEMA_VIEW_UNSPECIFIED = 0 - BASIC = 1 - FULL = 2 - - -class Encoding(proto.Enum): - r"""Possible encoding types for messages.""" - ENCODING_UNSPECIFIED = 0 - JSON = 1 - BINARY = 2 - - -class Schema(proto.Message): - r"""A schema resource. - - Attributes: - name (str): - Required. Name of the schema. Format is - ``projects/{project}/schemas/{schema}``. - type_ (google.pubsub_v1.types.Schema.Type): - The type of the schema definition. - definition (str): - The definition of the schema. This should contain a string - representing the full definition of the schema that is a - valid schema definition of the type specified in ``type``. - """ - class Type(proto.Enum): - r"""Possible schema definition types.""" - TYPE_UNSPECIFIED = 0 - PROTOCOL_BUFFER = 1 - AVRO = 2 - - name = proto.Field(proto.STRING, number=1) - - type_ = proto.Field(proto.ENUM, number=2, - enum=Type, - ) - - definition = proto.Field(proto.STRING, number=3) - - -class CreateSchemaRequest(proto.Message): - r"""Request for the CreateSchema method. - - Attributes: - parent (str): - Required. The name of the project in which to create the - schema. Format is ``projects/{project-id}``. - schema (google.pubsub_v1.types.Schema): - Required. The schema object to create. - - This schema's ``name`` parameter is ignored. The schema - object returned by CreateSchema will have a ``name`` made - using the given ``parent`` and ``schema_id``. - schema_id (str): - The ID to use for the schema, which will become the final - component of the schema's resource name. - - See - https://cloud.google.com/pubsub/docs/admin#resource_names - for resource name constraints. - """ - - parent = proto.Field(proto.STRING, number=1) - - schema = proto.Field(proto.MESSAGE, number=2, - message='Schema', - ) - - schema_id = proto.Field(proto.STRING, number=3) - - -class GetSchemaRequest(proto.Message): - r"""Request for the GetSchema method. - - Attributes: - name (str): - Required. The name of the schema to get. Format is - ``projects/{project}/schemas/{schema}``. - view (google.pubsub_v1.types.SchemaView): - The set of fields to return in the response. If not set, - returns a Schema with ``name`` and ``type``, but not - ``definition``. Set to ``FULL`` to retrieve all fields. - """ - - name = proto.Field(proto.STRING, number=1) - - view = proto.Field(proto.ENUM, number=2, - enum='SchemaView', - ) - - -class ListSchemasRequest(proto.Message): - r"""Request for the ``ListSchemas`` method. - - Attributes: - parent (str): - Required. The name of the project in which to list schemas. - Format is ``projects/{project-id}``. - view (google.pubsub_v1.types.SchemaView): - The set of Schema fields to return in the response. If not - set, returns Schemas with ``name`` and ``type``, but not - ``definition``. Set to ``FULL`` to retrieve all fields. - page_size (int): - Maximum number of schemas to return. - page_token (str): - The value returned by the last ``ListSchemasResponse``; - indicates that this is a continuation of a prior - ``ListSchemas`` call, and that the system should return the - next page of data. - """ - - parent = proto.Field(proto.STRING, number=1) - - view = proto.Field(proto.ENUM, number=2, - enum='SchemaView', - ) - - page_size = proto.Field(proto.INT32, number=3) - - page_token = proto.Field(proto.STRING, number=4) - - -class ListSchemasResponse(proto.Message): - r"""Response for the ``ListSchemas`` method. - - Attributes: - schemas (Sequence[google.pubsub_v1.types.Schema]): - The resulting schemas. - next_page_token (str): - If not empty, indicates that there may be more schemas that - match the request; this value should be passed in a new - ``ListSchemasRequest``. - """ - - @property - def raw_page(self): - return self - - schemas = proto.RepeatedField(proto.MESSAGE, number=1, - message='Schema', - ) - - next_page_token = proto.Field(proto.STRING, number=2) - - -class DeleteSchemaRequest(proto.Message): - r"""Request for the ``DeleteSchema`` method. - - Attributes: - name (str): - Required. Name of the schema to delete. Format is - ``projects/{project}/schemas/{schema}``. - """ - - name = proto.Field(proto.STRING, number=1) - - -class ValidateSchemaRequest(proto.Message): - r"""Request for the ``ValidateSchema`` method. - - Attributes: - parent (str): - Required. The name of the project in which to validate - schemas. Format is ``projects/{project-id}``. - schema (google.pubsub_v1.types.Schema): - Required. The schema object to validate. - """ - - parent = proto.Field(proto.STRING, number=1) - - schema = proto.Field(proto.MESSAGE, number=2, - message='Schema', - ) - - -class ValidateSchemaResponse(proto.Message): - r"""Response for the ``ValidateSchema`` method.""" - - -class ValidateMessageRequest(proto.Message): - r"""Request for the ``ValidateMessage`` method. - - Attributes: - parent (str): - Required. The name of the project in which to validate - schemas. Format is ``projects/{project-id}``. - name (str): - Name of the schema against which to validate. - - Format is ``projects/{project}/schemas/{schema}``. - schema (google.pubsub_v1.types.Schema): - Ad-hoc schema against which to validate - message (bytes): - Message to validate against the provided ``schema_spec``. - encoding (google.pubsub_v1.types.Encoding): - The encoding expected for messages - """ - - parent = proto.Field(proto.STRING, number=1) - - name = proto.Field(proto.STRING, number=2, oneof='schema_spec') - - schema = proto.Field(proto.MESSAGE, number=3, oneof='schema_spec', - message='Schema', - ) - - message = proto.Field(proto.BYTES, number=4) - - encoding = proto.Field(proto.ENUM, number=5, - enum='Encoding', - ) - - -class ValidateMessageResponse(proto.Message): - r"""Response for the ``ValidateMessage`` method.""" - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1/mypy.ini b/owl-bot-staging/v1/mypy.ini deleted file mode 100644 index 4505b4854..000000000 --- a/owl-bot-staging/v1/mypy.ini +++ /dev/null @@ -1,3 +0,0 @@ -[mypy] -python_version = 3.6 -namespace_packages = True diff --git a/owl-bot-staging/v1/noxfile.py b/owl-bot-staging/v1/noxfile.py deleted file mode 100644 index 06898353b..000000000 --- a/owl-bot-staging/v1/noxfile.py +++ /dev/null @@ -1,72 +0,0 @@ -# -*- coding: utf-8 -*- - -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -import os -import shutil - -import nox # type: ignore - - -@nox.session(python=['3.6', '3.7', '3.8', '3.9']) -def unit(session): - """Run the unit test suite.""" - - session.install('coverage', 'pytest', 'pytest-cov', 'asyncmock', 'pytest-asyncio') - session.install('-e', '.') - - session.run( - 'py.test', - '--quiet', - '--cov=google/pubsub_v1/', - '--cov-config=.coveragerc', - '--cov-report=term', - '--cov-report=html', - os.path.join('tests', 'unit', ''.join(session.posargs)) - ) - - -@nox.session(python=['3.6', '3.7']) -def mypy(session): - """Run the type checker.""" - session.install('mypy') - session.install('.') - session.run( - 'mypy', - '--explicit-package-bases', - 'google', - ) - -@nox.session(python='3.6') -def docs(session): - """Build the docs for this library.""" - - session.install("-e", ".") - session.install("sphinx<3.0.0", "alabaster", "recommonmark") - - shutil.rmtree(os.path.join("docs", "_build"), ignore_errors=True) - session.run( - "sphinx-build", - "-W", # warnings as errors - "-T", # show full traceback on exception - "-N", # no colors - "-b", - "html", - "-d", - os.path.join("docs", "_build", "doctrees", ""), - os.path.join("docs", ""), - os.path.join("docs", "_build", "html", ""), - ) diff --git a/owl-bot-staging/v1/scripts/fixup_pubsub_v1_keywords.py b/owl-bot-staging/v1/scripts/fixup_pubsub_v1_keywords.py deleted file mode 100644 index 071e3665f..000000000 --- a/owl-bot-staging/v1/scripts/fixup_pubsub_v1_keywords.py +++ /dev/null @@ -1,213 +0,0 @@ -#! /usr/bin/env python3 -# -*- coding: utf-8 -*- - -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -import argparse -import os -import libcst as cst -import pathlib -import sys -from typing import (Any, Callable, Dict, List, Sequence, Tuple) - - -def partition( - predicate: Callable[[Any], bool], - iterator: Sequence[Any] -) -> Tuple[List[Any], List[Any]]: - """A stable, out-of-place partition.""" - results = ([], []) - - for i in iterator: - results[int(predicate(i))].append(i) - - # Returns trueList, falseList - return results[1], results[0] - - -class pubsubCallTransformer(cst.CSTTransformer): - CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') - METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { - 'acknowledge': ('subscription', 'ack_ids', ), - 'create_schema': ('parent', 'schema', 'schema_id', ), - 'create_snapshot': ('name', 'subscription', 'labels', ), - 'create_subscription': ('name', 'topic', 'push_config', 'ack_deadline_seconds', 'retain_acked_messages', 'message_retention_duration', 'labels', 'enable_message_ordering', 'expiration_policy', 'filter', 'dead_letter_policy', 'retry_policy', 'detached', ), - '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: - try: - key = original.func.attr.value - kword_params = self.METHOD_TO_PARAMS[key] - except (AttributeError, KeyError): - # Either not a method from the API or too convoluted to be sure. - return updated - - # If the existing code is valid, keyword args come after positional args. - # Therefore, all positional args must map to the first parameters. - args, kwargs = partition(lambda a: not bool(a.keyword), updated.args) - if any(k.keyword.value == "request" for k in kwargs): - # We've already fixed this file, don't fix it again. - return updated - - kwargs, ctrl_kwargs = partition( - lambda a: not a.keyword.value in self.CTRL_PARAMS, - kwargs - ) - - args, ctrl_args = args[:len(kword_params)], args[len(kword_params):] - ctrl_kwargs.extend(cst.Arg(value=a.value, keyword=cst.Name(value=ctrl)) - for a, ctrl in zip(ctrl_args, self.CTRL_PARAMS)) - - request_arg = cst.Arg( - value=cst.Dict([ - cst.DictElement( - cst.SimpleString("'{}'".format(name)), - cst.Element(value=arg.value) - ) - # Note: the args + kwargs looks silly, but keep in mind that - # the control parameters had to be stripped out, and that - # those could have been passed positionally or by keyword. - for name, arg in zip(kword_params, args + kwargs)]), - keyword=cst.Name("request") - ) - - return updated.with_changes( - args=[request_arg] + ctrl_kwargs - ) - - -def fix_files( - in_dir: pathlib.Path, - out_dir: pathlib.Path, - *, - transformer=pubsubCallTransformer(), -): - """Duplicate the input dir to the output dir, fixing file method calls. - - Preconditions: - * in_dir is a real directory - * out_dir is a real, empty directory - """ - pyfile_gen = ( - pathlib.Path(os.path.join(root, f)) - for root, _, files in os.walk(in_dir) - for f in files if os.path.splitext(f)[1] == ".py" - ) - - for fpath in pyfile_gen: - with open(fpath, 'r') as f: - src = f.read() - - # Parse the code and insert method call fixes. - tree = cst.parse_module(src) - updated = tree.visit(transformer) - - # Create the path and directory structure for the new file. - updated_path = out_dir.joinpath(fpath.relative_to(in_dir)) - updated_path.parent.mkdir(parents=True, exist_ok=True) - - # Generate the updated source file at the corresponding path. - with open(updated_path, 'w') as f: - f.write(updated.code) - - -if __name__ == '__main__': - parser = argparse.ArgumentParser( - description="""Fix up source that uses the pubsub client library. - -The existing sources are NOT overwritten but are copied to output_dir with changes made. - -Note: This tool operates at a best-effort level at converting positional - parameters in client method calls to keyword based parameters. - Cases where it WILL FAIL include - A) * or ** expansion in a method call. - B) Calls via function or method alias (includes free function calls) - C) Indirect or dispatched calls (e.g. the method is looked up dynamically) - - These all constitute false negatives. The tool will also detect false - positives when an API method shares a name with another method. -""") - parser.add_argument( - '-d', - '--input-directory', - required=True, - dest='input_dir', - help='the input directory to walk for python files to fix up', - ) - parser.add_argument( - '-o', - '--output-directory', - required=True, - dest='output_dir', - help='the directory to output files fixed via un-flattening', - ) - args = parser.parse_args() - input_dir = pathlib.Path(args.input_dir) - output_dir = pathlib.Path(args.output_dir) - if not input_dir.is_dir(): - print( - f"input directory '{input_dir}' does not exist or is not a directory", - file=sys.stderr, - ) - sys.exit(-1) - - if not output_dir.is_dir(): - print( - f"output directory '{output_dir}' does not exist or is not a directory", - file=sys.stderr, - ) - sys.exit(-1) - - if os.listdir(output_dir): - print( - f"output directory '{output_dir}' is not empty", - file=sys.stderr, - ) - sys.exit(-1) - - fix_files(input_dir, output_dir) diff --git a/owl-bot-staging/v1/setup.py b/owl-bot-staging/v1/setup.py deleted file mode 100644 index 82bb43639..000000000 --- a/owl-bot-staging/v1/setup.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- coding: utf-8 -*- - -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -import io -import os -import setuptools # type: ignore - -version = '0.1.0' - -package_root = os.path.abspath(os.path.dirname(__file__)) - -readme_filename = os.path.join(package_root, 'README.rst') -with io.open(readme_filename, encoding='utf-8') as readme_file: - readme = readme_file.read() - -setuptools.setup( - name='google-pubsub', - version=version, - long_description=readme, - packages=setuptools.PEP420PackageFinder.find(), - namespace_packages=('google',), - platforms='Posix; MacOS X; Windows', - include_package_data=True, - install_requires=( - 'google-api-core[grpc] >= 1.22.2, < 2.0.0dev', - 'libcst >= 0.2.5', - 'proto-plus >= 1.15.0', - 'grpc-google-iam-v1', - ), - python_requires='>=3.6', - classifiers=[ - 'Development Status :: 3 - Alpha', - 'Intended Audience :: Developers', - 'Operating System :: OS Independent', - 'Programming Language :: Python :: 3.6', - 'Programming Language :: Python :: 3.7', - 'Programming Language :: Python :: 3.8', - 'Topic :: Internet', - 'Topic :: Software Development :: Libraries :: Python Modules', - ], - zip_safe=False, -) diff --git a/owl-bot-staging/v1/tests/unit/gapic/pubsub_v1/__init__.py b/owl-bot-staging/v1/tests/unit/gapic/pubsub_v1/__init__.py deleted file mode 100644 index 6a7301536..000000000 --- a/owl-bot-staging/v1/tests/unit/gapic/pubsub_v1/__init__.py +++ /dev/null @@ -1,17 +0,0 @@ - -# -*- coding: utf-8 -*- - -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# diff --git a/owl-bot-staging/v1/tests/unit/gapic/pubsub_v1/test_publisher.py b/owl-bot-staging/v1/tests/unit/gapic/pubsub_v1/test_publisher.py deleted file mode 100644 index 6324e48ec..000000000 --- a/owl-bot-staging/v1/tests/unit/gapic/pubsub_v1/test_publisher.py +++ /dev/null @@ -1,3983 +0,0 @@ -# -*- coding: utf-8 -*- - -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -import os -import mock - -import grpc -from grpc.experimental import aio -import math -import pytest -from proto.marshal.rules.dates import DurationRule, TimestampRule - -from google import auth -from google.api_core import client_options -from google.api_core import 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.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.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.pubsub_v1.services.publisher import PublisherAsyncClient -from google.pubsub_v1.services.publisher import PublisherClient -from google.pubsub_v1.services.publisher import pagers -from google.pubsub_v1.services.publisher import transports -from google.pubsub_v1.types import pubsub -from google.pubsub_v1.types import schema - - -def client_cert_source_callback(): - return b"cert bytes", b"key bytes" - - -# If default endpoint is localhost, then default mtls endpoint will be the same. -# This method modifies the default endpoint so the client can produce a different -# mtls endpoint for endpoint testing purposes. -def modify_default_endpoint(client): - return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT - - -def test__get_default_mtls_endpoint(): - api_endpoint = "example.googleapis.com" - api_mtls_endpoint = "example.mtls.googleapis.com" - sandbox_endpoint = "example.sandbox.googleapis.com" - sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" - non_googleapi = "api.example.com" - - assert PublisherClient._get_default_mtls_endpoint(None) is None - assert PublisherClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert PublisherClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert PublisherClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert PublisherClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert PublisherClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - - -@pytest.mark.parametrize("client_class", [ - PublisherClient, - PublisherAsyncClient, -]) -def test_publisher_client_from_service_account_info(client_class): - creds = credentials.AnonymousCredentials() - with mock.patch.object(service_account.Credentials, 'from_service_account_info') as factory: - factory.return_value = creds - info = {"valid": True} - client = client_class.from_service_account_info(info) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == 'pubsub.googleapis.com:443' - - -@pytest.mark.parametrize("client_class", [ - PublisherClient, - PublisherAsyncClient, -]) -def test_publisher_client_from_service_account_file(client_class): - creds = credentials.AnonymousCredentials() - with mock.patch.object(service_account.Credentials, 'from_service_account_file') as factory: - factory.return_value = creds - client = client_class.from_service_account_file("dummy/file/path.json") - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - client = client_class.from_service_account_json("dummy/file/path.json") - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == 'pubsub.googleapis.com:443' - - -def test_publisher_client_get_transport_class(): - transport = PublisherClient.get_transport_class() - available_transports = [ - transports.PublisherGrpcTransport, - ] - assert transport in available_transports - - transport = PublisherClient.get_transport_class("grpc") - assert transport == transports.PublisherGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (PublisherClient, transports.PublisherGrpcTransport, "grpc"), - (PublisherAsyncClient, transports.PublisherGrpcAsyncIOTransport, "grpc_asyncio"), -]) -@mock.patch.object(PublisherClient, "DEFAULT_ENDPOINT", modify_default_endpoint(PublisherClient)) -@mock.patch.object(PublisherAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(PublisherAsyncClient)) -def test_publisher_client_client_options(client_class, transport_class, transport_name): - # Check that if channel is provided we won't create a new one. - with mock.patch.object(PublisherClient, 'get_transport_class') as gtc: - transport = transport_class( - credentials=credentials.AnonymousCredentials() - ) - client = client_class(transport=transport) - gtc.assert_not_called() - - # Check that if channel is provided via str we will create a new one. - with mock.patch.object(PublisherClient, 'get_transport_class') as gtc: - client = client_class(transport=transport_name) - gtc.assert_called() - - # Check the case api_endpoint is provided. - options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class() - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class() - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_MTLS_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has - # unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError): - client = client_class() - - # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError): - client = client_class() - - # Check the case quota_project_id is provided - options = client_options.ClientOptions(quota_project_id="octopus") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id="octopus", - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ - - (PublisherClient, transports.PublisherGrpcTransport, "grpc", "true"), - (PublisherAsyncClient, transports.PublisherGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (PublisherClient, transports.PublisherGrpcTransport, "grpc", "false"), - (PublisherAsyncClient, transports.PublisherGrpcAsyncIOTransport, "grpc_asyncio", "false"), - -]) -@mock.patch.object(PublisherClient, "DEFAULT_ENDPOINT", modify_default_endpoint(PublisherClient)) -@mock.patch.object(PublisherAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(PublisherAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_publisher_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): - # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default - # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. - - # Check the case client_cert_source is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options) - - if use_client_cert_env == "false": - expected_client_cert_source = None - expected_host = client.DEFAULT_ENDPOINT - else: - expected_client_cert_source = client_cert_source_callback - expected_host = client.DEFAULT_MTLS_ENDPOINT - - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - - # Check the case ADC client cert is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): - if use_client_cert_env == "false": - expected_host = client.DEFAULT_ENDPOINT - expected_client_cert_source = None - else: - expected_host = client.DEFAULT_MTLS_ENDPOINT - expected_client_cert_source = client_cert_source_callback - - patched.return_value = None - client = client_class() - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - - # Check the case client_cert_source and ADC client cert are not provided. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): - patched.return_value = None - client = client_class() - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (PublisherClient, transports.PublisherGrpcTransport, "grpc"), - (PublisherAsyncClient, transports.PublisherGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_publisher_client_client_options_scopes(client_class, transport_class, transport_name): - # Check the case scopes are provided. - options = client_options.ClientOptions( - scopes=["1", "2"], - ) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=["1", "2"], - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (PublisherClient, transports.PublisherGrpcTransport, "grpc"), - (PublisherAsyncClient, transports.PublisherGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_publisher_client_client_options_credentials_file(client_class, transport_class, transport_name): - # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - - -def test_publisher_client_client_options_from_dict(): - with mock.patch('google.pubsub_v1.services.publisher.transports.PublisherGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = PublisherClient( - client_options={'api_endpoint': 'squid.clam.whelk'} - ) - grpc_transport.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - - -def test_create_topic(transport: str = 'grpc', request_type=pubsub.Topic): - client = PublisherClient( - credentials=credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_topic), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = pubsub.Topic( - name='name_value', - - kms_key_name='kms_key_name_value', - - satisfies_pzs=True, - - ) - - response = client.create_topic(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - - assert args[0] == pubsub.Topic() - - # Establish that the response is the type that we expect. - - assert isinstance(response, pubsub.Topic) - - assert response.name == 'name_value' - - assert response.kms_key_name == 'kms_key_name_value' - - assert response.satisfies_pzs is True - - -def test_create_topic_from_dict(): - test_create_topic(request_type=dict) - - -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', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_topic), - '__call__') as call: - client.create_topic() - call.assert_called() - _, args, _ = call.mock_calls[0] - - assert args[0] == pubsub.Topic() - -@pytest.mark.asyncio -async def test_create_topic_async(transport: str = 'grpc_asyncio', request_type=pubsub.Topic): - client = PublisherAsyncClient( - credentials=credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_topic), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(pubsub.Topic( - name='name_value', - kms_key_name='kms_key_name_value', - satisfies_pzs=True, - )) - - response = await client.create_topic(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - - assert args[0] == pubsub.Topic() - - # Establish that the response is the type that we expect. - assert isinstance(response, pubsub.Topic) - - assert response.name == 'name_value' - - assert response.kms_key_name == 'kms_key_name_value' - - assert response.satisfies_pzs is True - - -@pytest.mark.asyncio -async def test_create_topic_async_from_dict(): - await test_create_topic_async(request_type=dict) - - -def test_create_topic_field_headers(): - client = PublisherClient( - credentials=credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = pubsub.Topic() - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_topic), - '__call__') as call: - call.return_value = pubsub.Topic() - - client.create_topic(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name/value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_create_topic_field_headers_async(): - client = PublisherAsyncClient( - credentials=credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = pubsub.Topic() - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_topic), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(pubsub.Topic()) - - await client.create_topic(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name/value', - ) in kw['metadata'] - - -def test_create_topic_flattened(): - client = PublisherClient( - credentials=credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_topic), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = pubsub.Topic() - - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.create_topic( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - - assert args[0].name == 'name_value' - - -def test_create_topic_flattened_error(): - client = PublisherClient( - credentials=credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.create_topic( - pubsub.Topic(), - name='name_value', - ) - - -@pytest.mark.asyncio -async def test_create_topic_flattened_async(): - client = PublisherAsyncClient( - credentials=credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_topic), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = pubsub.Topic() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(pubsub.Topic()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.create_topic( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - - assert args[0].name == 'name_value' - - -@pytest.mark.asyncio -async def test_create_topic_flattened_error_async(): - client = PublisherAsyncClient( - credentials=credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.create_topic( - pubsub.Topic(), - name='name_value', - ) - - -def test_update_topic(transport: str = 'grpc', request_type=pubsub.UpdateTopicRequest): - client = PublisherClient( - credentials=credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_topic), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = pubsub.Topic( - name='name_value', - - kms_key_name='kms_key_name_value', - - satisfies_pzs=True, - - ) - - response = client.update_topic(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - - assert args[0] == pubsub.UpdateTopicRequest() - - # Establish that the response is the type that we expect. - - assert isinstance(response, pubsub.Topic) - - assert response.name == 'name_value' - - assert response.kms_key_name == 'kms_key_name_value' - - assert response.satisfies_pzs is True - - -def test_update_topic_from_dict(): - test_update_topic(request_type=dict) - - -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', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_topic), - '__call__') as call: - client.update_topic() - call.assert_called() - _, args, _ = call.mock_calls[0] - - assert args[0] == pubsub.UpdateTopicRequest() - -@pytest.mark.asyncio -async def test_update_topic_async(transport: str = 'grpc_asyncio', request_type=pubsub.UpdateTopicRequest): - client = PublisherAsyncClient( - credentials=credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_topic), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(pubsub.Topic( - name='name_value', - kms_key_name='kms_key_name_value', - satisfies_pzs=True, - )) - - response = await client.update_topic(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - - assert args[0] == pubsub.UpdateTopicRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pubsub.Topic) - - assert response.name == 'name_value' - - assert response.kms_key_name == 'kms_key_name_value' - - assert response.satisfies_pzs is True - - -@pytest.mark.asyncio -async def test_update_topic_async_from_dict(): - await test_update_topic_async(request_type=dict) - - -def test_update_topic_field_headers(): - client = PublisherClient( - credentials=credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = pubsub.UpdateTopicRequest() - request.topic.name = 'topic.name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_topic), - '__call__') as call: - call.return_value = pubsub.Topic() - - client.update_topic(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'topic.name=topic.name/value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_topic_field_headers_async(): - client = PublisherAsyncClient( - credentials=credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = pubsub.UpdateTopicRequest() - request.topic.name = 'topic.name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_topic), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(pubsub.Topic()) - - await client.update_topic(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'topic.name=topic.name/value', - ) in kw['metadata'] - - -def test_publish(transport: str = 'grpc', request_type=pubsub.PublishRequest): - client = PublisherClient( - credentials=credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.publish), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = pubsub.PublishResponse( - message_ids=['message_ids_value'], - - ) - - response = client.publish(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - - assert args[0] == pubsub.PublishRequest() - - # Establish that the response is the type that we expect. - - assert isinstance(response, pubsub.PublishResponse) - - assert response.message_ids == ['message_ids_value'] - - -def test_publish_from_dict(): - test_publish(request_type=dict) - - -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', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.publish), - '__call__') as call: - client.publish() - call.assert_called() - _, args, _ = call.mock_calls[0] - - assert args[0] == pubsub.PublishRequest() - -@pytest.mark.asyncio -async def test_publish_async(transport: str = 'grpc_asyncio', request_type=pubsub.PublishRequest): - client = PublisherAsyncClient( - credentials=credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.publish), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(pubsub.PublishResponse( - message_ids=['message_ids_value'], - )) - - response = await client.publish(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - - assert args[0] == pubsub.PublishRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pubsub.PublishResponse) - - assert response.message_ids == ['message_ids_value'] - - -@pytest.mark.asyncio -async def test_publish_async_from_dict(): - await test_publish_async(request_type=dict) - - -def test_publish_field_headers(): - client = PublisherClient( - credentials=credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = pubsub.PublishRequest() - request.topic = 'topic/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.publish), - '__call__') as call: - call.return_value = pubsub.PublishResponse() - - client.publish(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'topic=topic/value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_publish_field_headers_async(): - client = PublisherAsyncClient( - credentials=credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = pubsub.PublishRequest() - request.topic = 'topic/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.publish), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(pubsub.PublishResponse()) - - await client.publish(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'topic=topic/value', - ) in kw['metadata'] - - -def test_publish_flattened(): - client = PublisherClient( - credentials=credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.publish), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = pubsub.PublishResponse() - - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.publish( - topic='topic_value', - messages=[pubsub.PubsubMessage(data=b'data_blob')], - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - - 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(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.publish( - pubsub.PublishRequest(), - topic='topic_value', - messages=[pubsub.PubsubMessage(data=b'data_blob')], - ) - - -@pytest.mark.asyncio -async def test_publish_flattened_async(): - client = PublisherAsyncClient( - credentials=credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.publish), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = pubsub.PublishResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(pubsub.PublishResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.publish( - topic='topic_value', - messages=[pubsub.PubsubMessage(data=b'data_blob')], - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - - 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(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.publish( - pubsub.PublishRequest(), - topic='topic_value', - messages=[pubsub.PubsubMessage(data=b'data_blob')], - ) - - -def test_get_topic(transport: str = 'grpc', request_type=pubsub.GetTopicRequest): - client = PublisherClient( - credentials=credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_topic), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = pubsub.Topic( - name='name_value', - - kms_key_name='kms_key_name_value', - - satisfies_pzs=True, - - ) - - response = client.get_topic(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - - assert args[0] == pubsub.GetTopicRequest() - - # Establish that the response is the type that we expect. - - assert isinstance(response, pubsub.Topic) - - assert response.name == 'name_value' - - assert response.kms_key_name == 'kms_key_name_value' - - assert response.satisfies_pzs is True - - -def test_get_topic_from_dict(): - test_get_topic(request_type=dict) - - -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', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_topic), - '__call__') as call: - client.get_topic() - call.assert_called() - _, args, _ = call.mock_calls[0] - - assert args[0] == pubsub.GetTopicRequest() - -@pytest.mark.asyncio -async def test_get_topic_async(transport: str = 'grpc_asyncio', request_type=pubsub.GetTopicRequest): - client = PublisherAsyncClient( - credentials=credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_topic), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(pubsub.Topic( - name='name_value', - kms_key_name='kms_key_name_value', - satisfies_pzs=True, - )) - - response = await client.get_topic(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - - assert args[0] == pubsub.GetTopicRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pubsub.Topic) - - assert response.name == 'name_value' - - assert response.kms_key_name == 'kms_key_name_value' - - assert response.satisfies_pzs is True - - -@pytest.mark.asyncio -async def test_get_topic_async_from_dict(): - await test_get_topic_async(request_type=dict) - - -def test_get_topic_field_headers(): - client = PublisherClient( - credentials=credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = pubsub.GetTopicRequest() - request.topic = 'topic/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_topic), - '__call__') as call: - call.return_value = pubsub.Topic() - - client.get_topic(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'topic=topic/value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_get_topic_field_headers_async(): - client = PublisherAsyncClient( - credentials=credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = pubsub.GetTopicRequest() - request.topic = 'topic/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_topic), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(pubsub.Topic()) - - await client.get_topic(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'topic=topic/value', - ) in kw['metadata'] - - -def test_get_topic_flattened(): - client = PublisherClient( - credentials=credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_topic), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = pubsub.Topic() - - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_topic( - topic='topic_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - - assert args[0].topic == 'topic_value' - - -def test_get_topic_flattened_error(): - client = PublisherClient( - credentials=credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.get_topic( - pubsub.GetTopicRequest(), - topic='topic_value', - ) - - -@pytest.mark.asyncio -async def test_get_topic_flattened_async(): - client = PublisherAsyncClient( - credentials=credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_topic), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = pubsub.Topic() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(pubsub.Topic()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_topic( - topic='topic_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - - assert args[0].topic == 'topic_value' - - -@pytest.mark.asyncio -async def test_get_topic_flattened_error_async(): - client = PublisherAsyncClient( - credentials=credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.get_topic( - pubsub.GetTopicRequest(), - topic='topic_value', - ) - - -def test_list_topics(transport: str = 'grpc', request_type=pubsub.ListTopicsRequest): - client = PublisherClient( - credentials=credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_topics), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = pubsub.ListTopicsResponse( - next_page_token='next_page_token_value', - - ) - - response = client.list_topics(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - - assert args[0] == pubsub.ListTopicsRequest() - - # Establish that the response is the type that we expect. - - assert isinstance(response, pagers.ListTopicsPager) - - assert response.next_page_token == 'next_page_token_value' - - -def test_list_topics_from_dict(): - test_list_topics(request_type=dict) - - -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', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_topics), - '__call__') as call: - client.list_topics() - call.assert_called() - _, args, _ = call.mock_calls[0] - - assert args[0] == pubsub.ListTopicsRequest() - -@pytest.mark.asyncio -async def test_list_topics_async(transport: str = 'grpc_asyncio', request_type=pubsub.ListTopicsRequest): - client = PublisherAsyncClient( - credentials=credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_topics), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(pubsub.ListTopicsResponse( - next_page_token='next_page_token_value', - )) - - response = await client.list_topics(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - - assert args[0] == pubsub.ListTopicsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListTopicsAsyncPager) - - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_topics_async_from_dict(): - await test_list_topics_async(request_type=dict) - - -def test_list_topics_field_headers(): - client = PublisherClient( - credentials=credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = pubsub.ListTopicsRequest() - request.project = 'project/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_topics), - '__call__') as call: - call.return_value = pubsub.ListTopicsResponse() - - client.list_topics(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'project=project/value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_list_topics_field_headers_async(): - client = PublisherAsyncClient( - credentials=credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = pubsub.ListTopicsRequest() - request.project = 'project/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_topics), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(pubsub.ListTopicsResponse()) - - await client.list_topics(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'project=project/value', - ) in kw['metadata'] - - -def test_list_topics_flattened(): - client = PublisherClient( - credentials=credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_topics), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = pubsub.ListTopicsResponse() - - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_topics( - project='project_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - - assert args[0].project == 'project_value' - - -def test_list_topics_flattened_error(): - client = PublisherClient( - credentials=credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.list_topics( - pubsub.ListTopicsRequest(), - project='project_value', - ) - - -@pytest.mark.asyncio -async def test_list_topics_flattened_async(): - client = PublisherAsyncClient( - credentials=credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_topics), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = pubsub.ListTopicsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(pubsub.ListTopicsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_topics( - project='project_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - - assert args[0].project == 'project_value' - - -@pytest.mark.asyncio -async def test_list_topics_flattened_error_async(): - client = PublisherAsyncClient( - credentials=credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.list_topics( - pubsub.ListTopicsRequest(), - project='project_value', - ) - - -def test_list_topics_pager(): - client = PublisherClient( - credentials=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: - # Set the response to a series of pages. - call.side_effect = ( - pubsub.ListTopicsResponse( - topics=[ - pubsub.Topic(), - pubsub.Topic(), - pubsub.Topic(), - ], - next_page_token='abc', - ), - pubsub.ListTopicsResponse( - topics=[], - next_page_token='def', - ), - pubsub.ListTopicsResponse( - topics=[ - pubsub.Topic(), - ], - next_page_token='ghi', - ), - pubsub.ListTopicsResponse( - topics=[ - pubsub.Topic(), - pubsub.Topic(), - ], - ), - RuntimeError, - ) - - metadata = () - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('project', ''), - )), - ) - pager = client.list_topics(request={}) - - assert pager._metadata == metadata - - results = [i for i in pager] - assert len(results) == 6 - assert all(isinstance(i, pubsub.Topic) - for i in results) - -def test_list_topics_pages(): - client = PublisherClient( - credentials=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: - # Set the response to a series of pages. - call.side_effect = ( - pubsub.ListTopicsResponse( - topics=[ - pubsub.Topic(), - pubsub.Topic(), - pubsub.Topic(), - ], - next_page_token='abc', - ), - pubsub.ListTopicsResponse( - topics=[], - next_page_token='def', - ), - pubsub.ListTopicsResponse( - topics=[ - pubsub.Topic(), - ], - next_page_token='ghi', - ), - pubsub.ListTopicsResponse( - topics=[ - pubsub.Topic(), - pubsub.Topic(), - ], - ), - RuntimeError, - ) - pages = list(client.list_topics(request={}).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - -@pytest.mark.asyncio -async def test_list_topics_async_pager(): - client = PublisherAsyncClient( - credentials=credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_topics), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - pubsub.ListTopicsResponse( - topics=[ - pubsub.Topic(), - pubsub.Topic(), - pubsub.Topic(), - ], - next_page_token='abc', - ), - pubsub.ListTopicsResponse( - topics=[], - next_page_token='def', - ), - pubsub.ListTopicsResponse( - topics=[ - pubsub.Topic(), - ], - next_page_token='ghi', - ), - pubsub.ListTopicsResponse( - topics=[ - pubsub.Topic(), - pubsub.Topic(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_topics(request={},) - assert async_pager.next_page_token == 'abc' - responses = [] - async for response in async_pager: - responses.append(response) - - assert len(responses) == 6 - assert all(isinstance(i, pubsub.Topic) - for i in responses) - -@pytest.mark.asyncio -async def test_list_topics_async_pages(): - client = PublisherAsyncClient( - credentials=credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_topics), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - pubsub.ListTopicsResponse( - topics=[ - pubsub.Topic(), - pubsub.Topic(), - pubsub.Topic(), - ], - next_page_token='abc', - ), - pubsub.ListTopicsResponse( - topics=[], - next_page_token='def', - ), - pubsub.ListTopicsResponse( - topics=[ - pubsub.Topic(), - ], - next_page_token='ghi', - ), - pubsub.ListTopicsResponse( - topics=[ - pubsub.Topic(), - pubsub.Topic(), - ], - ), - RuntimeError, - ) - pages = [] - async for page_ in (await client.list_topics(request={})).pages: - pages.append(page_) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -def test_list_topic_subscriptions(transport: str = 'grpc', request_type=pubsub.ListTopicSubscriptionsRequest): - client = PublisherClient( - credentials=credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_topic_subscriptions), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = pubsub.ListTopicSubscriptionsResponse( - subscriptions=['subscriptions_value'], - - next_page_token='next_page_token_value', - - ) - - response = client.list_topic_subscriptions(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - - assert args[0] == pubsub.ListTopicSubscriptionsRequest() - - # Establish that the response is the type that we expect. - - assert isinstance(response, pagers.ListTopicSubscriptionsPager) - - assert response.subscriptions == ['subscriptions_value'] - - assert response.next_page_token == 'next_page_token_value' - - -def test_list_topic_subscriptions_from_dict(): - test_list_topic_subscriptions(request_type=dict) - - -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', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_topic_subscriptions), - '__call__') as call: - client.list_topic_subscriptions() - call.assert_called() - _, args, _ = call.mock_calls[0] - - assert args[0] == pubsub.ListTopicSubscriptionsRequest() - -@pytest.mark.asyncio -async def test_list_topic_subscriptions_async(transport: str = 'grpc_asyncio', request_type=pubsub.ListTopicSubscriptionsRequest): - client = PublisherAsyncClient( - credentials=credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_topic_subscriptions), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(pubsub.ListTopicSubscriptionsResponse( - subscriptions=['subscriptions_value'], - next_page_token='next_page_token_value', - )) - - response = await client.list_topic_subscriptions(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - - assert args[0] == pubsub.ListTopicSubscriptionsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListTopicSubscriptionsAsyncPager) - - assert response.subscriptions == ['subscriptions_value'] - - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_topic_subscriptions_async_from_dict(): - await test_list_topic_subscriptions_async(request_type=dict) - - -def test_list_topic_subscriptions_field_headers(): - client = PublisherClient( - credentials=credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = pubsub.ListTopicSubscriptionsRequest() - request.topic = 'topic/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_topic_subscriptions), - '__call__') as call: - call.return_value = pubsub.ListTopicSubscriptionsResponse() - - client.list_topic_subscriptions(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'topic=topic/value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_list_topic_subscriptions_field_headers_async(): - client = PublisherAsyncClient( - credentials=credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = pubsub.ListTopicSubscriptionsRequest() - request.topic = 'topic/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_topic_subscriptions), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(pubsub.ListTopicSubscriptionsResponse()) - - await client.list_topic_subscriptions(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'topic=topic/value', - ) in kw['metadata'] - - -def test_list_topic_subscriptions_flattened(): - client = PublisherClient( - credentials=credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_topic_subscriptions), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = pubsub.ListTopicSubscriptionsResponse() - - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_topic_subscriptions( - topic='topic_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - - assert args[0].topic == 'topic_value' - - -def test_list_topic_subscriptions_flattened_error(): - client = PublisherClient( - credentials=credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.list_topic_subscriptions( - pubsub.ListTopicSubscriptionsRequest(), - topic='topic_value', - ) - - -@pytest.mark.asyncio -async def test_list_topic_subscriptions_flattened_async(): - client = PublisherAsyncClient( - credentials=credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_topic_subscriptions), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = pubsub.ListTopicSubscriptionsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(pubsub.ListTopicSubscriptionsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_topic_subscriptions( - topic='topic_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - - assert args[0].topic == 'topic_value' - - -@pytest.mark.asyncio -async def test_list_topic_subscriptions_flattened_error_async(): - client = PublisherAsyncClient( - credentials=credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.list_topic_subscriptions( - pubsub.ListTopicSubscriptionsRequest(), - topic='topic_value', - ) - - -def test_list_topic_subscriptions_pager(): - client = PublisherClient( - credentials=credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_topic_subscriptions), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - pubsub.ListTopicSubscriptionsResponse( - subscriptions=[ - str(), - str(), - str(), - ], - next_page_token='abc', - ), - pubsub.ListTopicSubscriptionsResponse( - subscriptions=[], - next_page_token='def', - ), - pubsub.ListTopicSubscriptionsResponse( - subscriptions=[ - str(), - ], - next_page_token='ghi', - ), - pubsub.ListTopicSubscriptionsResponse( - subscriptions=[ - str(), - str(), - ], - ), - RuntimeError, - ) - - metadata = () - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('topic', ''), - )), - ) - pager = client.list_topic_subscriptions(request={}) - - assert pager._metadata == metadata - - results = [i for i in pager] - assert len(results) == 6 - assert all(isinstance(i, str) - for i in results) - -def test_list_topic_subscriptions_pages(): - client = PublisherClient( - credentials=credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_topic_subscriptions), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - pubsub.ListTopicSubscriptionsResponse( - subscriptions=[ - str(), - str(), - str(), - ], - next_page_token='abc', - ), - pubsub.ListTopicSubscriptionsResponse( - subscriptions=[], - next_page_token='def', - ), - pubsub.ListTopicSubscriptionsResponse( - subscriptions=[ - str(), - ], - next_page_token='ghi', - ), - pubsub.ListTopicSubscriptionsResponse( - subscriptions=[ - str(), - str(), - ], - ), - RuntimeError, - ) - pages = list(client.list_topic_subscriptions(request={}).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - -@pytest.mark.asyncio -async def test_list_topic_subscriptions_async_pager(): - client = PublisherAsyncClient( - credentials=credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_topic_subscriptions), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - pubsub.ListTopicSubscriptionsResponse( - subscriptions=[ - str(), - str(), - str(), - ], - next_page_token='abc', - ), - pubsub.ListTopicSubscriptionsResponse( - subscriptions=[], - next_page_token='def', - ), - pubsub.ListTopicSubscriptionsResponse( - subscriptions=[ - str(), - ], - next_page_token='ghi', - ), - pubsub.ListTopicSubscriptionsResponse( - subscriptions=[ - str(), - str(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_topic_subscriptions(request={},) - assert async_pager.next_page_token == 'abc' - responses = [] - async for response in async_pager: - responses.append(response) - - assert len(responses) == 6 - assert all(isinstance(i, str) - for i in responses) - -@pytest.mark.asyncio -async def test_list_topic_subscriptions_async_pages(): - client = PublisherAsyncClient( - credentials=credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_topic_subscriptions), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - pubsub.ListTopicSubscriptionsResponse( - subscriptions=[ - str(), - str(), - str(), - ], - next_page_token='abc', - ), - pubsub.ListTopicSubscriptionsResponse( - subscriptions=[], - next_page_token='def', - ), - pubsub.ListTopicSubscriptionsResponse( - subscriptions=[ - str(), - ], - next_page_token='ghi', - ), - pubsub.ListTopicSubscriptionsResponse( - subscriptions=[ - str(), - str(), - ], - ), - RuntimeError, - ) - pages = [] - async for page_ in (await client.list_topic_subscriptions(request={})).pages: - pages.append(page_) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -def test_list_topic_snapshots(transport: str = 'grpc', request_type=pubsub.ListTopicSnapshotsRequest): - client = PublisherClient( - credentials=credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_topic_snapshots), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = pubsub.ListTopicSnapshotsResponse( - snapshots=['snapshots_value'], - - next_page_token='next_page_token_value', - - ) - - response = client.list_topic_snapshots(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - - assert args[0] == pubsub.ListTopicSnapshotsRequest() - - # Establish that the response is the type that we expect. - - assert isinstance(response, pagers.ListTopicSnapshotsPager) - - assert response.snapshots == ['snapshots_value'] - - assert response.next_page_token == 'next_page_token_value' - - -def test_list_topic_snapshots_from_dict(): - test_list_topic_snapshots(request_type=dict) - - -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', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_topic_snapshots), - '__call__') as call: - client.list_topic_snapshots() - call.assert_called() - _, args, _ = call.mock_calls[0] - - assert args[0] == pubsub.ListTopicSnapshotsRequest() - -@pytest.mark.asyncio -async def test_list_topic_snapshots_async(transport: str = 'grpc_asyncio', request_type=pubsub.ListTopicSnapshotsRequest): - client = PublisherAsyncClient( - credentials=credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_topic_snapshots), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(pubsub.ListTopicSnapshotsResponse( - snapshots=['snapshots_value'], - next_page_token='next_page_token_value', - )) - - response = await client.list_topic_snapshots(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - - assert args[0] == pubsub.ListTopicSnapshotsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListTopicSnapshotsAsyncPager) - - assert response.snapshots == ['snapshots_value'] - - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_topic_snapshots_async_from_dict(): - await test_list_topic_snapshots_async(request_type=dict) - - -def test_list_topic_snapshots_field_headers(): - client = PublisherClient( - credentials=credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = pubsub.ListTopicSnapshotsRequest() - request.topic = 'topic/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_topic_snapshots), - '__call__') as call: - call.return_value = pubsub.ListTopicSnapshotsResponse() - - client.list_topic_snapshots(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'topic=topic/value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_list_topic_snapshots_field_headers_async(): - client = PublisherAsyncClient( - credentials=credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = pubsub.ListTopicSnapshotsRequest() - request.topic = 'topic/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_topic_snapshots), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(pubsub.ListTopicSnapshotsResponse()) - - await client.list_topic_snapshots(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'topic=topic/value', - ) in kw['metadata'] - - -def test_list_topic_snapshots_flattened(): - client = PublisherClient( - credentials=credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_topic_snapshots), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = pubsub.ListTopicSnapshotsResponse() - - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_topic_snapshots( - topic='topic_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - - assert args[0].topic == 'topic_value' - - -def test_list_topic_snapshots_flattened_error(): - client = PublisherClient( - credentials=credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.list_topic_snapshots( - pubsub.ListTopicSnapshotsRequest(), - topic='topic_value', - ) - - -@pytest.mark.asyncio -async def test_list_topic_snapshots_flattened_async(): - client = PublisherAsyncClient( - credentials=credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_topic_snapshots), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = pubsub.ListTopicSnapshotsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(pubsub.ListTopicSnapshotsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_topic_snapshots( - topic='topic_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - - assert args[0].topic == 'topic_value' - - -@pytest.mark.asyncio -async def test_list_topic_snapshots_flattened_error_async(): - client = PublisherAsyncClient( - credentials=credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.list_topic_snapshots( - pubsub.ListTopicSnapshotsRequest(), - topic='topic_value', - ) - - -def test_list_topic_snapshots_pager(): - client = PublisherClient( - credentials=credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_topic_snapshots), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - pubsub.ListTopicSnapshotsResponse( - snapshots=[ - str(), - str(), - str(), - ], - next_page_token='abc', - ), - pubsub.ListTopicSnapshotsResponse( - snapshots=[], - next_page_token='def', - ), - pubsub.ListTopicSnapshotsResponse( - snapshots=[ - str(), - ], - next_page_token='ghi', - ), - pubsub.ListTopicSnapshotsResponse( - snapshots=[ - str(), - str(), - ], - ), - RuntimeError, - ) - - metadata = () - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('topic', ''), - )), - ) - pager = client.list_topic_snapshots(request={}) - - assert pager._metadata == metadata - - results = [i for i in pager] - assert len(results) == 6 - assert all(isinstance(i, str) - for i in results) - -def test_list_topic_snapshots_pages(): - client = PublisherClient( - credentials=credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_topic_snapshots), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - pubsub.ListTopicSnapshotsResponse( - snapshots=[ - str(), - str(), - str(), - ], - next_page_token='abc', - ), - pubsub.ListTopicSnapshotsResponse( - snapshots=[], - next_page_token='def', - ), - pubsub.ListTopicSnapshotsResponse( - snapshots=[ - str(), - ], - next_page_token='ghi', - ), - pubsub.ListTopicSnapshotsResponse( - snapshots=[ - str(), - str(), - ], - ), - RuntimeError, - ) - pages = list(client.list_topic_snapshots(request={}).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - -@pytest.mark.asyncio -async def test_list_topic_snapshots_async_pager(): - client = PublisherAsyncClient( - credentials=credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_topic_snapshots), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - pubsub.ListTopicSnapshotsResponse( - snapshots=[ - str(), - str(), - str(), - ], - next_page_token='abc', - ), - pubsub.ListTopicSnapshotsResponse( - snapshots=[], - next_page_token='def', - ), - pubsub.ListTopicSnapshotsResponse( - snapshots=[ - str(), - ], - next_page_token='ghi', - ), - pubsub.ListTopicSnapshotsResponse( - snapshots=[ - str(), - str(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_topic_snapshots(request={},) - assert async_pager.next_page_token == 'abc' - responses = [] - async for response in async_pager: - responses.append(response) - - assert len(responses) == 6 - assert all(isinstance(i, str) - for i in responses) - -@pytest.mark.asyncio -async def test_list_topic_snapshots_async_pages(): - client = PublisherAsyncClient( - credentials=credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_topic_snapshots), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - pubsub.ListTopicSnapshotsResponse( - snapshots=[ - str(), - str(), - str(), - ], - next_page_token='abc', - ), - pubsub.ListTopicSnapshotsResponse( - snapshots=[], - next_page_token='def', - ), - pubsub.ListTopicSnapshotsResponse( - snapshots=[ - str(), - ], - next_page_token='ghi', - ), - pubsub.ListTopicSnapshotsResponse( - snapshots=[ - str(), - str(), - ], - ), - RuntimeError, - ) - pages = [] - async for page_ in (await client.list_topic_snapshots(request={})).pages: - pages.append(page_) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -def test_delete_topic(transport: str = 'grpc', request_type=pubsub.DeleteTopicRequest): - client = PublisherClient( - credentials=credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_topic), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = None - - response = client.delete_topic(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - - assert args[0] == pubsub.DeleteTopicRequest() - - # Establish that the response is the type that we expect. - assert response is None - - -def test_delete_topic_from_dict(): - test_delete_topic(request_type=dict) - - -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', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_topic), - '__call__') as call: - client.delete_topic() - call.assert_called() - _, args, _ = call.mock_calls[0] - - assert args[0] == pubsub.DeleteTopicRequest() - -@pytest.mark.asyncio -async def test_delete_topic_async(transport: str = 'grpc_asyncio', request_type=pubsub.DeleteTopicRequest): - client = PublisherAsyncClient( - credentials=credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_topic), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - - response = await client.delete_topic(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - - assert args[0] == pubsub.DeleteTopicRequest() - - # Establish that the response is the type that we expect. - assert response is None - - -@pytest.mark.asyncio -async def test_delete_topic_async_from_dict(): - await test_delete_topic_async(request_type=dict) - - -def test_delete_topic_field_headers(): - client = PublisherClient( - credentials=credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = pubsub.DeleteTopicRequest() - request.topic = 'topic/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_topic), - '__call__') as call: - call.return_value = None - - client.delete_topic(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'topic=topic/value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_delete_topic_field_headers_async(): - client = PublisherAsyncClient( - credentials=credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = pubsub.DeleteTopicRequest() - request.topic = 'topic/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_topic), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - - await client.delete_topic(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'topic=topic/value', - ) in kw['metadata'] - - -def test_delete_topic_flattened(): - client = PublisherClient( - credentials=credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_topic), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = None - - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.delete_topic( - topic='topic_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - - assert args[0].topic == 'topic_value' - - -def test_delete_topic_flattened_error(): - client = PublisherClient( - credentials=credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.delete_topic( - pubsub.DeleteTopicRequest(), - topic='topic_value', - ) - - -@pytest.mark.asyncio -async def test_delete_topic_flattened_async(): - client = PublisherAsyncClient( - credentials=credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_topic), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = None - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.delete_topic( - topic='topic_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - - assert args[0].topic == 'topic_value' - - -@pytest.mark.asyncio -async def test_delete_topic_flattened_error_async(): - client = PublisherAsyncClient( - credentials=credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.delete_topic( - pubsub.DeleteTopicRequest(), - topic='topic_value', - ) - - -def test_detach_subscription(transport: str = 'grpc', request_type=pubsub.DetachSubscriptionRequest): - client = PublisherClient( - credentials=credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.detach_subscription), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = pubsub.DetachSubscriptionResponse( - ) - - response = client.detach_subscription(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - - assert args[0] == pubsub.DetachSubscriptionRequest() - - # Establish that the response is the type that we expect. - - assert isinstance(response, pubsub.DetachSubscriptionResponse) - - -def test_detach_subscription_from_dict(): - test_detach_subscription(request_type=dict) - - -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', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.detach_subscription), - '__call__') as call: - client.detach_subscription() - call.assert_called() - _, args, _ = call.mock_calls[0] - - assert args[0] == pubsub.DetachSubscriptionRequest() - -@pytest.mark.asyncio -async def test_detach_subscription_async(transport: str = 'grpc_asyncio', request_type=pubsub.DetachSubscriptionRequest): - client = PublisherAsyncClient( - credentials=credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.detach_subscription), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(pubsub.DetachSubscriptionResponse( - )) - - response = await client.detach_subscription(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - - assert args[0] == pubsub.DetachSubscriptionRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pubsub.DetachSubscriptionResponse) - - -@pytest.mark.asyncio -async def test_detach_subscription_async_from_dict(): - await test_detach_subscription_async(request_type=dict) - - -def test_detach_subscription_field_headers(): - client = PublisherClient( - credentials=credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = pubsub.DetachSubscriptionRequest() - request.subscription = 'subscription/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.detach_subscription), - '__call__') as call: - call.return_value = pubsub.DetachSubscriptionResponse() - - client.detach_subscription(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'subscription=subscription/value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_detach_subscription_field_headers_async(): - client = PublisherAsyncClient( - credentials=credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = pubsub.DetachSubscriptionRequest() - request.subscription = 'subscription/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.detach_subscription), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(pubsub.DetachSubscriptionResponse()) - - await client.detach_subscription(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'subscription=subscription/value', - ) in kw['metadata'] - - -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.PublisherGrpcTransport( - credentials=credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = PublisherClient( - credentials=credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.PublisherGrpcTransport( - credentials=credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = PublisherClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.PublisherGrpcTransport( - credentials=credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = PublisherClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.PublisherGrpcTransport( - credentials=credentials.AnonymousCredentials(), - ) - client = PublisherClient(transport=transport) - assert client.transport is transport - - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.PublisherGrpcTransport( - credentials=credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.PublisherGrpcAsyncIOTransport( - credentials=credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - -@pytest.mark.parametrize("transport_class", [ - transports.PublisherGrpcTransport, - transports.PublisherGrpcAsyncIOTransport, -]) -def test_transport_adc(transport_class): - # Test default credentials are used if not provided. - with mock.patch.object(auth, 'default') as adc: - adc.return_value = (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(), - ) - 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): - transport = transports.PublisherTransport( - credentials=credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_publisher_base_transport(): - # Instantiate the base transport. - with mock.patch('google.pubsub_v1.services.publisher.transports.PublisherTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.PublisherTransport( - credentials=credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'create_topic', - 'update_topic', - 'publish', - 'get_topic', - 'list_topics', - 'list_topic_subscriptions', - 'list_topic_snapshots', - 'delete_topic', - 'detach_subscription', - 'set_iam_policy', - 'get_iam_policy', - 'test_iam_permissions', - ) - for method in methods: - with pytest.raises(NotImplementedError): - getattr(transport, method)(request=object()) - - -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') 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=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/pubsub', - ), - quota_project_id="octopus", - ) - - -def test_publisher_base_transport_with_adc(): - # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(auth, 'default') 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) - transport = transports.PublisherTransport() - adc.assert_called_once() - - -def test_publisher_auth_adc(): - # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(auth, 'default') as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) - PublisherClient() - adc.assert_called_once_with(scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/pubsub',), - quota_project_id=None, - ) - - -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') as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) - transports.PublisherGrpcTransport(host="squid.clam.whelk", quota_project_id="octopus") - adc.assert_called_once_with(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]) -def test_publisher_grpc_transport_client_cert_source_for_mtls( - transport_class -): - cred = credentials.AnonymousCredentials() - - # Check ssl_channel_credentials is used if provided. - with mock.patch.object(transport_class, "create_channel") as mock_create_channel: - mock_ssl_channel_creds = mock.Mock() - transport_class( - host="squid.clam.whelk", - credentials=cred, - ssl_channel_credentials=mock_ssl_channel_creds - ) - mock_create_channel.assert_called_once_with( - "squid.clam.whelk:443", - credentials=cred, - credentials_file=None, - scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/pubsub', - ), - ssl_credentials=mock_ssl_channel_creds, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls - # is used. - with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): - with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: - transport_class( - credentials=cred, - client_cert_source_for_mtls=client_cert_source_callback - ) - expected_cert, expected_key = client_cert_source_callback() - mock_ssl_cred.assert_called_once_with( - certificate_chain=expected_cert, - private_key=expected_key - ) - - -def test_publisher_host_no_port(): - client = PublisherClient( - credentials=credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='pubsub.googleapis.com'), - ) - assert client.transport._host == 'pubsub.googleapis.com:443' - - -def test_publisher_host_with_port(): - client = PublisherClient( - credentials=credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='pubsub.googleapis.com:8000'), - ) - assert client.transport._host == 'pubsub.googleapis.com:8000' - - -def test_publisher_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.PublisherGrpcTransport( - host="squid.clam.whelk", - channel=channel, - ) - assert transport.grpc_channel == channel - assert transport._host == "squid.clam.whelk:443" - assert transport._ssl_channel_credentials == None - - -def test_publisher_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.PublisherGrpcAsyncIOTransport( - host="squid.clam.whelk", - channel=channel, - ) - assert transport.grpc_channel == channel - assert transport._host == "squid.clam.whelk:443" - assert transport._ssl_channel_credentials == None - - -# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are -# removed from grpc/grpc_asyncio transport constructor. -@pytest.mark.parametrize("transport_class", [transports.PublisherGrpcTransport, transports.PublisherGrpcAsyncIOTransport]) -def test_publisher_transport_channel_mtls_with_client_cert_source( - transport_class -): - with mock.patch("grpc.ssl_channel_credentials", autospec=True) as grpc_ssl_channel_cred: - with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: - mock_ssl_cred = mock.Mock() - grpc_ssl_channel_cred.return_value = mock_ssl_cred - - mock_grpc_channel = mock.Mock() - grpc_create_channel.return_value = mock_grpc_channel - - cred = credentials.AnonymousCredentials() - with pytest.warns(DeprecationWarning): - with mock.patch.object(auth, 'default') as adc: - adc.return_value = (cred, None) - transport = transport_class( - host="squid.clam.whelk", - api_mtls_endpoint="mtls.squid.clam.whelk", - client_cert_source=client_cert_source_callback, - ) - adc.assert_called_once() - - grpc_ssl_channel_cred.assert_called_once_with( - certificate_chain=b"cert bytes", private_key=b"key bytes" - ) - grpc_create_channel.assert_called_once_with( - "mtls.squid.clam.whelk:443", - credentials=cred, - credentials_file=None, - scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/pubsub', - ), - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel - assert transport._ssl_channel_credentials == mock_ssl_cred - - -# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are -# removed from grpc/grpc_asyncio transport constructor. -@pytest.mark.parametrize("transport_class", [transports.PublisherGrpcTransport, transports.PublisherGrpcAsyncIOTransport]) -def test_publisher_transport_channel_mtls_with_adc( - transport_class -): - mock_ssl_cred = mock.Mock() - with mock.patch.multiple( - "google.auth.transport.grpc.SslCredentials", - __init__=mock.Mock(return_value=None), - ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), - ): - with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: - mock_grpc_channel = mock.Mock() - grpc_create_channel.return_value = mock_grpc_channel - mock_cred = mock.Mock() - - with pytest.warns(DeprecationWarning): - transport = transport_class( - host="squid.clam.whelk", - credentials=mock_cred, - api_mtls_endpoint="mtls.squid.clam.whelk", - client_cert_source=None, - ) - - grpc_create_channel.assert_called_once_with( - "mtls.squid.clam.whelk:443", - credentials=mock_cred, - credentials_file=None, - scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/pubsub', - ), - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel - - -def test_schema_path(): - project = "squid" - schema = "clam" - - expected = "projects/{project}/schemas/{schema}".format(project=project, schema=schema, ) - actual = PublisherClient.schema_path(project, schema) - assert expected == actual - - -def test_parse_schema_path(): - expected = { - "project": "whelk", - "schema": "octopus", - - } - path = PublisherClient.schema_path(**expected) - - # Check that the path construction is reversible. - actual = PublisherClient.parse_schema_path(path) - assert expected == actual - -def test_subscription_path(): - project = "oyster" - subscription = "nudibranch" - - expected = "projects/{project}/subscriptions/{subscription}".format(project=project, subscription=subscription, ) - actual = PublisherClient.subscription_path(project, subscription) - assert expected == actual - - -def test_parse_subscription_path(): - expected = { - "project": "cuttlefish", - "subscription": "mussel", - - } - path = PublisherClient.subscription_path(**expected) - - # Check that the path construction is reversible. - actual = PublisherClient.parse_subscription_path(path) - assert expected == actual - -def test_topic_path(): - project = "winkle" - topic = "nautilus" - - expected = "projects/{project}/topics/{topic}".format(project=project, topic=topic, ) - actual = PublisherClient.topic_path(project, topic) - assert expected == actual - - -def test_parse_topic_path(): - expected = { - "project": "scallop", - "topic": "abalone", - - } - path = PublisherClient.topic_path(**expected) - - # Check that the path construction is reversible. - actual = PublisherClient.parse_topic_path(path) - assert expected == actual - -def test_common_billing_account_path(): - billing_account = "squid" - - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = PublisherClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "clam", - - } - path = PublisherClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = PublisherClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "whelk" - - expected = "folders/{folder}".format(folder=folder, ) - actual = PublisherClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "octopus", - - } - path = PublisherClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = PublisherClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "oyster" - - expected = "organizations/{organization}".format(organization=organization, ) - actual = PublisherClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "nudibranch", - - } - path = PublisherClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = PublisherClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "cuttlefish" - - expected = "projects/{project}".format(project=project, ) - actual = PublisherClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "mussel", - - } - path = PublisherClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = PublisherClient.parse_common_project_path(path) - assert expected == actual - -def test_common_location_path(): - project = "winkle" - location = "nautilus" - - expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) - actual = PublisherClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "scallop", - "location": "abalone", - - } - path = PublisherClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = PublisherClient.parse_common_location_path(path) - assert expected == actual - - -def test_client_withDEFAULT_CLIENT_INFO(): - client_info = gapic_v1.client_info.ClientInfo() - - with mock.patch.object(transports.PublisherTransport, '_prep_wrapped_messages') as prep: - client = PublisherClient( - credentials=credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.PublisherTransport, '_prep_wrapped_messages') as prep: - transport_class = PublisherClient.get_transport_class() - transport = transport_class( - credentials=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, - ) - - # Everything is optional 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() - - # 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",) - - response = client.set_iam_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, policy.Policy) - - assert response.version == 774 - - assert response.etag == b"etag_blob" - - -@pytest.mark.asyncio -async def test_set_iam_policy_async(transport: str = "grpc_asyncio"): - client = PublisherAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional 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() - - # 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",) - ) - - response = await client.set_iam_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, policy.Policy) - - assert response.version == 774 - - assert response.etag == b"etag_blob" - - -def test_set_iam_policy_field_headers(): - client = PublisherClient( - credentials=credentials.AnonymousCredentials(), - ) - - # Any value 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.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() - - client.set_iam_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] - - -@pytest.mark.asyncio -async def test_set_iam_policy_field_headers_async(): - client = PublisherAsyncClient( - credentials=credentials.AnonymousCredentials(), - ) - - # Any value 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.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()) - - await client.set_iam_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] - - -def test_set_iam_policy_from_dict(): - client = PublisherClient( - credentials=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() - - response = client.set_iam_policy( - request={ - "resource": "resource_value", - "policy": policy.Policy(version=774), - } - ) - call.assert_called() - - -@pytest.mark.asyncio -async def test_set_iam_policy_from_dict_async(): - client = PublisherAsyncClient( - credentials=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() - ) - - response = await client.set_iam_policy( - request={ - "resource": "resource_value", - "policy": policy.Policy(version=774), - } - ) - call.assert_called() - - -def test_get_iam_policy(transport: str = "grpc"): - client = PublisherClient( - credentials=credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional 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() - - # 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",) - - response = client.get_iam_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, policy.Policy) - - assert response.version == 774 - - assert response.etag == b"etag_blob" - - -@pytest.mark.asyncio -async def test_get_iam_policy_async(transport: str = "grpc_asyncio"): - client = PublisherAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional 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() - - # 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",) - ) - - response = await client.get_iam_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, policy.Policy) - - assert response.version == 774 - - assert response.etag == b"etag_blob" - - -def test_get_iam_policy_field_headers(): - client = PublisherClient( - credentials=credentials.AnonymousCredentials(), - ) - - # Any value 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.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() - - client.get_iam_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] - - -@pytest.mark.asyncio -async def test_get_iam_policy_field_headers_async(): - client = PublisherAsyncClient( - credentials=credentials.AnonymousCredentials(), - ) - - # Any value 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.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()) - - await client.get_iam_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] - - -def test_get_iam_policy_from_dict(): - client = PublisherClient( - credentials=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() - - response = client.get_iam_policy( - request={ - "resource": "resource_value", - "options": options.GetPolicyOptions(requested_policy_version=2598), - } - ) - call.assert_called() - -@pytest.mark.asyncio -async def test_get_iam_policy_from_dict_async(): - client = PublisherAsyncClient( - credentials=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() - ) - - response = await client.get_iam_policy( - request={ - "resource": "resource_value", - "options": options.GetPolicyOptions(requested_policy_version=2598), - } - ) - call.assert_called() - - -def test_test_iam_permissions(transport: str = "grpc"): - client = PublisherClient( - credentials=credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional 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() - - # 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( - permissions=["permissions_value"], - ) - - response = client.test_iam_permissions(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, iam_policy.TestIamPermissionsResponse) - - assert response.permissions == ["permissions_value"] - - -@pytest.mark.asyncio -async def test_test_iam_permissions_async(transport: str = "grpc_asyncio"): - client = PublisherAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional 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() - - # 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(permissions=["permissions_value"],) - ) - - response = await client.test_iam_permissions(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, iam_policy.TestIamPermissionsResponse) - - assert response.permissions == ["permissions_value"] - - -def test_test_iam_permissions_field_headers(): - client = PublisherClient( - credentials=credentials.AnonymousCredentials(), - ) - - # Any value 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.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() - - client.test_iam_permissions(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] - - -@pytest.mark.asyncio -async def test_test_iam_permissions_field_headers_async(): - client = PublisherAsyncClient( - credentials=credentials.AnonymousCredentials(), - ) - - # Any value 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.resource = "resource/value" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.test_iam_permissions), "__call__" - ) as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - iam_policy.TestIamPermissionsResponse() - ) - - await client.test_iam_permissions(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] - - -def test_test_iam_permissions_from_dict(): - client = PublisherClient( - credentials=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() - - response = client.test_iam_permissions( - request={ - "resource": "resource_value", - "permissions": ["permissions_value"], - } - ) - call.assert_called() - -@pytest.mark.asyncio -async def test_test_iam_permissions_from_dict_async(): - client = PublisherAsyncClient( - credentials=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() - ) - - response = await client.test_iam_permissions( - request={ - "resource": "resource_value", - "permissions": ["permissions_value"], - } - ) - call.assert_called() diff --git a/owl-bot-staging/v1/tests/unit/gapic/pubsub_v1/test_schema_service.py b/owl-bot-staging/v1/tests/unit/gapic/pubsub_v1/test_schema_service.py deleted file mode 100644 index 400aa87f6..000000000 --- a/owl-bot-staging/v1/tests/unit/gapic/pubsub_v1/test_schema_service.py +++ /dev/null @@ -1,2900 +0,0 @@ -# -*- coding: utf-8 -*- - -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -import os -import mock - -import grpc -from grpc.experimental import aio -import math -import pytest -from proto.marshal.rules.dates import DurationRule, TimestampRule - -from google import auth -from google.api_core import client_options -from google.api_core import 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.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.oauth2 import service_account -from google.pubsub_v1.services.schema_service import SchemaServiceAsyncClient -from google.pubsub_v1.services.schema_service import SchemaServiceClient -from google.pubsub_v1.services.schema_service import pagers -from google.pubsub_v1.services.schema_service import transports -from google.pubsub_v1.types import schema -from google.pubsub_v1.types import schema as gp_schema - - -def client_cert_source_callback(): - return b"cert bytes", b"key bytes" - - -# If default endpoint is localhost, then default mtls endpoint will be the same. -# This method modifies the default endpoint so the client can produce a different -# mtls endpoint for endpoint testing purposes. -def modify_default_endpoint(client): - return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT - - -def test__get_default_mtls_endpoint(): - api_endpoint = "example.googleapis.com" - api_mtls_endpoint = "example.mtls.googleapis.com" - sandbox_endpoint = "example.sandbox.googleapis.com" - sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" - non_googleapi = "api.example.com" - - assert SchemaServiceClient._get_default_mtls_endpoint(None) is None - assert SchemaServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert SchemaServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert SchemaServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert SchemaServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert SchemaServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - - -@pytest.mark.parametrize("client_class", [ - SchemaServiceClient, - SchemaServiceAsyncClient, -]) -def test_schema_service_client_from_service_account_info(client_class): - creds = credentials.AnonymousCredentials() - with mock.patch.object(service_account.Credentials, 'from_service_account_info') as factory: - factory.return_value = creds - info = {"valid": True} - client = client_class.from_service_account_info(info) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == 'pubsub.googleapis.com:443' - - -@pytest.mark.parametrize("client_class", [ - SchemaServiceClient, - SchemaServiceAsyncClient, -]) -def test_schema_service_client_from_service_account_file(client_class): - creds = credentials.AnonymousCredentials() - with mock.patch.object(service_account.Credentials, 'from_service_account_file') as factory: - factory.return_value = creds - client = client_class.from_service_account_file("dummy/file/path.json") - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - client = client_class.from_service_account_json("dummy/file/path.json") - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == 'pubsub.googleapis.com:443' - - -def test_schema_service_client_get_transport_class(): - transport = SchemaServiceClient.get_transport_class() - available_transports = [ - transports.SchemaServiceGrpcTransport, - ] - assert transport in available_transports - - transport = SchemaServiceClient.get_transport_class("grpc") - assert transport == transports.SchemaServiceGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (SchemaServiceClient, transports.SchemaServiceGrpcTransport, "grpc"), - (SchemaServiceAsyncClient, transports.SchemaServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -@mock.patch.object(SchemaServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SchemaServiceClient)) -@mock.patch.object(SchemaServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SchemaServiceAsyncClient)) -def test_schema_service_client_client_options(client_class, transport_class, transport_name): - # Check that if channel is provided we won't create a new one. - with mock.patch.object(SchemaServiceClient, 'get_transport_class') as gtc: - transport = transport_class( - credentials=credentials.AnonymousCredentials() - ) - client = client_class(transport=transport) - gtc.assert_not_called() - - # Check that if channel is provided via str we will create a new one. - with mock.patch.object(SchemaServiceClient, 'get_transport_class') as gtc: - client = client_class(transport=transport_name) - gtc.assert_called() - - # Check the case api_endpoint is provided. - options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class() - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class() - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_MTLS_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has - # unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError): - client = client_class() - - # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError): - client = client_class() - - # Check the case quota_project_id is provided - options = client_options.ClientOptions(quota_project_id="octopus") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id="octopus", - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ - - (SchemaServiceClient, transports.SchemaServiceGrpcTransport, "grpc", "true"), - (SchemaServiceAsyncClient, transports.SchemaServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (SchemaServiceClient, transports.SchemaServiceGrpcTransport, "grpc", "false"), - (SchemaServiceAsyncClient, transports.SchemaServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), - -]) -@mock.patch.object(SchemaServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SchemaServiceClient)) -@mock.patch.object(SchemaServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SchemaServiceAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_schema_service_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): - # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default - # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. - - # Check the case client_cert_source is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options) - - if use_client_cert_env == "false": - expected_client_cert_source = None - expected_host = client.DEFAULT_ENDPOINT - else: - expected_client_cert_source = client_cert_source_callback - expected_host = client.DEFAULT_MTLS_ENDPOINT - - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - - # Check the case ADC client cert is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): - if use_client_cert_env == "false": - expected_host = client.DEFAULT_ENDPOINT - expected_client_cert_source = None - else: - expected_host = client.DEFAULT_MTLS_ENDPOINT - expected_client_cert_source = client_cert_source_callback - - patched.return_value = None - client = client_class() - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - - # Check the case client_cert_source and ADC client cert are not provided. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): - patched.return_value = None - client = client_class() - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (SchemaServiceClient, transports.SchemaServiceGrpcTransport, "grpc"), - (SchemaServiceAsyncClient, transports.SchemaServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_schema_service_client_client_options_scopes(client_class, transport_class, transport_name): - # Check the case scopes are provided. - options = client_options.ClientOptions( - scopes=["1", "2"], - ) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=["1", "2"], - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (SchemaServiceClient, transports.SchemaServiceGrpcTransport, "grpc"), - (SchemaServiceAsyncClient, transports.SchemaServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_schema_service_client_client_options_credentials_file(client_class, transport_class, transport_name): - # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - - -def test_schema_service_client_client_options_from_dict(): - with mock.patch('google.pubsub_v1.services.schema_service.transports.SchemaServiceGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = SchemaServiceClient( - client_options={'api_endpoint': 'squid.clam.whelk'} - ) - grpc_transport.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - - -def test_create_schema(transport: str = 'grpc', request_type=gp_schema.CreateSchemaRequest): - client = SchemaServiceClient( - credentials=credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_schema), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gp_schema.Schema( - name='name_value', - - type_=gp_schema.Schema.Type.PROTOCOL_BUFFER, - - definition='definition_value', - - ) - - response = client.create_schema(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - - assert args[0] == gp_schema.CreateSchemaRequest() - - # Establish that the response is the type that we expect. - - assert isinstance(response, gp_schema.Schema) - - assert response.name == 'name_value' - - assert response.type_ == gp_schema.Schema.Type.PROTOCOL_BUFFER - - assert response.definition == 'definition_value' - - -def test_create_schema_from_dict(): - test_create_schema(request_type=dict) - - -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', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_schema), - '__call__') as call: - client.create_schema() - call.assert_called() - _, args, _ = call.mock_calls[0] - - assert args[0] == gp_schema.CreateSchemaRequest() - -@pytest.mark.asyncio -async def test_create_schema_async(transport: str = 'grpc_asyncio', request_type=gp_schema.CreateSchemaRequest): - client = SchemaServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_schema), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gp_schema.Schema( - name='name_value', - type_=gp_schema.Schema.Type.PROTOCOL_BUFFER, - definition='definition_value', - )) - - response = await client.create_schema(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - - assert args[0] == gp_schema.CreateSchemaRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gp_schema.Schema) - - assert response.name == 'name_value' - - assert response.type_ == gp_schema.Schema.Type.PROTOCOL_BUFFER - - assert response.definition == 'definition_value' - - -@pytest.mark.asyncio -async def test_create_schema_async_from_dict(): - await test_create_schema_async(request_type=dict) - - -def test_create_schema_field_headers(): - client = SchemaServiceClient( - credentials=credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = gp_schema.CreateSchemaRequest() - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_schema), - '__call__') as call: - call.return_value = gp_schema.Schema() - - client.create_schema(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent/value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_create_schema_field_headers_async(): - client = SchemaServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = gp_schema.CreateSchemaRequest() - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_schema), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gp_schema.Schema()) - - await client.create_schema(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent/value', - ) in kw['metadata'] - - -def test_create_schema_flattened(): - client = SchemaServiceClient( - credentials=credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_schema), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gp_schema.Schema() - - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.create_schema( - parent='parent_value', - schema=gp_schema.Schema(name='name_value'), - schema_id='schema_id_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - - 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(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.create_schema( - gp_schema.CreateSchemaRequest(), - parent='parent_value', - schema=gp_schema.Schema(name='name_value'), - schema_id='schema_id_value', - ) - - -@pytest.mark.asyncio -async def test_create_schema_flattened_async(): - client = SchemaServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_schema), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gp_schema.Schema() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gp_schema.Schema()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.create_schema( - parent='parent_value', - schema=gp_schema.Schema(name='name_value'), - schema_id='schema_id_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - - 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(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.create_schema( - gp_schema.CreateSchemaRequest(), - parent='parent_value', - schema=gp_schema.Schema(name='name_value'), - schema_id='schema_id_value', - ) - - -def test_get_schema(transport: str = 'grpc', request_type=schema.GetSchemaRequest): - client = SchemaServiceClient( - credentials=credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_schema), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = schema.Schema( - name='name_value', - - type_=schema.Schema.Type.PROTOCOL_BUFFER, - - definition='definition_value', - - ) - - response = client.get_schema(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - - assert args[0] == schema.GetSchemaRequest() - - # Establish that the response is the type that we expect. - - assert isinstance(response, schema.Schema) - - assert response.name == 'name_value' - - assert response.type_ == schema.Schema.Type.PROTOCOL_BUFFER - - assert response.definition == 'definition_value' - - -def test_get_schema_from_dict(): - test_get_schema(request_type=dict) - - -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', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_schema), - '__call__') as call: - client.get_schema() - call.assert_called() - _, args, _ = call.mock_calls[0] - - assert args[0] == schema.GetSchemaRequest() - -@pytest.mark.asyncio -async def test_get_schema_async(transport: str = 'grpc_asyncio', request_type=schema.GetSchemaRequest): - client = SchemaServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_schema), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(schema.Schema( - name='name_value', - type_=schema.Schema.Type.PROTOCOL_BUFFER, - definition='definition_value', - )) - - response = await client.get_schema(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - - assert args[0] == schema.GetSchemaRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, schema.Schema) - - assert response.name == 'name_value' - - assert response.type_ == schema.Schema.Type.PROTOCOL_BUFFER - - assert response.definition == 'definition_value' - - -@pytest.mark.asyncio -async def test_get_schema_async_from_dict(): - await test_get_schema_async(request_type=dict) - - -def test_get_schema_field_headers(): - client = SchemaServiceClient( - credentials=credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = schema.GetSchemaRequest() - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_schema), - '__call__') as call: - call.return_value = schema.Schema() - - client.get_schema(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name/value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_get_schema_field_headers_async(): - client = SchemaServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = schema.GetSchemaRequest() - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_schema), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(schema.Schema()) - - await client.get_schema(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name/value', - ) in kw['metadata'] - - -def test_get_schema_flattened(): - client = SchemaServiceClient( - credentials=credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_schema), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = schema.Schema() - - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_schema( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - - assert args[0].name == 'name_value' - - -def test_get_schema_flattened_error(): - client = SchemaServiceClient( - credentials=credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.get_schema( - schema.GetSchemaRequest(), - name='name_value', - ) - - -@pytest.mark.asyncio -async def test_get_schema_flattened_async(): - client = SchemaServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_schema), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = schema.Schema() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(schema.Schema()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_schema( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - - assert args[0].name == 'name_value' - - -@pytest.mark.asyncio -async def test_get_schema_flattened_error_async(): - client = SchemaServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.get_schema( - schema.GetSchemaRequest(), - name='name_value', - ) - - -def test_list_schemas(transport: str = 'grpc', request_type=schema.ListSchemasRequest): - client = SchemaServiceClient( - credentials=credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_schemas), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = schema.ListSchemasResponse( - next_page_token='next_page_token_value', - - ) - - response = client.list_schemas(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - - assert args[0] == schema.ListSchemasRequest() - - # Establish that the response is the type that we expect. - - assert isinstance(response, pagers.ListSchemasPager) - - assert response.next_page_token == 'next_page_token_value' - - -def test_list_schemas_from_dict(): - test_list_schemas(request_type=dict) - - -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', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_schemas), - '__call__') as call: - client.list_schemas() - call.assert_called() - _, args, _ = call.mock_calls[0] - - assert args[0] == schema.ListSchemasRequest() - -@pytest.mark.asyncio -async def test_list_schemas_async(transport: str = 'grpc_asyncio', request_type=schema.ListSchemasRequest): - client = SchemaServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_schemas), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(schema.ListSchemasResponse( - next_page_token='next_page_token_value', - )) - - response = await client.list_schemas(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - - assert args[0] == schema.ListSchemasRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListSchemasAsyncPager) - - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_schemas_async_from_dict(): - await test_list_schemas_async(request_type=dict) - - -def test_list_schemas_field_headers(): - client = SchemaServiceClient( - credentials=credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = schema.ListSchemasRequest() - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_schemas), - '__call__') as call: - call.return_value = schema.ListSchemasResponse() - - client.list_schemas(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent/value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_list_schemas_field_headers_async(): - client = SchemaServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = schema.ListSchemasRequest() - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_schemas), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(schema.ListSchemasResponse()) - - await client.list_schemas(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent/value', - ) in kw['metadata'] - - -def test_list_schemas_flattened(): - client = SchemaServiceClient( - credentials=credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_schemas), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = schema.ListSchemasResponse() - - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_schemas( - parent='parent_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - - assert args[0].parent == 'parent_value' - - -def test_list_schemas_flattened_error(): - client = SchemaServiceClient( - credentials=credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.list_schemas( - schema.ListSchemasRequest(), - parent='parent_value', - ) - - -@pytest.mark.asyncio -async def test_list_schemas_flattened_async(): - client = SchemaServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_schemas), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = schema.ListSchemasResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(schema.ListSchemasResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_schemas( - parent='parent_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - - assert args[0].parent == 'parent_value' - - -@pytest.mark.asyncio -async def test_list_schemas_flattened_error_async(): - client = SchemaServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.list_schemas( - schema.ListSchemasRequest(), - parent='parent_value', - ) - - -def test_list_schemas_pager(): - client = SchemaServiceClient( - credentials=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: - # Set the response to a series of pages. - call.side_effect = ( - schema.ListSchemasResponse( - schemas=[ - schema.Schema(), - schema.Schema(), - schema.Schema(), - ], - next_page_token='abc', - ), - schema.ListSchemasResponse( - schemas=[], - next_page_token='def', - ), - schema.ListSchemasResponse( - schemas=[ - schema.Schema(), - ], - next_page_token='ghi', - ), - schema.ListSchemasResponse( - schemas=[ - schema.Schema(), - schema.Schema(), - ], - ), - RuntimeError, - ) - - metadata = () - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_schemas(request={}) - - assert pager._metadata == metadata - - results = [i for i in pager] - assert len(results) == 6 - assert all(isinstance(i, schema.Schema) - for i in results) - -def test_list_schemas_pages(): - client = SchemaServiceClient( - credentials=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: - # Set the response to a series of pages. - call.side_effect = ( - schema.ListSchemasResponse( - schemas=[ - schema.Schema(), - schema.Schema(), - schema.Schema(), - ], - next_page_token='abc', - ), - schema.ListSchemasResponse( - schemas=[], - next_page_token='def', - ), - schema.ListSchemasResponse( - schemas=[ - schema.Schema(), - ], - next_page_token='ghi', - ), - schema.ListSchemasResponse( - schemas=[ - schema.Schema(), - schema.Schema(), - ], - ), - RuntimeError, - ) - pages = list(client.list_schemas(request={}).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - -@pytest.mark.asyncio -async def test_list_schemas_async_pager(): - client = SchemaServiceAsyncClient( - credentials=credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_schemas), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - schema.ListSchemasResponse( - schemas=[ - schema.Schema(), - schema.Schema(), - schema.Schema(), - ], - next_page_token='abc', - ), - schema.ListSchemasResponse( - schemas=[], - next_page_token='def', - ), - schema.ListSchemasResponse( - schemas=[ - schema.Schema(), - ], - next_page_token='ghi', - ), - schema.ListSchemasResponse( - schemas=[ - schema.Schema(), - schema.Schema(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_schemas(request={},) - assert async_pager.next_page_token == 'abc' - responses = [] - async for response in async_pager: - responses.append(response) - - assert len(responses) == 6 - assert all(isinstance(i, schema.Schema) - for i in responses) - -@pytest.mark.asyncio -async def test_list_schemas_async_pages(): - client = SchemaServiceAsyncClient( - credentials=credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_schemas), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - schema.ListSchemasResponse( - schemas=[ - schema.Schema(), - schema.Schema(), - schema.Schema(), - ], - next_page_token='abc', - ), - schema.ListSchemasResponse( - schemas=[], - next_page_token='def', - ), - schema.ListSchemasResponse( - schemas=[ - schema.Schema(), - ], - next_page_token='ghi', - ), - schema.ListSchemasResponse( - schemas=[ - schema.Schema(), - schema.Schema(), - ], - ), - RuntimeError, - ) - pages = [] - async for page_ in (await client.list_schemas(request={})).pages: - pages.append(page_) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -def test_delete_schema(transport: str = 'grpc', request_type=schema.DeleteSchemaRequest): - client = SchemaServiceClient( - credentials=credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_schema), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = None - - response = client.delete_schema(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - - assert args[0] == schema.DeleteSchemaRequest() - - # Establish that the response is the type that we expect. - assert response is None - - -def test_delete_schema_from_dict(): - test_delete_schema(request_type=dict) - - -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', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_schema), - '__call__') as call: - client.delete_schema() - call.assert_called() - _, args, _ = call.mock_calls[0] - - assert args[0] == schema.DeleteSchemaRequest() - -@pytest.mark.asyncio -async def test_delete_schema_async(transport: str = 'grpc_asyncio', request_type=schema.DeleteSchemaRequest): - client = SchemaServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_schema), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - - response = await client.delete_schema(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - - assert args[0] == schema.DeleteSchemaRequest() - - # Establish that the response is the type that we expect. - assert response is None - - -@pytest.mark.asyncio -async def test_delete_schema_async_from_dict(): - await test_delete_schema_async(request_type=dict) - - -def test_delete_schema_field_headers(): - client = SchemaServiceClient( - credentials=credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = schema.DeleteSchemaRequest() - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_schema), - '__call__') as call: - call.return_value = None - - client.delete_schema(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name/value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_delete_schema_field_headers_async(): - client = SchemaServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = schema.DeleteSchemaRequest() - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_schema), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - - await client.delete_schema(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name/value', - ) in kw['metadata'] - - -def test_delete_schema_flattened(): - client = SchemaServiceClient( - credentials=credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_schema), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = None - - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.delete_schema( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - - assert args[0].name == 'name_value' - - -def test_delete_schema_flattened_error(): - client = SchemaServiceClient( - credentials=credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.delete_schema( - schema.DeleteSchemaRequest(), - name='name_value', - ) - - -@pytest.mark.asyncio -async def test_delete_schema_flattened_async(): - client = SchemaServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_schema), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = None - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.delete_schema( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - - assert args[0].name == 'name_value' - - -@pytest.mark.asyncio -async def test_delete_schema_flattened_error_async(): - client = SchemaServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.delete_schema( - schema.DeleteSchemaRequest(), - name='name_value', - ) - - -def test_validate_schema(transport: str = 'grpc', request_type=gp_schema.ValidateSchemaRequest): - client = SchemaServiceClient( - credentials=credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.validate_schema), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gp_schema.ValidateSchemaResponse( - ) - - response = client.validate_schema(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - - assert args[0] == gp_schema.ValidateSchemaRequest() - - # Establish that the response is the type that we expect. - - assert isinstance(response, gp_schema.ValidateSchemaResponse) - - -def test_validate_schema_from_dict(): - test_validate_schema(request_type=dict) - - -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', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.validate_schema), - '__call__') as call: - client.validate_schema() - call.assert_called() - _, args, _ = call.mock_calls[0] - - assert args[0] == gp_schema.ValidateSchemaRequest() - -@pytest.mark.asyncio -async def test_validate_schema_async(transport: str = 'grpc_asyncio', request_type=gp_schema.ValidateSchemaRequest): - client = SchemaServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.validate_schema), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gp_schema.ValidateSchemaResponse( - )) - - response = await client.validate_schema(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - - assert args[0] == gp_schema.ValidateSchemaRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gp_schema.ValidateSchemaResponse) - - -@pytest.mark.asyncio -async def test_validate_schema_async_from_dict(): - await test_validate_schema_async(request_type=dict) - - -def test_validate_schema_field_headers(): - client = SchemaServiceClient( - credentials=credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = gp_schema.ValidateSchemaRequest() - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.validate_schema), - '__call__') as call: - call.return_value = gp_schema.ValidateSchemaResponse() - - client.validate_schema(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent/value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_validate_schema_field_headers_async(): - client = SchemaServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = gp_schema.ValidateSchemaRequest() - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.validate_schema), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gp_schema.ValidateSchemaResponse()) - - await client.validate_schema(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent/value', - ) in kw['metadata'] - - -def test_validate_schema_flattened(): - client = SchemaServiceClient( - credentials=credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.validate_schema), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gp_schema.ValidateSchemaResponse() - - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.validate_schema( - parent='parent_value', - schema=gp_schema.Schema(name='name_value'), - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - - 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(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.validate_schema( - gp_schema.ValidateSchemaRequest(), - parent='parent_value', - schema=gp_schema.Schema(name='name_value'), - ) - - -@pytest.mark.asyncio -async def test_validate_schema_flattened_async(): - client = SchemaServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.validate_schema), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gp_schema.ValidateSchemaResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gp_schema.ValidateSchemaResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.validate_schema( - parent='parent_value', - schema=gp_schema.Schema(name='name_value'), - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - - 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(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.validate_schema( - gp_schema.ValidateSchemaRequest(), - parent='parent_value', - schema=gp_schema.Schema(name='name_value'), - ) - - -def test_validate_message(transport: str = 'grpc', request_type=schema.ValidateMessageRequest): - client = SchemaServiceClient( - credentials=credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.validate_message), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = schema.ValidateMessageResponse( - ) - - response = client.validate_message(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - - assert args[0] == schema.ValidateMessageRequest() - - # Establish that the response is the type that we expect. - - assert isinstance(response, schema.ValidateMessageResponse) - - -def test_validate_message_from_dict(): - test_validate_message(request_type=dict) - - -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', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.validate_message), - '__call__') as call: - client.validate_message() - call.assert_called() - _, args, _ = call.mock_calls[0] - - assert args[0] == schema.ValidateMessageRequest() - -@pytest.mark.asyncio -async def test_validate_message_async(transport: str = 'grpc_asyncio', request_type=schema.ValidateMessageRequest): - client = SchemaServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.validate_message), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(schema.ValidateMessageResponse( - )) - - response = await client.validate_message(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - - assert args[0] == schema.ValidateMessageRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, schema.ValidateMessageResponse) - - -@pytest.mark.asyncio -async def test_validate_message_async_from_dict(): - await test_validate_message_async(request_type=dict) - - -def test_validate_message_field_headers(): - client = SchemaServiceClient( - credentials=credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = schema.ValidateMessageRequest() - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.validate_message), - '__call__') as call: - call.return_value = schema.ValidateMessageResponse() - - client.validate_message(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent/value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_validate_message_field_headers_async(): - client = SchemaServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = schema.ValidateMessageRequest() - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.validate_message), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(schema.ValidateMessageResponse()) - - await client.validate_message(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent/value', - ) in kw['metadata'] - - -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.SchemaServiceGrpcTransport( - credentials=credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = SchemaServiceClient( - credentials=credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.SchemaServiceGrpcTransport( - credentials=credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = SchemaServiceClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.SchemaServiceGrpcTransport( - credentials=credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = SchemaServiceClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.SchemaServiceGrpcTransport( - credentials=credentials.AnonymousCredentials(), - ) - client = SchemaServiceClient(transport=transport) - assert client.transport is transport - - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.SchemaServiceGrpcTransport( - credentials=credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.SchemaServiceGrpcAsyncIOTransport( - credentials=credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - -@pytest.mark.parametrize("transport_class", [ - transports.SchemaServiceGrpcTransport, - transports.SchemaServiceGrpcAsyncIOTransport, -]) -def test_transport_adc(transport_class): - # Test default credentials are used if not provided. - with mock.patch.object(auth, 'default') as adc: - adc.return_value = (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(), - ) - 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): - transport = transports.SchemaServiceTransport( - credentials=credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_schema_service_base_transport(): - # Instantiate the base transport. - with mock.patch('google.pubsub_v1.services.schema_service.transports.SchemaServiceTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.SchemaServiceTransport( - credentials=credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'create_schema', - 'get_schema', - 'list_schemas', - 'delete_schema', - 'validate_schema', - 'validate_message', - 'set_iam_policy', - 'get_iam_policy', - 'test_iam_permissions', - ) - for method in methods: - with pytest.raises(NotImplementedError): - getattr(transport, method)(request=object()) - - -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') 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=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/pubsub', - ), - quota_project_id="octopus", - ) - - -def test_schema_service_base_transport_with_adc(): - # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(auth, 'default') 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) - transport = transports.SchemaServiceTransport() - adc.assert_called_once() - - -def test_schema_service_auth_adc(): - # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(auth, 'default') as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) - SchemaServiceClient() - adc.assert_called_once_with(scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/pubsub',), - quota_project_id=None, - ) - - -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') as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) - transports.SchemaServiceGrpcTransport(host="squid.clam.whelk", quota_project_id="octopus") - adc.assert_called_once_with(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]) -def test_schema_service_grpc_transport_client_cert_source_for_mtls( - transport_class -): - cred = credentials.AnonymousCredentials() - - # Check ssl_channel_credentials is used if provided. - with mock.patch.object(transport_class, "create_channel") as mock_create_channel: - mock_ssl_channel_creds = mock.Mock() - transport_class( - host="squid.clam.whelk", - credentials=cred, - ssl_channel_credentials=mock_ssl_channel_creds - ) - mock_create_channel.assert_called_once_with( - "squid.clam.whelk:443", - credentials=cred, - credentials_file=None, - scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/pubsub', - ), - ssl_credentials=mock_ssl_channel_creds, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls - # is used. - with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): - with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: - transport_class( - credentials=cred, - client_cert_source_for_mtls=client_cert_source_callback - ) - expected_cert, expected_key = client_cert_source_callback() - mock_ssl_cred.assert_called_once_with( - certificate_chain=expected_cert, - private_key=expected_key - ) - - -def test_schema_service_host_no_port(): - client = SchemaServiceClient( - credentials=credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='pubsub.googleapis.com'), - ) - assert client.transport._host == 'pubsub.googleapis.com:443' - - -def test_schema_service_host_with_port(): - client = SchemaServiceClient( - credentials=credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='pubsub.googleapis.com:8000'), - ) - assert client.transport._host == 'pubsub.googleapis.com:8000' - - -def test_schema_service_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.SchemaServiceGrpcTransport( - host="squid.clam.whelk", - channel=channel, - ) - assert transport.grpc_channel == channel - assert transport._host == "squid.clam.whelk:443" - assert transport._ssl_channel_credentials == None - - -def test_schema_service_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.SchemaServiceGrpcAsyncIOTransport( - host="squid.clam.whelk", - channel=channel, - ) - assert transport.grpc_channel == channel - assert transport._host == "squid.clam.whelk:443" - assert transport._ssl_channel_credentials == None - - -# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are -# removed from grpc/grpc_asyncio transport constructor. -@pytest.mark.parametrize("transport_class", [transports.SchemaServiceGrpcTransport, transports.SchemaServiceGrpcAsyncIOTransport]) -def test_schema_service_transport_channel_mtls_with_client_cert_source( - transport_class -): - with mock.patch("grpc.ssl_channel_credentials", autospec=True) as grpc_ssl_channel_cred: - with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: - mock_ssl_cred = mock.Mock() - grpc_ssl_channel_cred.return_value = mock_ssl_cred - - mock_grpc_channel = mock.Mock() - grpc_create_channel.return_value = mock_grpc_channel - - cred = credentials.AnonymousCredentials() - with pytest.warns(DeprecationWarning): - with mock.patch.object(auth, 'default') as adc: - adc.return_value = (cred, None) - transport = transport_class( - host="squid.clam.whelk", - api_mtls_endpoint="mtls.squid.clam.whelk", - client_cert_source=client_cert_source_callback, - ) - adc.assert_called_once() - - grpc_ssl_channel_cred.assert_called_once_with( - certificate_chain=b"cert bytes", private_key=b"key bytes" - ) - grpc_create_channel.assert_called_once_with( - "mtls.squid.clam.whelk:443", - credentials=cred, - credentials_file=None, - scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/pubsub', - ), - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel - assert transport._ssl_channel_credentials == mock_ssl_cred - - -# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are -# removed from grpc/grpc_asyncio transport constructor. -@pytest.mark.parametrize("transport_class", [transports.SchemaServiceGrpcTransport, transports.SchemaServiceGrpcAsyncIOTransport]) -def test_schema_service_transport_channel_mtls_with_adc( - transport_class -): - mock_ssl_cred = mock.Mock() - with mock.patch.multiple( - "google.auth.transport.grpc.SslCredentials", - __init__=mock.Mock(return_value=None), - ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), - ): - with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: - mock_grpc_channel = mock.Mock() - grpc_create_channel.return_value = mock_grpc_channel - mock_cred = mock.Mock() - - with pytest.warns(DeprecationWarning): - transport = transport_class( - host="squid.clam.whelk", - credentials=mock_cred, - api_mtls_endpoint="mtls.squid.clam.whelk", - client_cert_source=None, - ) - - grpc_create_channel.assert_called_once_with( - "mtls.squid.clam.whelk:443", - credentials=mock_cred, - credentials_file=None, - scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/pubsub', - ), - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel - - -def test_schema_path(): - project = "squid" - schema = "clam" - - expected = "projects/{project}/schemas/{schema}".format(project=project, schema=schema, ) - actual = SchemaServiceClient.schema_path(project, schema) - assert expected == actual - - -def test_parse_schema_path(): - expected = { - "project": "whelk", - "schema": "octopus", - - } - path = SchemaServiceClient.schema_path(**expected) - - # Check that the path construction is reversible. - actual = SchemaServiceClient.parse_schema_path(path) - assert expected == actual - -def test_common_billing_account_path(): - billing_account = "oyster" - - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = SchemaServiceClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "nudibranch", - - } - path = SchemaServiceClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = SchemaServiceClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "cuttlefish" - - expected = "folders/{folder}".format(folder=folder, ) - actual = SchemaServiceClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "mussel", - - } - path = SchemaServiceClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = SchemaServiceClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "winkle" - - expected = "organizations/{organization}".format(organization=organization, ) - actual = SchemaServiceClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "nautilus", - - } - path = SchemaServiceClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = SchemaServiceClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "scallop" - - expected = "projects/{project}".format(project=project, ) - actual = SchemaServiceClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "abalone", - - } - path = SchemaServiceClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = SchemaServiceClient.parse_common_project_path(path) - assert expected == actual - -def test_common_location_path(): - project = "squid" - location = "clam" - - expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) - actual = SchemaServiceClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "whelk", - "location": "octopus", - - } - path = SchemaServiceClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = SchemaServiceClient.parse_common_location_path(path) - assert expected == actual - - -def test_client_withDEFAULT_CLIENT_INFO(): - client_info = gapic_v1.client_info.ClientInfo() - - with mock.patch.object(transports.SchemaServiceTransport, '_prep_wrapped_messages') as prep: - client = SchemaServiceClient( - credentials=credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.SchemaServiceTransport, '_prep_wrapped_messages') as prep: - transport_class = SchemaServiceClient.get_transport_class() - transport = transport_class( - credentials=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, - ) - - # Everything is optional 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() - - # 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",) - - response = client.set_iam_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, policy.Policy) - - assert response.version == 774 - - assert response.etag == b"etag_blob" - - -@pytest.mark.asyncio -async def test_set_iam_policy_async(transport: str = "grpc_asyncio"): - client = SchemaServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional 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() - - # 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",) - ) - - response = await client.set_iam_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, policy.Policy) - - assert response.version == 774 - - assert response.etag == b"etag_blob" - - -def test_set_iam_policy_field_headers(): - client = SchemaServiceClient( - credentials=credentials.AnonymousCredentials(), - ) - - # Any value 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.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() - - client.set_iam_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] - - -@pytest.mark.asyncio -async def test_set_iam_policy_field_headers_async(): - client = SchemaServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), - ) - - # Any value 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.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()) - - await client.set_iam_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] - - -def test_set_iam_policy_from_dict(): - client = SchemaServiceClient( - credentials=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() - - response = client.set_iam_policy( - request={ - "resource": "resource_value", - "policy": policy.Policy(version=774), - } - ) - call.assert_called() - - -@pytest.mark.asyncio -async def test_set_iam_policy_from_dict_async(): - client = SchemaServiceAsyncClient( - credentials=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() - ) - - response = await client.set_iam_policy( - request={ - "resource": "resource_value", - "policy": policy.Policy(version=774), - } - ) - call.assert_called() - - -def test_get_iam_policy(transport: str = "grpc"): - client = SchemaServiceClient( - credentials=credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional 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() - - # 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",) - - response = client.get_iam_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, policy.Policy) - - assert response.version == 774 - - assert response.etag == b"etag_blob" - - -@pytest.mark.asyncio -async def test_get_iam_policy_async(transport: str = "grpc_asyncio"): - client = SchemaServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional 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() - - # 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",) - ) - - response = await client.get_iam_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, policy.Policy) - - assert response.version == 774 - - assert response.etag == b"etag_blob" - - -def test_get_iam_policy_field_headers(): - client = SchemaServiceClient( - credentials=credentials.AnonymousCredentials(), - ) - - # Any value 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.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() - - client.get_iam_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] - - -@pytest.mark.asyncio -async def test_get_iam_policy_field_headers_async(): - client = SchemaServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), - ) - - # Any value 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.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()) - - await client.get_iam_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] - - -def test_get_iam_policy_from_dict(): - client = SchemaServiceClient( - credentials=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() - - response = client.get_iam_policy( - request={ - "resource": "resource_value", - "options": options.GetPolicyOptions(requested_policy_version=2598), - } - ) - call.assert_called() - -@pytest.mark.asyncio -async def test_get_iam_policy_from_dict_async(): - client = SchemaServiceAsyncClient( - credentials=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() - ) - - response = await client.get_iam_policy( - request={ - "resource": "resource_value", - "options": options.GetPolicyOptions(requested_policy_version=2598), - } - ) - call.assert_called() - - -def test_test_iam_permissions(transport: str = "grpc"): - client = SchemaServiceClient( - credentials=credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional 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() - - # 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( - permissions=["permissions_value"], - ) - - response = client.test_iam_permissions(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, iam_policy.TestIamPermissionsResponse) - - assert response.permissions == ["permissions_value"] - - -@pytest.mark.asyncio -async def test_test_iam_permissions_async(transport: str = "grpc_asyncio"): - client = SchemaServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional 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() - - # 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(permissions=["permissions_value"],) - ) - - response = await client.test_iam_permissions(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, iam_policy.TestIamPermissionsResponse) - - assert response.permissions == ["permissions_value"] - - -def test_test_iam_permissions_field_headers(): - client = SchemaServiceClient( - credentials=credentials.AnonymousCredentials(), - ) - - # Any value 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.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() - - client.test_iam_permissions(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] - - -@pytest.mark.asyncio -async def test_test_iam_permissions_field_headers_async(): - client = SchemaServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), - ) - - # Any value 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.resource = "resource/value" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.test_iam_permissions), "__call__" - ) as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - iam_policy.TestIamPermissionsResponse() - ) - - await client.test_iam_permissions(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] - - -def test_test_iam_permissions_from_dict(): - client = SchemaServiceClient( - credentials=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() - - response = client.test_iam_permissions( - request={ - "resource": "resource_value", - "permissions": ["permissions_value"], - } - ) - call.assert_called() - -@pytest.mark.asyncio -async def test_test_iam_permissions_from_dict_async(): - client = SchemaServiceAsyncClient( - credentials=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() - ) - - response = await client.test_iam_permissions( - request={ - "resource": "resource_value", - "permissions": ["permissions_value"], - } - ) - call.assert_called() diff --git a/owl-bot-staging/v1/tests/unit/gapic/pubsub_v1/test_subscriber.py b/owl-bot-staging/v1/tests/unit/gapic/pubsub_v1/test_subscriber.py deleted file mode 100644 index 08b27b565..000000000 --- a/owl-bot-staging/v1/tests/unit/gapic/pubsub_v1/test_subscriber.py +++ /dev/null @@ -1,5363 +0,0 @@ -# -*- coding: utf-8 -*- - -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -import os -import mock - -import grpc -from grpc.experimental import aio -import math -import pytest -from proto.marshal.rules.dates import DurationRule, TimestampRule - -from google import auth -from google.api_core import client_options -from google.api_core import 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.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.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.pubsub_v1.services.subscriber import SubscriberAsyncClient -from google.pubsub_v1.services.subscriber import SubscriberClient -from google.pubsub_v1.services.subscriber import pagers -from google.pubsub_v1.services.subscriber import transports -from google.pubsub_v1.types import pubsub - - -def client_cert_source_callback(): - return b"cert bytes", b"key bytes" - - -# If default endpoint is localhost, then default mtls endpoint will be the same. -# This method modifies the default endpoint so the client can produce a different -# mtls endpoint for endpoint testing purposes. -def modify_default_endpoint(client): - return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT - - -def test__get_default_mtls_endpoint(): - api_endpoint = "example.googleapis.com" - api_mtls_endpoint = "example.mtls.googleapis.com" - sandbox_endpoint = "example.sandbox.googleapis.com" - sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" - non_googleapi = "api.example.com" - - assert SubscriberClient._get_default_mtls_endpoint(None) is None - assert SubscriberClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert SubscriberClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert SubscriberClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert SubscriberClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert SubscriberClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - - -@pytest.mark.parametrize("client_class", [ - SubscriberClient, - SubscriberAsyncClient, -]) -def test_subscriber_client_from_service_account_info(client_class): - creds = credentials.AnonymousCredentials() - with mock.patch.object(service_account.Credentials, 'from_service_account_info') as factory: - factory.return_value = creds - info = {"valid": True} - client = client_class.from_service_account_info(info) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == 'pubsub.googleapis.com:443' - - -@pytest.mark.parametrize("client_class", [ - SubscriberClient, - SubscriberAsyncClient, -]) -def test_subscriber_client_from_service_account_file(client_class): - creds = credentials.AnonymousCredentials() - with mock.patch.object(service_account.Credentials, 'from_service_account_file') as factory: - factory.return_value = creds - client = client_class.from_service_account_file("dummy/file/path.json") - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - client = client_class.from_service_account_json("dummy/file/path.json") - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == 'pubsub.googleapis.com:443' - - -def test_subscriber_client_get_transport_class(): - transport = SubscriberClient.get_transport_class() - available_transports = [ - transports.SubscriberGrpcTransport, - ] - assert transport in available_transports - - transport = SubscriberClient.get_transport_class("grpc") - assert transport == transports.SubscriberGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (SubscriberClient, transports.SubscriberGrpcTransport, "grpc"), - (SubscriberAsyncClient, transports.SubscriberGrpcAsyncIOTransport, "grpc_asyncio"), -]) -@mock.patch.object(SubscriberClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SubscriberClient)) -@mock.patch.object(SubscriberAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SubscriberAsyncClient)) -def test_subscriber_client_client_options(client_class, transport_class, transport_name): - # Check that if channel is provided we won't create a new one. - with mock.patch.object(SubscriberClient, 'get_transport_class') as gtc: - transport = transport_class( - credentials=credentials.AnonymousCredentials() - ) - client = client_class(transport=transport) - gtc.assert_not_called() - - # Check that if channel is provided via str we will create a new one. - with mock.patch.object(SubscriberClient, 'get_transport_class') as gtc: - client = client_class(transport=transport_name) - gtc.assert_called() - - # Check the case api_endpoint is provided. - options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class() - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class() - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_MTLS_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has - # unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError): - client = client_class() - - # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError): - client = client_class() - - # Check the case quota_project_id is provided - options = client_options.ClientOptions(quota_project_id="octopus") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id="octopus", - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ - - (SubscriberClient, transports.SubscriberGrpcTransport, "grpc", "true"), - (SubscriberAsyncClient, transports.SubscriberGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (SubscriberClient, transports.SubscriberGrpcTransport, "grpc", "false"), - (SubscriberAsyncClient, transports.SubscriberGrpcAsyncIOTransport, "grpc_asyncio", "false"), - -]) -@mock.patch.object(SubscriberClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SubscriberClient)) -@mock.patch.object(SubscriberAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SubscriberAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_subscriber_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): - # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default - # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. - - # Check the case client_cert_source is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options) - - if use_client_cert_env == "false": - expected_client_cert_source = None - expected_host = client.DEFAULT_ENDPOINT - else: - expected_client_cert_source = client_cert_source_callback - expected_host = client.DEFAULT_MTLS_ENDPOINT - - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - - # Check the case ADC client cert is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): - if use_client_cert_env == "false": - expected_host = client.DEFAULT_ENDPOINT - expected_client_cert_source = None - else: - expected_host = client.DEFAULT_MTLS_ENDPOINT - expected_client_cert_source = client_cert_source_callback - - patched.return_value = None - client = client_class() - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - - # Check the case client_cert_source and ADC client cert are not provided. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): - patched.return_value = None - client = client_class() - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (SubscriberClient, transports.SubscriberGrpcTransport, "grpc"), - (SubscriberAsyncClient, transports.SubscriberGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_subscriber_client_client_options_scopes(client_class, transport_class, transport_name): - # Check the case scopes are provided. - options = client_options.ClientOptions( - scopes=["1", "2"], - ) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=["1", "2"], - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (SubscriberClient, transports.SubscriberGrpcTransport, "grpc"), - (SubscriberAsyncClient, transports.SubscriberGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_subscriber_client_client_options_credentials_file(client_class, transport_class, transport_name): - # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - - -def test_subscriber_client_client_options_from_dict(): - with mock.patch('google.pubsub_v1.services.subscriber.transports.SubscriberGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = SubscriberClient( - client_options={'api_endpoint': 'squid.clam.whelk'} - ) - grpc_transport.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - - -def test_create_subscription(transport: str = 'grpc', request_type=pubsub.Subscription): - client = SubscriberClient( - credentials=credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_subscription), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = pubsub.Subscription( - name='name_value', - - topic='topic_value', - - ack_deadline_seconds=2066, - - retain_acked_messages=True, - - enable_message_ordering=True, - - filter='filter_value', - - detached=True, - - ) - - 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 - - -def test_create_subscription_from_dict(): - test_create_subscription(request_type=dict) - - -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', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_subscription), - '__call__') as call: - client.create_subscription() - call.assert_called() - _, args, _ = call.mock_calls[0] - - assert args[0] == pubsub.Subscription() - -@pytest.mark.asyncio -async def test_create_subscription_async(transport: str = 'grpc_asyncio', request_type=pubsub.Subscription): - client = SubscriberAsyncClient( - credentials=credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_subscription), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(pubsub.Subscription( - name='name_value', - topic='topic_value', - ack_deadline_seconds=2066, - retain_acked_messages=True, - enable_message_ordering=True, - filter='filter_value', - detached=True, - )) - - 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 - - -@pytest.mark.asyncio -async def test_create_subscription_async_from_dict(): - await test_create_subscription_async(request_type=dict) - - -def test_create_subscription_field_headers(): - client = SubscriberClient( - credentials=credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = pubsub.Subscription() - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_subscription), - '__call__') as call: - call.return_value = pubsub.Subscription() - - client.create_subscription(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name/value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_create_subscription_field_headers_async(): - client = SubscriberAsyncClient( - credentials=credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = pubsub.Subscription() - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_subscription), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(pubsub.Subscription()) - - await client.create_subscription(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name/value', - ) in kw['metadata'] - - -def test_create_subscription_flattened(): - client = SubscriberClient( - credentials=credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_subscription), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = pubsub.Subscription() - - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.create_subscription( - name='name_value', - topic='topic_value', - push_config=pubsub.PushConfig(push_endpoint='push_endpoint_value'), - ack_deadline_seconds=2066, - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - - 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(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.create_subscription( - pubsub.Subscription(), - name='name_value', - topic='topic_value', - push_config=pubsub.PushConfig(push_endpoint='push_endpoint_value'), - ack_deadline_seconds=2066, - ) - - -@pytest.mark.asyncio -async def test_create_subscription_flattened_async(): - client = SubscriberAsyncClient( - credentials=credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_subscription), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = pubsub.Subscription() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(pubsub.Subscription()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.create_subscription( - name='name_value', - topic='topic_value', - push_config=pubsub.PushConfig(push_endpoint='push_endpoint_value'), - ack_deadline_seconds=2066, - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - - 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(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.create_subscription( - pubsub.Subscription(), - name='name_value', - topic='topic_value', - push_config=pubsub.PushConfig(push_endpoint='push_endpoint_value'), - ack_deadline_seconds=2066, - ) - - -def test_get_subscription(transport: str = 'grpc', request_type=pubsub.GetSubscriptionRequest): - client = SubscriberClient( - credentials=credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_subscription), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = pubsub.Subscription( - name='name_value', - - topic='topic_value', - - ack_deadline_seconds=2066, - - retain_acked_messages=True, - - enable_message_ordering=True, - - filter='filter_value', - - detached=True, - - ) - - 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 - - -def test_get_subscription_from_dict(): - test_get_subscription(request_type=dict) - - -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', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_subscription), - '__call__') as call: - client.get_subscription() - call.assert_called() - _, args, _ = call.mock_calls[0] - - assert args[0] == pubsub.GetSubscriptionRequest() - -@pytest.mark.asyncio -async def test_get_subscription_async(transport: str = 'grpc_asyncio', request_type=pubsub.GetSubscriptionRequest): - client = SubscriberAsyncClient( - credentials=credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_subscription), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(pubsub.Subscription( - name='name_value', - topic='topic_value', - ack_deadline_seconds=2066, - retain_acked_messages=True, - enable_message_ordering=True, - filter='filter_value', - detached=True, - )) - - 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 - - -@pytest.mark.asyncio -async def test_get_subscription_async_from_dict(): - await test_get_subscription_async(request_type=dict) - - -def test_get_subscription_field_headers(): - client = SubscriberClient( - credentials=credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = pubsub.GetSubscriptionRequest() - request.subscription = 'subscription/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_subscription), - '__call__') as call: - call.return_value = pubsub.Subscription() - - client.get_subscription(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'subscription=subscription/value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_get_subscription_field_headers_async(): - client = SubscriberAsyncClient( - credentials=credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = pubsub.GetSubscriptionRequest() - request.subscription = 'subscription/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_subscription), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(pubsub.Subscription()) - - await client.get_subscription(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'subscription=subscription/value', - ) in kw['metadata'] - - -def test_get_subscription_flattened(): - client = SubscriberClient( - credentials=credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_subscription), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = pubsub.Subscription() - - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_subscription( - subscription='subscription_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - - assert args[0].subscription == 'subscription_value' - - -def test_get_subscription_flattened_error(): - client = SubscriberClient( - credentials=credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.get_subscription( - pubsub.GetSubscriptionRequest(), - subscription='subscription_value', - ) - - -@pytest.mark.asyncio -async def test_get_subscription_flattened_async(): - client = SubscriberAsyncClient( - credentials=credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_subscription), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = pubsub.Subscription() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(pubsub.Subscription()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_subscription( - subscription='subscription_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - - assert args[0].subscription == 'subscription_value' - - -@pytest.mark.asyncio -async def test_get_subscription_flattened_error_async(): - client = SubscriberAsyncClient( - credentials=credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.get_subscription( - pubsub.GetSubscriptionRequest(), - subscription='subscription_value', - ) - - -def test_update_subscription(transport: str = 'grpc', request_type=pubsub.UpdateSubscriptionRequest): - client = SubscriberClient( - credentials=credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_subscription), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = pubsub.Subscription( - name='name_value', - - topic='topic_value', - - ack_deadline_seconds=2066, - - retain_acked_messages=True, - - enable_message_ordering=True, - - filter='filter_value', - - detached=True, - - ) - - 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 - - -def test_update_subscription_from_dict(): - test_update_subscription(request_type=dict) - - -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', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_subscription), - '__call__') as call: - client.update_subscription() - call.assert_called() - _, args, _ = call.mock_calls[0] - - assert args[0] == pubsub.UpdateSubscriptionRequest() - -@pytest.mark.asyncio -async def test_update_subscription_async(transport: str = 'grpc_asyncio', request_type=pubsub.UpdateSubscriptionRequest): - client = SubscriberAsyncClient( - credentials=credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_subscription), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(pubsub.Subscription( - name='name_value', - topic='topic_value', - ack_deadline_seconds=2066, - retain_acked_messages=True, - enable_message_ordering=True, - filter='filter_value', - detached=True, - )) - - 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 - - -@pytest.mark.asyncio -async def test_update_subscription_async_from_dict(): - await test_update_subscription_async(request_type=dict) - - -def test_update_subscription_field_headers(): - client = SubscriberClient( - credentials=credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = pubsub.UpdateSubscriptionRequest() - request.subscription.name = 'subscription.name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_subscription), - '__call__') as call: - call.return_value = pubsub.Subscription() - - client.update_subscription(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'subscription.name=subscription.name/value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_subscription_field_headers_async(): - client = SubscriberAsyncClient( - credentials=credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = pubsub.UpdateSubscriptionRequest() - request.subscription.name = 'subscription.name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_subscription), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(pubsub.Subscription()) - - await client.update_subscription(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'subscription.name=subscription.name/value', - ) in kw['metadata'] - - -def test_list_subscriptions(transport: str = 'grpc', request_type=pubsub.ListSubscriptionsRequest): - client = SubscriberClient( - credentials=credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_subscriptions), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = pubsub.ListSubscriptionsResponse( - next_page_token='next_page_token_value', - - ) - - response = client.list_subscriptions(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - - assert args[0] == pubsub.ListSubscriptionsRequest() - - # Establish that the response is the type that we expect. - - assert isinstance(response, pagers.ListSubscriptionsPager) - - assert response.next_page_token == 'next_page_token_value' - - -def test_list_subscriptions_from_dict(): - test_list_subscriptions(request_type=dict) - - -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', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_subscriptions), - '__call__') as call: - client.list_subscriptions() - call.assert_called() - _, args, _ = call.mock_calls[0] - - assert args[0] == pubsub.ListSubscriptionsRequest() - -@pytest.mark.asyncio -async def test_list_subscriptions_async(transport: str = 'grpc_asyncio', request_type=pubsub.ListSubscriptionsRequest): - client = SubscriberAsyncClient( - credentials=credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_subscriptions), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(pubsub.ListSubscriptionsResponse( - next_page_token='next_page_token_value', - )) - - response = await client.list_subscriptions(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - - assert args[0] == pubsub.ListSubscriptionsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListSubscriptionsAsyncPager) - - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_subscriptions_async_from_dict(): - await test_list_subscriptions_async(request_type=dict) - - -def test_list_subscriptions_field_headers(): - client = SubscriberClient( - credentials=credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = pubsub.ListSubscriptionsRequest() - request.project = 'project/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_subscriptions), - '__call__') as call: - call.return_value = pubsub.ListSubscriptionsResponse() - - client.list_subscriptions(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'project=project/value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_list_subscriptions_field_headers_async(): - client = SubscriberAsyncClient( - credentials=credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = pubsub.ListSubscriptionsRequest() - request.project = 'project/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_subscriptions), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(pubsub.ListSubscriptionsResponse()) - - await client.list_subscriptions(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'project=project/value', - ) in kw['metadata'] - - -def test_list_subscriptions_flattened(): - client = SubscriberClient( - credentials=credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_subscriptions), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = pubsub.ListSubscriptionsResponse() - - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_subscriptions( - project='project_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - - assert args[0].project == 'project_value' - - -def test_list_subscriptions_flattened_error(): - client = SubscriberClient( - credentials=credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.list_subscriptions( - pubsub.ListSubscriptionsRequest(), - project='project_value', - ) - - -@pytest.mark.asyncio -async def test_list_subscriptions_flattened_async(): - client = SubscriberAsyncClient( - credentials=credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_subscriptions), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = pubsub.ListSubscriptionsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(pubsub.ListSubscriptionsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_subscriptions( - project='project_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - - assert args[0].project == 'project_value' - - -@pytest.mark.asyncio -async def test_list_subscriptions_flattened_error_async(): - client = SubscriberAsyncClient( - credentials=credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.list_subscriptions( - pubsub.ListSubscriptionsRequest(), - project='project_value', - ) - - -def test_list_subscriptions_pager(): - client = SubscriberClient( - credentials=credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_subscriptions), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - pubsub.ListSubscriptionsResponse( - subscriptions=[ - pubsub.Subscription(), - pubsub.Subscription(), - pubsub.Subscription(), - ], - next_page_token='abc', - ), - pubsub.ListSubscriptionsResponse( - subscriptions=[], - next_page_token='def', - ), - pubsub.ListSubscriptionsResponse( - subscriptions=[ - pubsub.Subscription(), - ], - next_page_token='ghi', - ), - pubsub.ListSubscriptionsResponse( - subscriptions=[ - pubsub.Subscription(), - pubsub.Subscription(), - ], - ), - RuntimeError, - ) - - metadata = () - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('project', ''), - )), - ) - pager = client.list_subscriptions(request={}) - - assert pager._metadata == metadata - - results = [i for i in pager] - assert len(results) == 6 - assert all(isinstance(i, pubsub.Subscription) - for i in results) - -def test_list_subscriptions_pages(): - client = SubscriberClient( - credentials=credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_subscriptions), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - pubsub.ListSubscriptionsResponse( - subscriptions=[ - pubsub.Subscription(), - pubsub.Subscription(), - pubsub.Subscription(), - ], - next_page_token='abc', - ), - pubsub.ListSubscriptionsResponse( - subscriptions=[], - next_page_token='def', - ), - pubsub.ListSubscriptionsResponse( - subscriptions=[ - pubsub.Subscription(), - ], - next_page_token='ghi', - ), - pubsub.ListSubscriptionsResponse( - subscriptions=[ - pubsub.Subscription(), - pubsub.Subscription(), - ], - ), - RuntimeError, - ) - pages = list(client.list_subscriptions(request={}).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - -@pytest.mark.asyncio -async def test_list_subscriptions_async_pager(): - client = SubscriberAsyncClient( - credentials=credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_subscriptions), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - pubsub.ListSubscriptionsResponse( - subscriptions=[ - pubsub.Subscription(), - pubsub.Subscription(), - pubsub.Subscription(), - ], - next_page_token='abc', - ), - pubsub.ListSubscriptionsResponse( - subscriptions=[], - next_page_token='def', - ), - pubsub.ListSubscriptionsResponse( - subscriptions=[ - pubsub.Subscription(), - ], - next_page_token='ghi', - ), - pubsub.ListSubscriptionsResponse( - subscriptions=[ - pubsub.Subscription(), - pubsub.Subscription(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_subscriptions(request={},) - assert async_pager.next_page_token == 'abc' - responses = [] - async for response in async_pager: - responses.append(response) - - assert len(responses) == 6 - assert all(isinstance(i, pubsub.Subscription) - for i in responses) - -@pytest.mark.asyncio -async def test_list_subscriptions_async_pages(): - client = SubscriberAsyncClient( - credentials=credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_subscriptions), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - pubsub.ListSubscriptionsResponse( - subscriptions=[ - pubsub.Subscription(), - pubsub.Subscription(), - pubsub.Subscription(), - ], - next_page_token='abc', - ), - pubsub.ListSubscriptionsResponse( - subscriptions=[], - next_page_token='def', - ), - pubsub.ListSubscriptionsResponse( - subscriptions=[ - pubsub.Subscription(), - ], - next_page_token='ghi', - ), - pubsub.ListSubscriptionsResponse( - subscriptions=[ - pubsub.Subscription(), - pubsub.Subscription(), - ], - ), - RuntimeError, - ) - pages = [] - async for page_ in (await client.list_subscriptions(request={})).pages: - pages.append(page_) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -def test_delete_subscription(transport: str = 'grpc', request_type=pubsub.DeleteSubscriptionRequest): - client = SubscriberClient( - credentials=credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_subscription), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = None - - response = client.delete_subscription(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - - assert args[0] == pubsub.DeleteSubscriptionRequest() - - # Establish that the response is the type that we expect. - assert response is None - - -def test_delete_subscription_from_dict(): - test_delete_subscription(request_type=dict) - - -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', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_subscription), - '__call__') as call: - client.delete_subscription() - call.assert_called() - _, args, _ = call.mock_calls[0] - - assert args[0] == pubsub.DeleteSubscriptionRequest() - -@pytest.mark.asyncio -async def test_delete_subscription_async(transport: str = 'grpc_asyncio', request_type=pubsub.DeleteSubscriptionRequest): - client = SubscriberAsyncClient( - credentials=credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_subscription), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - - response = await client.delete_subscription(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - - assert args[0] == pubsub.DeleteSubscriptionRequest() - - # Establish that the response is the type that we expect. - assert response is None - - -@pytest.mark.asyncio -async def test_delete_subscription_async_from_dict(): - await test_delete_subscription_async(request_type=dict) - - -def test_delete_subscription_field_headers(): - client = SubscriberClient( - credentials=credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = pubsub.DeleteSubscriptionRequest() - request.subscription = 'subscription/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_subscription), - '__call__') as call: - call.return_value = None - - client.delete_subscription(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'subscription=subscription/value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_delete_subscription_field_headers_async(): - client = SubscriberAsyncClient( - credentials=credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = pubsub.DeleteSubscriptionRequest() - request.subscription = 'subscription/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_subscription), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - - await client.delete_subscription(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'subscription=subscription/value', - ) in kw['metadata'] - - -def test_delete_subscription_flattened(): - client = SubscriberClient( - credentials=credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_subscription), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = None - - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.delete_subscription( - subscription='subscription_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - - assert args[0].subscription == 'subscription_value' - - -def test_delete_subscription_flattened_error(): - client = SubscriberClient( - credentials=credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.delete_subscription( - pubsub.DeleteSubscriptionRequest(), - subscription='subscription_value', - ) - - -@pytest.mark.asyncio -async def test_delete_subscription_flattened_async(): - client = SubscriberAsyncClient( - credentials=credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_subscription), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = None - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.delete_subscription( - subscription='subscription_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - - assert args[0].subscription == 'subscription_value' - - -@pytest.mark.asyncio -async def test_delete_subscription_flattened_error_async(): - client = SubscriberAsyncClient( - credentials=credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.delete_subscription( - pubsub.DeleteSubscriptionRequest(), - subscription='subscription_value', - ) - - -def test_modify_ack_deadline(transport: str = 'grpc', request_type=pubsub.ModifyAckDeadlineRequest): - client = SubscriberClient( - credentials=credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.modify_ack_deadline), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = None - - response = client.modify_ack_deadline(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - - assert args[0] == pubsub.ModifyAckDeadlineRequest() - - # Establish that the response is the type that we expect. - assert response is None - - -def test_modify_ack_deadline_from_dict(): - test_modify_ack_deadline(request_type=dict) - - -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', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.modify_ack_deadline), - '__call__') as call: - client.modify_ack_deadline() - call.assert_called() - _, args, _ = call.mock_calls[0] - - assert args[0] == pubsub.ModifyAckDeadlineRequest() - -@pytest.mark.asyncio -async def test_modify_ack_deadline_async(transport: str = 'grpc_asyncio', request_type=pubsub.ModifyAckDeadlineRequest): - client = SubscriberAsyncClient( - credentials=credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.modify_ack_deadline), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - - response = await client.modify_ack_deadline(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - - assert args[0] == pubsub.ModifyAckDeadlineRequest() - - # Establish that the response is the type that we expect. - assert response is None - - -@pytest.mark.asyncio -async def test_modify_ack_deadline_async_from_dict(): - await test_modify_ack_deadline_async(request_type=dict) - - -def test_modify_ack_deadline_field_headers(): - client = SubscriberClient( - credentials=credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = pubsub.ModifyAckDeadlineRequest() - request.subscription = 'subscription/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.modify_ack_deadline), - '__call__') as call: - call.return_value = None - - client.modify_ack_deadline(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'subscription=subscription/value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_modify_ack_deadline_field_headers_async(): - client = SubscriberAsyncClient( - credentials=credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = pubsub.ModifyAckDeadlineRequest() - request.subscription = 'subscription/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.modify_ack_deadline), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - - await client.modify_ack_deadline(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'subscription=subscription/value', - ) in kw['metadata'] - - -def test_modify_ack_deadline_flattened(): - client = SubscriberClient( - credentials=credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.modify_ack_deadline), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = None - - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.modify_ack_deadline( - subscription='subscription_value', - ack_ids=['ack_ids_value'], - ack_deadline_seconds=2066, - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - - 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(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.modify_ack_deadline( - pubsub.ModifyAckDeadlineRequest(), - subscription='subscription_value', - ack_ids=['ack_ids_value'], - ack_deadline_seconds=2066, - ) - - -@pytest.mark.asyncio -async def test_modify_ack_deadline_flattened_async(): - client = SubscriberAsyncClient( - credentials=credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.modify_ack_deadline), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = None - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.modify_ack_deadline( - subscription='subscription_value', - ack_ids=['ack_ids_value'], - ack_deadline_seconds=2066, - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - - 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(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.modify_ack_deadline( - pubsub.ModifyAckDeadlineRequest(), - subscription='subscription_value', - ack_ids=['ack_ids_value'], - ack_deadline_seconds=2066, - ) - - -def test_acknowledge(transport: str = 'grpc', request_type=pubsub.AcknowledgeRequest): - client = SubscriberClient( - credentials=credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.acknowledge), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = None - - response = client.acknowledge(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - - assert args[0] == pubsub.AcknowledgeRequest() - - # Establish that the response is the type that we expect. - assert response is None - - -def test_acknowledge_from_dict(): - test_acknowledge(request_type=dict) - - -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', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.acknowledge), - '__call__') as call: - client.acknowledge() - call.assert_called() - _, args, _ = call.mock_calls[0] - - assert args[0] == pubsub.AcknowledgeRequest() - -@pytest.mark.asyncio -async def test_acknowledge_async(transport: str = 'grpc_asyncio', request_type=pubsub.AcknowledgeRequest): - client = SubscriberAsyncClient( - credentials=credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.acknowledge), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - - response = await client.acknowledge(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - - assert args[0] == pubsub.AcknowledgeRequest() - - # Establish that the response is the type that we expect. - assert response is None - - -@pytest.mark.asyncio -async def test_acknowledge_async_from_dict(): - await test_acknowledge_async(request_type=dict) - - -def test_acknowledge_field_headers(): - client = SubscriberClient( - credentials=credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = pubsub.AcknowledgeRequest() - request.subscription = 'subscription/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.acknowledge), - '__call__') as call: - call.return_value = None - - client.acknowledge(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'subscription=subscription/value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_acknowledge_field_headers_async(): - client = SubscriberAsyncClient( - credentials=credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = pubsub.AcknowledgeRequest() - request.subscription = 'subscription/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.acknowledge), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - - await client.acknowledge(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'subscription=subscription/value', - ) in kw['metadata'] - - -def test_acknowledge_flattened(): - client = SubscriberClient( - credentials=credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.acknowledge), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = None - - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.acknowledge( - subscription='subscription_value', - ack_ids=['ack_ids_value'], - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - - assert args[0].subscription == 'subscription_value' - - assert args[0].ack_ids == ['ack_ids_value'] - - -def test_acknowledge_flattened_error(): - client = SubscriberClient( - credentials=credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.acknowledge( - pubsub.AcknowledgeRequest(), - subscription='subscription_value', - ack_ids=['ack_ids_value'], - ) - - -@pytest.mark.asyncio -async def test_acknowledge_flattened_async(): - client = SubscriberAsyncClient( - credentials=credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.acknowledge), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = None - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.acknowledge( - subscription='subscription_value', - ack_ids=['ack_ids_value'], - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - - 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(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.acknowledge( - pubsub.AcknowledgeRequest(), - subscription='subscription_value', - ack_ids=['ack_ids_value'], - ) - - -def test_pull(transport: str = 'grpc', request_type=pubsub.PullRequest): - client = SubscriberClient( - credentials=credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.pull), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = pubsub.PullResponse( - ) - - response = client.pull(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - - assert args[0] == pubsub.PullRequest() - - # Establish that the response is the type that we expect. - - assert isinstance(response, pubsub.PullResponse) - - -def test_pull_from_dict(): - test_pull(request_type=dict) - - -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', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.pull), - '__call__') as call: - client.pull() - call.assert_called() - _, args, _ = call.mock_calls[0] - - assert args[0] == pubsub.PullRequest() - -@pytest.mark.asyncio -async def test_pull_async(transport: str = 'grpc_asyncio', request_type=pubsub.PullRequest): - client = SubscriberAsyncClient( - credentials=credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.pull), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(pubsub.PullResponse( - )) - - response = await client.pull(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - - assert args[0] == pubsub.PullRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pubsub.PullResponse) - - -@pytest.mark.asyncio -async def test_pull_async_from_dict(): - await test_pull_async(request_type=dict) - - -def test_pull_field_headers(): - client = SubscriberClient( - credentials=credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = pubsub.PullRequest() - request.subscription = 'subscription/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.pull), - '__call__') as call: - call.return_value = pubsub.PullResponse() - - client.pull(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'subscription=subscription/value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_pull_field_headers_async(): - client = SubscriberAsyncClient( - credentials=credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = pubsub.PullRequest() - request.subscription = 'subscription/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.pull), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(pubsub.PullResponse()) - - await client.pull(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'subscription=subscription/value', - ) in kw['metadata'] - - -def test_pull_flattened(): - client = SubscriberClient( - credentials=credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.pull), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = pubsub.PullResponse() - - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.pull( - subscription='subscription_value', - return_immediately=True, - max_messages=1277, - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - - 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(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.pull( - pubsub.PullRequest(), - subscription='subscription_value', - return_immediately=True, - max_messages=1277, - ) - - -@pytest.mark.asyncio -async def test_pull_flattened_async(): - client = SubscriberAsyncClient( - credentials=credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.pull), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = pubsub.PullResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(pubsub.PullResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.pull( - subscription='subscription_value', - return_immediately=True, - max_messages=1277, - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - - 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(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.pull( - pubsub.PullRequest(), - subscription='subscription_value', - return_immediately=True, - max_messages=1277, - ) - - -def test_streaming_pull(transport: str = 'grpc', request_type=pubsub.StreamingPullRequest): - client = SubscriberClient( - credentials=credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - requests = [request] - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.streaming_pull), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = iter([pubsub.StreamingPullResponse()]) - - response = client.streaming_pull(iter(requests)) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - - assert next(args[0]) == request - - # Establish that the response is the type that we expect. - for message in response: - assert isinstance(message, pubsub.StreamingPullResponse) - - -def test_streaming_pull_from_dict(): - test_streaming_pull(request_type=dict) - - -@pytest.mark.asyncio -async def test_streaming_pull_async(transport: str = 'grpc_asyncio', request_type=pubsub.StreamingPullRequest): - client = SubscriberAsyncClient( - credentials=credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - requests = [request] - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.streaming_pull), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = mock.Mock(aio.StreamStreamCall, autospec=True) - call.return_value.read = mock.AsyncMock(side_effect=[pubsub.StreamingPullResponse()]) - - response = await client.streaming_pull(iter(requests)) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - - assert next(args[0]) == request - - # Establish that the response is the type that we expect. - message = await response.read() - assert isinstance(message, pubsub.StreamingPullResponse) - - -@pytest.mark.asyncio -async def test_streaming_pull_async_from_dict(): - await test_streaming_pull_async(request_type=dict) - - -def test_modify_push_config(transport: str = 'grpc', request_type=pubsub.ModifyPushConfigRequest): - client = SubscriberClient( - credentials=credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.modify_push_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = None - - response = client.modify_push_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - - assert args[0] == pubsub.ModifyPushConfigRequest() - - # Establish that the response is the type that we expect. - assert response is None - - -def test_modify_push_config_from_dict(): - test_modify_push_config(request_type=dict) - - -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', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.modify_push_config), - '__call__') as call: - client.modify_push_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - - assert args[0] == pubsub.ModifyPushConfigRequest() - -@pytest.mark.asyncio -async def test_modify_push_config_async(transport: str = 'grpc_asyncio', request_type=pubsub.ModifyPushConfigRequest): - client = SubscriberAsyncClient( - credentials=credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.modify_push_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - - response = await client.modify_push_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - - assert args[0] == pubsub.ModifyPushConfigRequest() - - # Establish that the response is the type that we expect. - assert response is None - - -@pytest.mark.asyncio -async def test_modify_push_config_async_from_dict(): - await test_modify_push_config_async(request_type=dict) - - -def test_modify_push_config_field_headers(): - client = SubscriberClient( - credentials=credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = pubsub.ModifyPushConfigRequest() - request.subscription = 'subscription/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.modify_push_config), - '__call__') as call: - call.return_value = None - - client.modify_push_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'subscription=subscription/value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_modify_push_config_field_headers_async(): - client = SubscriberAsyncClient( - credentials=credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = pubsub.ModifyPushConfigRequest() - request.subscription = 'subscription/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.modify_push_config), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - - await client.modify_push_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'subscription=subscription/value', - ) in kw['metadata'] - - -def test_modify_push_config_flattened(): - client = SubscriberClient( - credentials=credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.modify_push_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = None - - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.modify_push_config( - subscription='subscription_value', - push_config=pubsub.PushConfig(push_endpoint='push_endpoint_value'), - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - - 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(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.modify_push_config( - pubsub.ModifyPushConfigRequest(), - subscription='subscription_value', - push_config=pubsub.PushConfig(push_endpoint='push_endpoint_value'), - ) - - -@pytest.mark.asyncio -async def test_modify_push_config_flattened_async(): - client = SubscriberAsyncClient( - credentials=credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.modify_push_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = None - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.modify_push_config( - subscription='subscription_value', - push_config=pubsub.PushConfig(push_endpoint='push_endpoint_value'), - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - - assert args[0].subscription == 'subscription_value' - - assert args[0].push_config == pubsub.PushConfig(push_endpoint='push_endpoint_value') - - -@pytest.mark.asyncio -async def test_modify_push_config_flattened_error_async(): - client = SubscriberAsyncClient( - credentials=credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.modify_push_config( - pubsub.ModifyPushConfigRequest(), - subscription='subscription_value', - push_config=pubsub.PushConfig(push_endpoint='push_endpoint_value'), - ) - - -def test_get_snapshot(transport: str = 'grpc', request_type=pubsub.GetSnapshotRequest): - client = SubscriberClient( - credentials=credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_snapshot), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = pubsub.Snapshot( - name='name_value', - - topic='topic_value', - - ) - - response = client.get_snapshot(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - - assert args[0] == pubsub.GetSnapshotRequest() - - # Establish that the response is the type that we expect. - - assert isinstance(response, pubsub.Snapshot) - - assert response.name == 'name_value' - - assert response.topic == 'topic_value' - - -def test_get_snapshot_from_dict(): - test_get_snapshot(request_type=dict) - - -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', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_snapshot), - '__call__') as call: - client.get_snapshot() - call.assert_called() - _, args, _ = call.mock_calls[0] - - assert args[0] == pubsub.GetSnapshotRequest() - -@pytest.mark.asyncio -async def test_get_snapshot_async(transport: str = 'grpc_asyncio', request_type=pubsub.GetSnapshotRequest): - client = SubscriberAsyncClient( - credentials=credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_snapshot), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(pubsub.Snapshot( - name='name_value', - topic='topic_value', - )) - - response = await client.get_snapshot(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - - assert args[0] == pubsub.GetSnapshotRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pubsub.Snapshot) - - assert response.name == 'name_value' - - assert response.topic == 'topic_value' - - -@pytest.mark.asyncio -async def test_get_snapshot_async_from_dict(): - await test_get_snapshot_async(request_type=dict) - - -def test_get_snapshot_field_headers(): - client = SubscriberClient( - credentials=credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = pubsub.GetSnapshotRequest() - request.snapshot = 'snapshot/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_snapshot), - '__call__') as call: - call.return_value = pubsub.Snapshot() - - client.get_snapshot(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'snapshot=snapshot/value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_get_snapshot_field_headers_async(): - client = SubscriberAsyncClient( - credentials=credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = pubsub.GetSnapshotRequest() - request.snapshot = 'snapshot/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_snapshot), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(pubsub.Snapshot()) - - await client.get_snapshot(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'snapshot=snapshot/value', - ) in kw['metadata'] - - -def test_get_snapshot_flattened(): - client = SubscriberClient( - credentials=credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_snapshot), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = pubsub.Snapshot() - - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_snapshot( - snapshot='snapshot_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - - assert args[0].snapshot == 'snapshot_value' - - -def test_get_snapshot_flattened_error(): - client = SubscriberClient( - credentials=credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.get_snapshot( - pubsub.GetSnapshotRequest(), - snapshot='snapshot_value', - ) - - -@pytest.mark.asyncio -async def test_get_snapshot_flattened_async(): - client = SubscriberAsyncClient( - credentials=credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_snapshot), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = pubsub.Snapshot() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(pubsub.Snapshot()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_snapshot( - snapshot='snapshot_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - - assert args[0].snapshot == 'snapshot_value' - - -@pytest.mark.asyncio -async def test_get_snapshot_flattened_error_async(): - client = SubscriberAsyncClient( - credentials=credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.get_snapshot( - pubsub.GetSnapshotRequest(), - snapshot='snapshot_value', - ) - - -def test_list_snapshots(transport: str = 'grpc', request_type=pubsub.ListSnapshotsRequest): - client = SubscriberClient( - credentials=credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_snapshots), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = pubsub.ListSnapshotsResponse( - next_page_token='next_page_token_value', - - ) - - response = client.list_snapshots(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - - assert args[0] == pubsub.ListSnapshotsRequest() - - # Establish that the response is the type that we expect. - - assert isinstance(response, pagers.ListSnapshotsPager) - - assert response.next_page_token == 'next_page_token_value' - - -def test_list_snapshots_from_dict(): - test_list_snapshots(request_type=dict) - - -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', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_snapshots), - '__call__') as call: - client.list_snapshots() - call.assert_called() - _, args, _ = call.mock_calls[0] - - assert args[0] == pubsub.ListSnapshotsRequest() - -@pytest.mark.asyncio -async def test_list_snapshots_async(transport: str = 'grpc_asyncio', request_type=pubsub.ListSnapshotsRequest): - client = SubscriberAsyncClient( - credentials=credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_snapshots), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(pubsub.ListSnapshotsResponse( - next_page_token='next_page_token_value', - )) - - response = await client.list_snapshots(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - - assert args[0] == pubsub.ListSnapshotsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListSnapshotsAsyncPager) - - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_snapshots_async_from_dict(): - await test_list_snapshots_async(request_type=dict) - - -def test_list_snapshots_field_headers(): - client = SubscriberClient( - credentials=credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = pubsub.ListSnapshotsRequest() - request.project = 'project/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_snapshots), - '__call__') as call: - call.return_value = pubsub.ListSnapshotsResponse() - - client.list_snapshots(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'project=project/value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_list_snapshots_field_headers_async(): - client = SubscriberAsyncClient( - credentials=credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = pubsub.ListSnapshotsRequest() - request.project = 'project/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_snapshots), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(pubsub.ListSnapshotsResponse()) - - await client.list_snapshots(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'project=project/value', - ) in kw['metadata'] - - -def test_list_snapshots_flattened(): - client = SubscriberClient( - credentials=credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_snapshots), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = pubsub.ListSnapshotsResponse() - - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_snapshots( - project='project_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - - assert args[0].project == 'project_value' - - -def test_list_snapshots_flattened_error(): - client = SubscriberClient( - credentials=credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.list_snapshots( - pubsub.ListSnapshotsRequest(), - project='project_value', - ) - - -@pytest.mark.asyncio -async def test_list_snapshots_flattened_async(): - client = SubscriberAsyncClient( - credentials=credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_snapshots), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = pubsub.ListSnapshotsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(pubsub.ListSnapshotsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_snapshots( - project='project_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - - assert args[0].project == 'project_value' - - -@pytest.mark.asyncio -async def test_list_snapshots_flattened_error_async(): - client = SubscriberAsyncClient( - credentials=credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.list_snapshots( - pubsub.ListSnapshotsRequest(), - project='project_value', - ) - - -def test_list_snapshots_pager(): - client = SubscriberClient( - credentials=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: - # Set the response to a series of pages. - call.side_effect = ( - pubsub.ListSnapshotsResponse( - snapshots=[ - pubsub.Snapshot(), - pubsub.Snapshot(), - pubsub.Snapshot(), - ], - next_page_token='abc', - ), - pubsub.ListSnapshotsResponse( - snapshots=[], - next_page_token='def', - ), - pubsub.ListSnapshotsResponse( - snapshots=[ - pubsub.Snapshot(), - ], - next_page_token='ghi', - ), - pubsub.ListSnapshotsResponse( - snapshots=[ - pubsub.Snapshot(), - pubsub.Snapshot(), - ], - ), - RuntimeError, - ) - - metadata = () - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('project', ''), - )), - ) - pager = client.list_snapshots(request={}) - - assert pager._metadata == metadata - - results = [i for i in pager] - assert len(results) == 6 - assert all(isinstance(i, pubsub.Snapshot) - for i in results) - -def test_list_snapshots_pages(): - client = SubscriberClient( - credentials=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: - # Set the response to a series of pages. - call.side_effect = ( - pubsub.ListSnapshotsResponse( - snapshots=[ - pubsub.Snapshot(), - pubsub.Snapshot(), - pubsub.Snapshot(), - ], - next_page_token='abc', - ), - pubsub.ListSnapshotsResponse( - snapshots=[], - next_page_token='def', - ), - pubsub.ListSnapshotsResponse( - snapshots=[ - pubsub.Snapshot(), - ], - next_page_token='ghi', - ), - pubsub.ListSnapshotsResponse( - snapshots=[ - pubsub.Snapshot(), - pubsub.Snapshot(), - ], - ), - RuntimeError, - ) - pages = list(client.list_snapshots(request={}).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - -@pytest.mark.asyncio -async def test_list_snapshots_async_pager(): - client = SubscriberAsyncClient( - credentials=credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_snapshots), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - pubsub.ListSnapshotsResponse( - snapshots=[ - pubsub.Snapshot(), - pubsub.Snapshot(), - pubsub.Snapshot(), - ], - next_page_token='abc', - ), - pubsub.ListSnapshotsResponse( - snapshots=[], - next_page_token='def', - ), - pubsub.ListSnapshotsResponse( - snapshots=[ - pubsub.Snapshot(), - ], - next_page_token='ghi', - ), - pubsub.ListSnapshotsResponse( - snapshots=[ - pubsub.Snapshot(), - pubsub.Snapshot(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_snapshots(request={},) - assert async_pager.next_page_token == 'abc' - responses = [] - async for response in async_pager: - responses.append(response) - - assert len(responses) == 6 - assert all(isinstance(i, pubsub.Snapshot) - for i in responses) - -@pytest.mark.asyncio -async def test_list_snapshots_async_pages(): - client = SubscriberAsyncClient( - credentials=credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_snapshots), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - pubsub.ListSnapshotsResponse( - snapshots=[ - pubsub.Snapshot(), - pubsub.Snapshot(), - pubsub.Snapshot(), - ], - next_page_token='abc', - ), - pubsub.ListSnapshotsResponse( - snapshots=[], - next_page_token='def', - ), - pubsub.ListSnapshotsResponse( - snapshots=[ - pubsub.Snapshot(), - ], - next_page_token='ghi', - ), - pubsub.ListSnapshotsResponse( - snapshots=[ - pubsub.Snapshot(), - pubsub.Snapshot(), - ], - ), - RuntimeError, - ) - pages = [] - async for page_ in (await client.list_snapshots(request={})).pages: - pages.append(page_) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -def test_create_snapshot(transport: str = 'grpc', request_type=pubsub.CreateSnapshotRequest): - client = SubscriberClient( - credentials=credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_snapshot), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = pubsub.Snapshot( - name='name_value', - - topic='topic_value', - - ) - - response = client.create_snapshot(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - - assert args[0] == pubsub.CreateSnapshotRequest() - - # Establish that the response is the type that we expect. - - assert isinstance(response, pubsub.Snapshot) - - assert response.name == 'name_value' - - assert response.topic == 'topic_value' - - -def test_create_snapshot_from_dict(): - test_create_snapshot(request_type=dict) - - -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', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_snapshot), - '__call__') as call: - client.create_snapshot() - call.assert_called() - _, args, _ = call.mock_calls[0] - - assert args[0] == pubsub.CreateSnapshotRequest() - -@pytest.mark.asyncio -async def test_create_snapshot_async(transport: str = 'grpc_asyncio', request_type=pubsub.CreateSnapshotRequest): - client = SubscriberAsyncClient( - credentials=credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_snapshot), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(pubsub.Snapshot( - name='name_value', - topic='topic_value', - )) - - response = await client.create_snapshot(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - - assert args[0] == pubsub.CreateSnapshotRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pubsub.Snapshot) - - assert response.name == 'name_value' - - assert response.topic == 'topic_value' - - -@pytest.mark.asyncio -async def test_create_snapshot_async_from_dict(): - await test_create_snapshot_async(request_type=dict) - - -def test_create_snapshot_field_headers(): - client = SubscriberClient( - credentials=credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = pubsub.CreateSnapshotRequest() - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_snapshot), - '__call__') as call: - call.return_value = pubsub.Snapshot() - - client.create_snapshot(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name/value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_create_snapshot_field_headers_async(): - client = SubscriberAsyncClient( - credentials=credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = pubsub.CreateSnapshotRequest() - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_snapshot), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(pubsub.Snapshot()) - - await client.create_snapshot(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name/value', - ) in kw['metadata'] - - -def test_create_snapshot_flattened(): - client = SubscriberClient( - credentials=credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_snapshot), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = pubsub.Snapshot() - - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.create_snapshot( - name='name_value', - subscription='subscription_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - - assert args[0].name == 'name_value' - - assert args[0].subscription == 'subscription_value' - - -def test_create_snapshot_flattened_error(): - client = SubscriberClient( - credentials=credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.create_snapshot( - pubsub.CreateSnapshotRequest(), - name='name_value', - subscription='subscription_value', - ) - - -@pytest.mark.asyncio -async def test_create_snapshot_flattened_async(): - client = SubscriberAsyncClient( - credentials=credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_snapshot), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = pubsub.Snapshot() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(pubsub.Snapshot()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.create_snapshot( - name='name_value', - subscription='subscription_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - - 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(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.create_snapshot( - pubsub.CreateSnapshotRequest(), - name='name_value', - subscription='subscription_value', - ) - - -def test_update_snapshot(transport: str = 'grpc', request_type=pubsub.UpdateSnapshotRequest): - client = SubscriberClient( - credentials=credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_snapshot), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = pubsub.Snapshot( - name='name_value', - - topic='topic_value', - - ) - - response = client.update_snapshot(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - - assert args[0] == pubsub.UpdateSnapshotRequest() - - # Establish that the response is the type that we expect. - - assert isinstance(response, pubsub.Snapshot) - - assert response.name == 'name_value' - - assert response.topic == 'topic_value' - - -def test_update_snapshot_from_dict(): - test_update_snapshot(request_type=dict) - - -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', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_snapshot), - '__call__') as call: - client.update_snapshot() - call.assert_called() - _, args, _ = call.mock_calls[0] - - assert args[0] == pubsub.UpdateSnapshotRequest() - -@pytest.mark.asyncio -async def test_update_snapshot_async(transport: str = 'grpc_asyncio', request_type=pubsub.UpdateSnapshotRequest): - client = SubscriberAsyncClient( - credentials=credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_snapshot), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(pubsub.Snapshot( - name='name_value', - topic='topic_value', - )) - - response = await client.update_snapshot(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - - assert args[0] == pubsub.UpdateSnapshotRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pubsub.Snapshot) - - assert response.name == 'name_value' - - assert response.topic == 'topic_value' - - -@pytest.mark.asyncio -async def test_update_snapshot_async_from_dict(): - await test_update_snapshot_async(request_type=dict) - - -def test_update_snapshot_field_headers(): - client = SubscriberClient( - credentials=credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = pubsub.UpdateSnapshotRequest() - request.snapshot.name = 'snapshot.name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_snapshot), - '__call__') as call: - call.return_value = pubsub.Snapshot() - - client.update_snapshot(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'snapshot.name=snapshot.name/value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_snapshot_field_headers_async(): - client = SubscriberAsyncClient( - credentials=credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = pubsub.UpdateSnapshotRequest() - request.snapshot.name = 'snapshot.name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_snapshot), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(pubsub.Snapshot()) - - await client.update_snapshot(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'snapshot.name=snapshot.name/value', - ) in kw['metadata'] - - -def test_delete_snapshot(transport: str = 'grpc', request_type=pubsub.DeleteSnapshotRequest): - client = SubscriberClient( - credentials=credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_snapshot), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = None - - response = client.delete_snapshot(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - - assert args[0] == pubsub.DeleteSnapshotRequest() - - # Establish that the response is the type that we expect. - assert response is None - - -def test_delete_snapshot_from_dict(): - test_delete_snapshot(request_type=dict) - - -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', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_snapshot), - '__call__') as call: - client.delete_snapshot() - call.assert_called() - _, args, _ = call.mock_calls[0] - - assert args[0] == pubsub.DeleteSnapshotRequest() - -@pytest.mark.asyncio -async def test_delete_snapshot_async(transport: str = 'grpc_asyncio', request_type=pubsub.DeleteSnapshotRequest): - client = SubscriberAsyncClient( - credentials=credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_snapshot), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - - response = await client.delete_snapshot(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - - assert args[0] == pubsub.DeleteSnapshotRequest() - - # Establish that the response is the type that we expect. - assert response is None - - -@pytest.mark.asyncio -async def test_delete_snapshot_async_from_dict(): - await test_delete_snapshot_async(request_type=dict) - - -def test_delete_snapshot_field_headers(): - client = SubscriberClient( - credentials=credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = pubsub.DeleteSnapshotRequest() - request.snapshot = 'snapshot/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_snapshot), - '__call__') as call: - call.return_value = None - - client.delete_snapshot(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'snapshot=snapshot/value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_delete_snapshot_field_headers_async(): - client = SubscriberAsyncClient( - credentials=credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = pubsub.DeleteSnapshotRequest() - request.snapshot = 'snapshot/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_snapshot), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - - await client.delete_snapshot(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'snapshot=snapshot/value', - ) in kw['metadata'] - - -def test_delete_snapshot_flattened(): - client = SubscriberClient( - credentials=credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_snapshot), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = None - - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.delete_snapshot( - snapshot='snapshot_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - - assert args[0].snapshot == 'snapshot_value' - - -def test_delete_snapshot_flattened_error(): - client = SubscriberClient( - credentials=credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.delete_snapshot( - pubsub.DeleteSnapshotRequest(), - snapshot='snapshot_value', - ) - - -@pytest.mark.asyncio -async def test_delete_snapshot_flattened_async(): - client = SubscriberAsyncClient( - credentials=credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_snapshot), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = None - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.delete_snapshot( - snapshot='snapshot_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - - assert args[0].snapshot == 'snapshot_value' - - -@pytest.mark.asyncio -async def test_delete_snapshot_flattened_error_async(): - client = SubscriberAsyncClient( - credentials=credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.delete_snapshot( - pubsub.DeleteSnapshotRequest(), - snapshot='snapshot_value', - ) - - -def test_seek(transport: str = 'grpc', request_type=pubsub.SeekRequest): - client = SubscriberClient( - credentials=credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.seek), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = pubsub.SeekResponse( - ) - - response = client.seek(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - - assert args[0] == pubsub.SeekRequest() - - # Establish that the response is the type that we expect. - - assert isinstance(response, pubsub.SeekResponse) - - -def test_seek_from_dict(): - test_seek(request_type=dict) - - -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', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.seek), - '__call__') as call: - client.seek() - call.assert_called() - _, args, _ = call.mock_calls[0] - - assert args[0] == pubsub.SeekRequest() - -@pytest.mark.asyncio -async def test_seek_async(transport: str = 'grpc_asyncio', request_type=pubsub.SeekRequest): - client = SubscriberAsyncClient( - credentials=credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.seek), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(pubsub.SeekResponse( - )) - - response = await client.seek(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - - assert args[0] == pubsub.SeekRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pubsub.SeekResponse) - - -@pytest.mark.asyncio -async def test_seek_async_from_dict(): - await test_seek_async(request_type=dict) - - -def test_seek_field_headers(): - client = SubscriberClient( - credentials=credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = pubsub.SeekRequest() - request.subscription = 'subscription/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.seek), - '__call__') as call: - call.return_value = pubsub.SeekResponse() - - client.seek(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'subscription=subscription/value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_seek_field_headers_async(): - client = SubscriberAsyncClient( - credentials=credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = pubsub.SeekRequest() - request.subscription = 'subscription/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.seek), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(pubsub.SeekResponse()) - - await client.seek(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'subscription=subscription/value', - ) in kw['metadata'] - - -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.SubscriberGrpcTransport( - credentials=credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = SubscriberClient( - credentials=credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.SubscriberGrpcTransport( - credentials=credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = SubscriberClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.SubscriberGrpcTransport( - credentials=credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = SubscriberClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.SubscriberGrpcTransport( - credentials=credentials.AnonymousCredentials(), - ) - client = SubscriberClient(transport=transport) - assert client.transport is transport - - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.SubscriberGrpcTransport( - credentials=credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.SubscriberGrpcAsyncIOTransport( - credentials=credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - -@pytest.mark.parametrize("transport_class", [ - transports.SubscriberGrpcTransport, - transports.SubscriberGrpcAsyncIOTransport, -]) -def test_transport_adc(transport_class): - # Test default credentials are used if not provided. - with mock.patch.object(auth, 'default') as adc: - adc.return_value = (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(), - ) - 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): - transport = transports.SubscriberTransport( - credentials=credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_subscriber_base_transport(): - # Instantiate the base transport. - with mock.patch('google.pubsub_v1.services.subscriber.transports.SubscriberTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.SubscriberTransport( - credentials=credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'create_subscription', - 'get_subscription', - 'update_subscription', - 'list_subscriptions', - 'delete_subscription', - 'modify_ack_deadline', - 'acknowledge', - 'pull', - 'streaming_pull', - 'modify_push_config', - 'get_snapshot', - 'list_snapshots', - 'create_snapshot', - 'update_snapshot', - 'delete_snapshot', - 'seek', - 'set_iam_policy', - 'get_iam_policy', - 'test_iam_permissions', - ) - for method in methods: - with pytest.raises(NotImplementedError): - getattr(transport, method)(request=object()) - - -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') 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=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/pubsub', - ), - quota_project_id="octopus", - ) - - -def test_subscriber_base_transport_with_adc(): - # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(auth, 'default') 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) - transport = transports.SubscriberTransport() - adc.assert_called_once() - - -def test_subscriber_auth_adc(): - # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(auth, 'default') as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) - SubscriberClient() - adc.assert_called_once_with(scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/pubsub',), - quota_project_id=None, - ) - - -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') as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) - transports.SubscriberGrpcTransport(host="squid.clam.whelk", quota_project_id="octopus") - adc.assert_called_once_with(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]) -def test_subscriber_grpc_transport_client_cert_source_for_mtls( - transport_class -): - cred = credentials.AnonymousCredentials() - - # Check ssl_channel_credentials is used if provided. - with mock.patch.object(transport_class, "create_channel") as mock_create_channel: - mock_ssl_channel_creds = mock.Mock() - transport_class( - host="squid.clam.whelk", - credentials=cred, - ssl_channel_credentials=mock_ssl_channel_creds - ) - mock_create_channel.assert_called_once_with( - "squid.clam.whelk:443", - credentials=cred, - credentials_file=None, - scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/pubsub', - ), - ssl_credentials=mock_ssl_channel_creds, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls - # is used. - with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): - with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: - transport_class( - credentials=cred, - client_cert_source_for_mtls=client_cert_source_callback - ) - expected_cert, expected_key = client_cert_source_callback() - mock_ssl_cred.assert_called_once_with( - certificate_chain=expected_cert, - private_key=expected_key - ) - - -def test_subscriber_host_no_port(): - client = SubscriberClient( - credentials=credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='pubsub.googleapis.com'), - ) - assert client.transport._host == 'pubsub.googleapis.com:443' - - -def test_subscriber_host_with_port(): - client = SubscriberClient( - credentials=credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='pubsub.googleapis.com:8000'), - ) - assert client.transport._host == 'pubsub.googleapis.com:8000' - - -def test_subscriber_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.SubscriberGrpcTransport( - host="squid.clam.whelk", - channel=channel, - ) - assert transport.grpc_channel == channel - assert transport._host == "squid.clam.whelk:443" - assert transport._ssl_channel_credentials == None - - -def test_subscriber_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.SubscriberGrpcAsyncIOTransport( - host="squid.clam.whelk", - channel=channel, - ) - assert transport.grpc_channel == channel - assert transport._host == "squid.clam.whelk:443" - assert transport._ssl_channel_credentials == None - - -# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are -# removed from grpc/grpc_asyncio transport constructor. -@pytest.mark.parametrize("transport_class", [transports.SubscriberGrpcTransport, transports.SubscriberGrpcAsyncIOTransport]) -def test_subscriber_transport_channel_mtls_with_client_cert_source( - transport_class -): - with mock.patch("grpc.ssl_channel_credentials", autospec=True) as grpc_ssl_channel_cred: - with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: - mock_ssl_cred = mock.Mock() - grpc_ssl_channel_cred.return_value = mock_ssl_cred - - mock_grpc_channel = mock.Mock() - grpc_create_channel.return_value = mock_grpc_channel - - cred = credentials.AnonymousCredentials() - with pytest.warns(DeprecationWarning): - with mock.patch.object(auth, 'default') as adc: - adc.return_value = (cred, None) - transport = transport_class( - host="squid.clam.whelk", - api_mtls_endpoint="mtls.squid.clam.whelk", - client_cert_source=client_cert_source_callback, - ) - adc.assert_called_once() - - grpc_ssl_channel_cred.assert_called_once_with( - certificate_chain=b"cert bytes", private_key=b"key bytes" - ) - grpc_create_channel.assert_called_once_with( - "mtls.squid.clam.whelk:443", - credentials=cred, - credentials_file=None, - scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/pubsub', - ), - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel - assert transport._ssl_channel_credentials == mock_ssl_cred - - -# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are -# removed from grpc/grpc_asyncio transport constructor. -@pytest.mark.parametrize("transport_class", [transports.SubscriberGrpcTransport, transports.SubscriberGrpcAsyncIOTransport]) -def test_subscriber_transport_channel_mtls_with_adc( - transport_class -): - mock_ssl_cred = mock.Mock() - with mock.patch.multiple( - "google.auth.transport.grpc.SslCredentials", - __init__=mock.Mock(return_value=None), - ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), - ): - with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: - mock_grpc_channel = mock.Mock() - grpc_create_channel.return_value = mock_grpc_channel - mock_cred = mock.Mock() - - with pytest.warns(DeprecationWarning): - transport = transport_class( - host="squid.clam.whelk", - credentials=mock_cred, - api_mtls_endpoint="mtls.squid.clam.whelk", - client_cert_source=None, - ) - - grpc_create_channel.assert_called_once_with( - "mtls.squid.clam.whelk:443", - credentials=mock_cred, - credentials_file=None, - scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/pubsub', - ), - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel - - -def test_snapshot_path(): - project = "squid" - snapshot = "clam" - - expected = "projects/{project}/snapshots/{snapshot}".format(project=project, snapshot=snapshot, ) - actual = SubscriberClient.snapshot_path(project, snapshot) - assert expected == actual - - -def test_parse_snapshot_path(): - expected = { - "project": "whelk", - "snapshot": "octopus", - - } - path = SubscriberClient.snapshot_path(**expected) - - # Check that the path construction is reversible. - actual = SubscriberClient.parse_snapshot_path(path) - assert expected == actual - -def test_subscription_path(): - project = "oyster" - subscription = "nudibranch" - - expected = "projects/{project}/subscriptions/{subscription}".format(project=project, subscription=subscription, ) - actual = SubscriberClient.subscription_path(project, subscription) - assert expected == actual - - -def test_parse_subscription_path(): - expected = { - "project": "cuttlefish", - "subscription": "mussel", - - } - path = SubscriberClient.subscription_path(**expected) - - # Check that the path construction is reversible. - actual = SubscriberClient.parse_subscription_path(path) - assert expected == actual - -def test_topic_path(): - project = "winkle" - topic = "nautilus" - - expected = "projects/{project}/topics/{topic}".format(project=project, topic=topic, ) - actual = SubscriberClient.topic_path(project, topic) - assert expected == actual - - -def test_parse_topic_path(): - expected = { - "project": "scallop", - "topic": "abalone", - - } - path = SubscriberClient.topic_path(**expected) - - # Check that the path construction is reversible. - actual = SubscriberClient.parse_topic_path(path) - assert expected == actual - -def test_common_billing_account_path(): - billing_account = "squid" - - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = SubscriberClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "clam", - - } - path = SubscriberClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = SubscriberClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "whelk" - - expected = "folders/{folder}".format(folder=folder, ) - actual = SubscriberClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "octopus", - - } - path = SubscriberClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = SubscriberClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "oyster" - - expected = "organizations/{organization}".format(organization=organization, ) - actual = SubscriberClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "nudibranch", - - } - path = SubscriberClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = SubscriberClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "cuttlefish" - - expected = "projects/{project}".format(project=project, ) - actual = SubscriberClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "mussel", - - } - path = SubscriberClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = SubscriberClient.parse_common_project_path(path) - assert expected == actual - -def test_common_location_path(): - project = "winkle" - location = "nautilus" - - expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) - actual = SubscriberClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "scallop", - "location": "abalone", - - } - path = SubscriberClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = SubscriberClient.parse_common_location_path(path) - assert expected == actual - - -def test_client_withDEFAULT_CLIENT_INFO(): - client_info = gapic_v1.client_info.ClientInfo() - - with mock.patch.object(transports.SubscriberTransport, '_prep_wrapped_messages') as prep: - client = SubscriberClient( - credentials=credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.SubscriberTransport, '_prep_wrapped_messages') as prep: - transport_class = SubscriberClient.get_transport_class() - transport = transport_class( - credentials=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, - ) - - # Everything is optional 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() - - # 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",) - - response = client.set_iam_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, policy.Policy) - - assert response.version == 774 - - assert response.etag == b"etag_blob" - - -@pytest.mark.asyncio -async def test_set_iam_policy_async(transport: str = "grpc_asyncio"): - client = SubscriberAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional 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() - - # 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",) - ) - - response = await client.set_iam_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, policy.Policy) - - assert response.version == 774 - - assert response.etag == b"etag_blob" - - -def test_set_iam_policy_field_headers(): - client = SubscriberClient( - credentials=credentials.AnonymousCredentials(), - ) - - # Any value 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.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() - - client.set_iam_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] - - -@pytest.mark.asyncio -async def test_set_iam_policy_field_headers_async(): - client = SubscriberAsyncClient( - credentials=credentials.AnonymousCredentials(), - ) - - # Any value 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.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()) - - await client.set_iam_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] - - -def test_set_iam_policy_from_dict(): - client = SubscriberClient( - credentials=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() - - response = client.set_iam_policy( - request={ - "resource": "resource_value", - "policy": policy.Policy(version=774), - } - ) - call.assert_called() - - -@pytest.mark.asyncio -async def test_set_iam_policy_from_dict_async(): - client = SubscriberAsyncClient( - credentials=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() - ) - - response = await client.set_iam_policy( - request={ - "resource": "resource_value", - "policy": policy.Policy(version=774), - } - ) - call.assert_called() - - -def test_get_iam_policy(transport: str = "grpc"): - client = SubscriberClient( - credentials=credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional 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() - - # 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",) - - response = client.get_iam_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, policy.Policy) - - assert response.version == 774 - - assert response.etag == b"etag_blob" - - -@pytest.mark.asyncio -async def test_get_iam_policy_async(transport: str = "grpc_asyncio"): - client = SubscriberAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional 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() - - # 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",) - ) - - response = await client.get_iam_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, policy.Policy) - - assert response.version == 774 - - assert response.etag == b"etag_blob" - - -def test_get_iam_policy_field_headers(): - client = SubscriberClient( - credentials=credentials.AnonymousCredentials(), - ) - - # Any value 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.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() - - client.get_iam_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] - - -@pytest.mark.asyncio -async def test_get_iam_policy_field_headers_async(): - client = SubscriberAsyncClient( - credentials=credentials.AnonymousCredentials(), - ) - - # Any value 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.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()) - - await client.get_iam_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] - - -def test_get_iam_policy_from_dict(): - client = SubscriberClient( - credentials=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() - - response = client.get_iam_policy( - request={ - "resource": "resource_value", - "options": options.GetPolicyOptions(requested_policy_version=2598), - } - ) - call.assert_called() - -@pytest.mark.asyncio -async def test_get_iam_policy_from_dict_async(): - client = SubscriberAsyncClient( - credentials=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() - ) - - response = await client.get_iam_policy( - request={ - "resource": "resource_value", - "options": options.GetPolicyOptions(requested_policy_version=2598), - } - ) - call.assert_called() - - -def test_test_iam_permissions(transport: str = "grpc"): - client = SubscriberClient( - credentials=credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional 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() - - # 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( - permissions=["permissions_value"], - ) - - response = client.test_iam_permissions(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, iam_policy.TestIamPermissionsResponse) - - assert response.permissions == ["permissions_value"] - - -@pytest.mark.asyncio -async def test_test_iam_permissions_async(transport: str = "grpc_asyncio"): - client = SubscriberAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional 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() - - # 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(permissions=["permissions_value"],) - ) - - response = await client.test_iam_permissions(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, iam_policy.TestIamPermissionsResponse) - - assert response.permissions == ["permissions_value"] - - -def test_test_iam_permissions_field_headers(): - client = SubscriberClient( - credentials=credentials.AnonymousCredentials(), - ) - - # Any value 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.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() - - client.test_iam_permissions(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] - - -@pytest.mark.asyncio -async def test_test_iam_permissions_field_headers_async(): - client = SubscriberAsyncClient( - credentials=credentials.AnonymousCredentials(), - ) - - # Any value 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.resource = "resource/value" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.test_iam_permissions), "__call__" - ) as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - iam_policy.TestIamPermissionsResponse() - ) - - await client.test_iam_permissions(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] - - -def test_test_iam_permissions_from_dict(): - client = SubscriberClient( - credentials=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() - - response = client.test_iam_permissions( - request={ - "resource": "resource_value", - "permissions": ["permissions_value"], - } - ) - call.assert_called() - -@pytest.mark.asyncio -async def test_test_iam_permissions_from_dict_async(): - client = SubscriberAsyncClient( - credentials=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() - ) - - response = await client.test_iam_permissions( - request={ - "resource": "resource_value", - "permissions": ["permissions_value"], - } - ) - call.assert_called() From c842cf036bbbfca2142c953e48d97bc45ab6c2dc Mon Sep 17 00:00:00 2001 From: Anthonios Partheniou Date: Sat, 17 Jul 2021 10:11:20 +0000 Subject: [PATCH 04/14] pull in synth.py changes from #299 --- owlbot.py | 57 +++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 57 insertions(+) diff --git a/owlbot.py b/owlbot.py index ed6865c24..5ab2422bb 100644 --- a/owlbot.py +++ b/owlbot.py @@ -234,6 +234,63 @@ "\n\g<0>", ) + # Allow timeout to be an instance of google.api_core.timeout.* + s.replace( + library / f"google/pubsub_{library.name}/types/__init__.py", + r"from \.pubsub import \(", + "from typing import Union\n\n\g<0>" + ) + + s.replace( + library / f"google/pubsub_{library.name}/types/__init__.py", + r"__all__ = \(\n", + textwrap.dedent('''\ + TimeoutType = Union[ + int, + float, + "google.api_core.timeout.ConstantTimeout", + "google.api_core.timeout.ExponentialTimeout", + ] + """The type of the timeout parameter of publisher client methods.""" + + \g<0> "TimeoutType",''') + ) + + s.replace( + library / f"google/pubsub_{library.name}/services/publisher/*client.py", + r"from google.api_core import retry as retries.*\n", + "\g<0>from google.api_core import timeout as timeouts # type: ignore\n" + ) + + s.replace( + library / f"google/pubsub_{library.name}/services/publisher/*client.py", + f"from google\.pubsub_{library.name}\.types import pubsub", + f"\g<0>\nfrom google.pubsub_{library.name}.types import TimeoutType", + ) + + s.replace( + library / f"google/pubsub_{library.name}/services/publisher/*client.py", + r"(\s+)timeout: float = None.*\n", + f"\g<1>timeout: TimeoutType = gapic_{library.name}.method.DEFAULT,", + ) + + s.replace( + library / f"google/pubsub_{library.name}/services/publisher/*client.py", + r"([^\S\r\n]+)timeout \(float\): (.*)\n", + ( + "\g<1>timeout (TimeoutType):\n" + "\g<1> \g<2>\n" + ), + ) + + # The namespace package declaration in google/cloud/__init__.py should be excluded + # from coverage. + s.replace( + ".coveragerc", + r"((?P[^\n\S]+)google/pubsub/__init__\.py)", + "\ggoogle/cloud/__init__.py\n\g<0>", + ) + s.move( library, excludes=[ From 922855dd2edf61ba28314dc83469e3ab9deb3702 Mon Sep 17 00:00:00 2001 From: Owl Bot Date: Sat, 17 Jul 2021 10:13:28 +0000 Subject: [PATCH 05/14] =?UTF-8?q?=F0=9F=A6=89=20Updates=20from=20OwlBot?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit See https://github.com/googleapis/repo-automation-bots/blob/master/packages/owl-bot/README.md --- .kokoro/presubmit/common.cfg | 8 +++----- .kokoro/presubmit/presubmit.cfg | 7 +------ 2 files changed, 4 insertions(+), 11 deletions(-) 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 From 6f95a51c9bb909484cd87638a945eb6ac25f1f9b Mon Sep 17 00:00:00 2001 From: Anthonios Partheniou Date: Sat, 17 Jul 2021 10:18:44 +0000 Subject: [PATCH 06/14] .github/use gcr.io/cloud-devrel-public-resources/owlbot-python post processor image --- .github/.OwlBot.lock.yaml | 5 ++--- .github/.OwlBot.yaml | 2 +- 2 files changed, 3 insertions(+), 4 deletions(-) diff --git a/.github/.OwlBot.lock.yaml b/.github/.OwlBot.lock.yaml index d49860b32..6bfcf3ecc 100644 --- a/.github/.OwlBot.lock.yaml +++ b/.github/.OwlBot.lock.yaml @@ -1,4 +1,3 @@ docker: - digest: sha256:457583330eec64daa02aeb7a72a04d33e7be2428f646671ce4045dcbc0191b1e - image: gcr.io/repo-automation-bots/owlbot-python:latest - + digest: sha256:808628fb9d5c649a28355b062ee184a4689e98e8607c241461dae26e5a6df0c2 + image: gcr.io/cloud-devrel-public-resources/owlbot-python:latest diff --git a/.github/.OwlBot.yaml b/.github/.OwlBot.yaml index 43e208e72..0bfe82f74 100644 --- a/.github/.OwlBot.yaml +++ b/.github/.OwlBot.yaml @@ -13,7 +13,7 @@ # limitations under the License. docker: - image: gcr.io/repo-automation-bots/owlbot-python:latest + image: gcr.io/cloud-devrel-public-resources/owlbot-python:latest deep-remove-regex: - /owl-bot-staging From 1f4cc7d1a208f1e5b7b0001398dffd51b9b9f2d3 Mon Sep 17 00:00:00 2001 From: Owl Bot Date: Sat, 17 Jul 2021 10:19:53 +0000 Subject: [PATCH 07/14] =?UTF-8?q?=F0=9F=A6=89=20Updates=20from=20OwlBot?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit See https://github.com/googleapis/repo-automation-bots/blob/master/packages/owl-bot/README.md --- .kokoro/docker/docs/Dockerfile | 35 ++---------------- .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 | 21 +++++------ docs/conf.py | 13 +++---- docs/multiprocessing.rst | 4 +-- noxfile.py | 6 ++-- samples/snippets/noxfile.py | 13 +++++-- 13 files changed, 107 insertions(+), 64 deletions(-) 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/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 1bbd78783..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.1 + rev: 3.9.2 hooks: - id: flake8 diff --git a/CONTRIBUTING.rst b/CONTRIBUTING.rst index 55453e840..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,9 +148,8 @@ 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 @@ -218,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/noxfile.py b/noxfile.py index e8dbd3f17..08c6654f4 100644 --- a/noxfile.py +++ b/noxfile.py @@ -181,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( @@ -203,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"): From 0b46582d4aed5ab40e32d165159c253a92880fec Mon Sep 17 00:00:00 2001 From: Anthonios Partheniou Date: Sat, 17 Jul 2021 10:35:45 +0000 Subject: [PATCH 08/14] fix owlbot.py replacement --- owlbot.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/owlbot.py b/owlbot.py index 5ab2422bb..45035495a 100644 --- a/owlbot.py +++ b/owlbot.py @@ -29,7 +29,7 @@ # DEFAULT SCOPES and SERVICE_ADDRESS are being used. so let's force them in. s.replace( library / f"google/pubsub_{library.name}/services/*er/*client.py", - r"DEFAULT_ENDPOINT = 'pubsub\.googleapis\.com'", + r"""DEFAULT_ENDPOINT = \"pubsub\.googleapis\.com\"""", """ # The scopes needed to make gRPC calls to all of the methods defined in # this service From a0b4c9dc046477492ca21a82cc6d16f9c84d7faa Mon Sep 17 00:00:00 2001 From: Anthonios Partheniou Date: Sat, 17 Jul 2021 10:38:23 +0000 Subject: [PATCH 09/14] Copy generated code from googleapis-gen --- .coveragerc | 2 - google/pubsub/__init__.py | 48 +- google/pubsub_v1/__init__.py | 19 +- 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 | 135 ++- google/pubsub_v1/services/publisher/client.py | 152 ++- google/pubsub_v1/services/publisher/pagers.py | 8 +- .../services/publisher/transports/__init__.py | 2 - .../services/publisher/transports/base.py | 217 +++-- .../services/publisher/transports/grpc.py | 55 +- .../publisher/transports/grpc_asyncio.py | 57 +- .../services/schema_service/__init__.py | 2 - .../services/schema_service/async_client.py | 83 +- .../services/schema_service/client.py | 141 ++- .../services/schema_service/pagers.py | 4 +- .../schema_service/transports/__init__.py | 2 - .../schema_service/transports/base.py | 149 ++- .../schema_service/transports/grpc.py | 55 +- .../schema_service/transports/grpc_asyncio.py | 57 +- .../pubsub_v1/services/subscriber/__init__.py | 2 - .../services/subscriber/async_client.py | 191 ++-- .../pubsub_v1/services/subscriber/client.py | 178 ++-- .../pubsub_v1/services/subscriber/pagers.py | 6 +- .../subscriber/transports/__init__.py | 2 - .../services/subscriber/transports/base.py | 274 +++--- .../services/subscriber/transports/grpc.py | 73 +- .../subscriber/transports/grpc_asyncio.py | 73 +- google/pubsub_v1/types/pubsub.py | 326 +++---- google/pubsub_v1/types/schema.py | 56 +- scripts/fixup_pubsub_v1_keywords.py | 68 +- 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 | 689 ++++++------- .../gapic/pubsub_v1/test_schema_service.py | 627 +++++++----- tests/unit/gapic/pubsub_v1/test_subscriber.py | 910 ++++++++---------- 39 files changed, 2761 insertions(+), 2312 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..bcdb1c586 100644 --- a/.coveragerc +++ b/.coveragerc @@ -2,10 +2,8 @@ branch = True [report] -fail_under = 100 show_missing = True omit = - google/cloud/__init__.py google/pubsub/__init__.py exclude_lines = # Re-enable the standard pragma 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..bc78db26f 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,19 +67,21 @@ 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__ = ( + "PublisherAsyncClient", + "SchemaServiceAsyncClient", + "SubscriberAsyncClient", "AcknowledgeRequest", "CreateSchemaRequest", "CreateSnapshotRequest", @@ -110,6 +115,7 @@ "ModifyPushConfigRequest", "PublishRequest", "PublishResponse", + "PublisherClient", "PubsubMessage", "PullRequest", "PullResponse", @@ -135,5 +141,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 041391c57..09e4b0e55 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,15 +20,15 @@ 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 @@ -55,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 @@ -81,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. @@ -96,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 @@ -113,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. @@ -127,12 +121,12 @@ 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, ) -> None: - """Instantiate the publisher client. + """Instantiates the publisher client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -164,7 +158,6 @@ def __init__( google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport creation failed for any reason. """ - self._client = PublisherClient( credentials=credentials, transport=transport, @@ -201,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): @@ -227,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 @@ -239,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 +277,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, @@ -295,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, @@ -370,10 +364,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) @@ -386,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, ), @@ -458,7 +450,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 @@ -471,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, ), @@ -543,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 @@ -556,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, ), @@ -637,7 +627,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 @@ -650,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, ), @@ -735,7 +724,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 @@ -748,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, ), @@ -824,7 +812,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 @@ -836,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, @@ -886,7 +875,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, @@ -897,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, @@ -920,16 +910,18 @@ 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: - r"""Sets the IAM access control policy on the specified - function. Replaces any existing 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, @@ -939,7 +931,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. @@ -1003,7 +995,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. @@ -1027,17 +1019,19 @@ 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, @@ -1047,7 +1041,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. @@ -1111,7 +1105,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. @@ -1135,17 +1129,20 @@ 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 + 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, @@ -1155,7 +1152,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. @@ -1163,7 +1160,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 3f249b01b..cb4450608 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 @@ -60,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: @@ -86,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. @@ -131,7 +129,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: @@ -149,7 +148,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: @@ -169,36 +168,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 ) @@ -206,18 +206,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, ) @@ -230,7 +230,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 @@ -241,7 +241,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 @@ -252,7 +252,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 @@ -263,7 +263,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, ) @@ -277,12 +277,12 @@ 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, ) -> None: - """Instantiate the publisher client. + """Instantiates the publisher client. Args: @@ -338,9 +338,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: @@ -352,12 +353,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. @@ -372,8 +375,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: @@ -427,7 +430,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 +457,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 +493,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 +505,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 +560,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 +587,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 +632,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 +659,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 +702,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 +733,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 @@ -827,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 @@ -885,7 +872,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): @@ -917,10 +903,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 @@ -974,7 +958,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): @@ -998,10 +981,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 @@ -1039,7 +1020,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): @@ -1054,7 +1034,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 @@ -1082,17 +1061,19 @@ 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: - r"""Sets the IAM access control policy on the specified - function. Replaces any existing 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, @@ -1102,7 +1083,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. @@ -1169,7 +1150,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. @@ -1193,26 +1174,30 @@ 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. + + 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, should be retried. timeout (TimeoutType): The timeout for this request. 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. @@ -1279,7 +1264,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. @@ -1303,26 +1288,31 @@ 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: - 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. + ) -> iam_policy_pb2.TestIamPermissionsResponse: + r"""Tests the specified IAM permissions against the IAM access control + policy for a function. + + If the function does not exist, this will return an empty set + of permissions, not a NOT_FOUND error. + Args: - request (:class:`~.iam_policy.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, should be retried. timeout (TimeoutType): The timeout for this request. 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. @@ -1330,7 +1320,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..1a826de78 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, @@ -117,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 @@ -245,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 @@ -373,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/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..6e9f8cea8 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,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.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 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 +40,15 @@ 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 + class PublisherTransport(abc.ABC): """Abstract transport class for Publisher.""" @@ -49,21 +58,25 @@ 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, + always_use_jwt_access: Optional[bool] = False, **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): @@ -80,35 +93,70 @@ 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: host += ":443" self._host = host + 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. 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 ) + # 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): 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-auth is 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 + def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. self._wrapped_methods = { @@ -118,7 +166,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 +180,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 +195,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 +215,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 +231,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 +247,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 +263,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 +278,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 +292,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 +305,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 +357,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 +369,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 +389,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..d6c127d10 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, @@ -64,11 +61,13 @@ 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. 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 @@ -103,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 @@ -155,6 +156,7 @@ def __init__( scopes=scopes, quota_project_id=quota_project_id, client_info=client_info, + always_use_jwt_access=always_use_jwt_access, ) if not self._grpc_channel: @@ -179,7 +181,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 +212,15 @@ def create_channel( google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` and ``credentials_file`` are passed. """ - 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, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, **kwargs, ) @@ -415,7 +419,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 +443,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 +482,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 +499,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 +525,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 +534,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 +554,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..d98b8fc1c 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 + return grpc_helpers_async.create_channel( host, credentials=credentials, credentials_file=credentials_file, - scopes=scopes, quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, **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, @@ -108,11 +107,13 @@ 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. 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 @@ -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 @@ -170,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 @@ -200,6 +202,7 @@ def __init__( scopes=scopes, quota_project_id=quota_project_id, client_info=client_info, + always_use_jwt_access=always_use_jwt_access, ) if not self._grpc_channel: @@ -426,7 +429,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 +453,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 +492,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 +509,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 +535,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 +544,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 +564,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..6ec1fe667 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 @@ -81,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. @@ -96,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 @@ -113,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. @@ -127,12 +120,12 @@ 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, ) -> None: - """Instantiate the schema service client. + """Instantiates the schema service client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -164,7 +157,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 +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: @@ -290,7 +280,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 +304,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 +349,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 +377,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 +428,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 +448,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 +500,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 +524,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 +563,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 +574,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 +598,18 @@ 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: - r"""Sets the IAM access control policy on the specified - function. Replaces any existing 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 +618,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 +682,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 +706,19 @@ 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 +727,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 +791,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 +815,20 @@ 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 + 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 +837,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 +845,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..106afa850 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 @@ -56,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 @@ -79,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: @@ -113,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. @@ -130,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 @@ -149,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, ) @@ -184,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 @@ -195,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 @@ -206,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 @@ -217,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, ) @@ -231,12 +231,12 @@ 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, ) -> None: - """Instantiate the schema service client. + """Instantiates the schema service client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -291,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: @@ -305,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. @@ -325,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: @@ -385,7 +388,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 +414,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 +460,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 +486,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 +529,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 +559,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 +608,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 +630,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 +680,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 +706,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 +743,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 +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 @@ -793,16 +779,18 @@ 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: - r"""Sets the IAM access control policy on the specified - function. Replaces any existing 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 +799,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 +863,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,26 +887,28 @@ 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. + + 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, - 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. 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 +972,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,26 +996,29 @@ 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: - 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. + ) -> iam_policy_pb2.TestIamPermissionsResponse: + r"""Tests the specified IAM permissions against the IAM access control + policy for a function. + + If the function does not exist, this will return an empty set + of permissions, not a NOT_FOUND error. + Args: - request (:class:`~.iam_policy.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, - 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. Returns: - ~.iam_policy.TestIamPermissionsResponse: + ~.iam_policy_pb2.TestIamPermissionsResponse: Response message for ``TestIamPermissions`` method. """ # Create or coerce a protobuf request object. @@ -1033,7 +1026,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..f0248bf5e 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, @@ -117,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/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..1044166cc 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,25 @@ # 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.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 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 +41,15 @@ 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 + class SchemaServiceTransport(abc.ABC): """Abstract transport class for SchemaService.""" @@ -50,21 +59,25 @@ 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, + always_use_jwt_access: Optional[bool] = False, **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): @@ -81,35 +94,70 @@ 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: host += ":443" self._host = host + 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. 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 ) + # 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): 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-auth is 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 + def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. self._wrapped_methods = { @@ -136,49 +184,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 +230,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 +241,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..c99633ca2 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, @@ -64,11 +61,13 @@ 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. 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 @@ -103,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 @@ -155,6 +156,7 @@ def __init__( scopes=scopes, quota_project_id=quota_project_id, client_info=client_info, + always_use_jwt_access=always_use_jwt_access, ) if not self._grpc_channel: @@ -179,7 +181,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 +212,15 @@ def create_channel( google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` and ``credentials_file`` are passed. """ - 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, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, **kwargs, ) @@ -303,7 +307,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 +326,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 +385,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 +402,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 +428,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 +437,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 +457,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..0f4c93370 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 + return grpc_helpers_async.create_channel( host, credentials=credentials, credentials_file=credentials_file, - scopes=scopes, quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, **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, @@ -108,11 +107,13 @@ 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. 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 @@ -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 @@ -170,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 @@ -200,6 +202,7 @@ def __init__( scopes=scopes, quota_project_id=quota_project_id, client_info=client_info, + always_use_jwt_access=always_use_jwt_access, ) if not self._grpc_channel: @@ -311,7 +314,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 +333,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 +396,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 +413,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 +439,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 +448,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 +468,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..502f6f158 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 @@ -94,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. @@ -109,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 @@ -126,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. @@ -140,12 +133,12 @@ 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, ) -> None: - """Instantiate the subscriber client. + """Instantiates the subscriber client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -177,7 +170,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 +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: @@ -320,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, ), @@ -364,7 +354,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 +378,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 @@ -402,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, ), @@ -442,7 +430,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 +441,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, @@ -465,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, @@ -508,7 +496,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 +524,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 @@ -550,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, ), @@ -605,7 +591,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 +611,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 @@ -638,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, @@ -708,7 +694,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 +714,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) @@ -746,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, @@ -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) @@ -840,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, @@ -910,7 +894,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 +918,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: @@ -958,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, ), @@ -1028,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, ), @@ -1087,7 +1069,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 +1089,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: @@ -1122,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, @@ -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 @@ -1213,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, ), @@ -1261,7 +1241,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 +1269,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 @@ -1303,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, ), @@ -1392,7 +1370,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 +1400,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: @@ -1437,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, @@ -1476,7 +1454,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 +1471,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, @@ -1505,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, @@ -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 @@ -1590,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, @@ -1629,7 +1607,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 +1618,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, @@ -1653,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, ), @@ -1679,16 +1655,18 @@ 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: - r"""Sets the IAM access control policy on the specified - function. Replaces any existing 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 +1675,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 +1739,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 +1763,19 @@ 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 +1784,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 +1848,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 +1872,20 @@ 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 + 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 +1894,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 +1902,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..9f506214a 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 @@ -71,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: @@ -99,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. @@ -144,7 +142,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: @@ -162,7 +161,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: @@ -182,36 +181,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 ) @@ -219,18 +219,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, ) @@ -243,7 +243,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 @@ -254,7 +254,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 @@ -265,7 +265,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 @@ -276,7 +276,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, ) @@ -290,12 +290,12 @@ 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, ) -> None: - """Instantiate the subscriber client. + """Instantiates the subscriber client. Args: @@ -351,9 +351,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: @@ -365,12 +366,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. @@ -385,8 +388,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: @@ -502,7 +505,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 +531,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 +581,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 +607,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 +647,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 +658,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 +706,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 +736,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 +791,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 +813,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 +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: @@ -987,7 +973,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 +995,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 +1070,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 +1096,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 +1224,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 +1246,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 +1298,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 +1330,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 +1378,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 +1408,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 +1497,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 +1529,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 +1573,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 +1590,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 +1647,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 +1669,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 +1711,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 +1722,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 +1749,19 @@ 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: - r"""Sets the IAM access control policy on the specified - function. Replaces any existing 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 +1770,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 +1837,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,27 +1861,29 @@ 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. + + 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, - 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. 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 +1950,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,27 +1974,30 @@ 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: - 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. + ) -> iam_policy_pb2.TestIamPermissionsResponse: + r"""Tests the specified IAM permissions against the IAM access control + policy for a function. + + If the function does not exist, this will return an empty set + of permissions, not a NOT_FOUND error. + Args: - request (:class:`~.iam_policy.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, - 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. Returns: - ~.iam_policy.TestIamPermissionsResponse: + ~.iam_policy_pb2.TestIamPermissionsResponse: Response message for ``TestIamPermissions`` method. """ # Create or coerce a protobuf request object. @@ -2037,7 +2005,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..495688522 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, @@ -117,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 @@ -245,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/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..7100e5849 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,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.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 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 +40,15 @@ 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 + class SubscriberTransport(abc.ABC): """Abstract transport class for Subscriber.""" @@ -49,21 +58,25 @@ 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, + always_use_jwt_access: Optional[bool] = False, **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): @@ -80,35 +93,70 @@ 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: host += ":443" self._host = host + 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. 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 ) + # 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): 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-auth is 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 + def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. self._wrapped_methods = { @@ -119,9 +167,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 +183,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 +198,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 +213,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 +228,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 +242,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 +256,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 +271,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 +287,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 +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, @@ -261,9 +319,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 +335,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 +350,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 +364,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 +378,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 +393,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 +407,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 +446,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..b116b018c 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, @@ -66,11 +63,13 @@ 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. 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 @@ -105,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 @@ -157,6 +158,7 @@ def __init__( scopes=scopes, quota_project_id=quota_project_id, client_info=client_info, + always_use_jwt_access=always_use_jwt_access, ) if not self._grpc_channel: @@ -181,7 +183,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 +214,15 @@ def create_channel( google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` and ``credentials_file`` are passed. """ - 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, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, **kwargs, ) @@ -349,7 +353,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 +377,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 +408,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 +439,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 +505,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 +530,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 +671,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 +701,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 +740,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 +757,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 +783,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 +792,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 +812,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..91d557790 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 + return grpc_helpers_async.create_channel( host, credentials=credentials, credentials_file=credentials_file, - scopes=scopes, quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, **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, @@ -110,11 +109,13 @@ 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. 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 @@ -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 @@ -172,7 +175,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 @@ -202,6 +204,7 @@ def __init__( scopes=scopes, quota_project_id=quota_project_id, client_info=client_info, + always_use_jwt_access=always_use_jwt_access, ) if not self._grpc_channel: @@ -355,7 +358,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 +382,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 +413,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 +446,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 +514,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 +539,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 +686,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 +714,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 +753,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 +770,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 +796,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 +805,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 +825,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/pubsub.py b/google/pubsub_v1/types/pubsub.py index 6fb73e8c9..d105a9048 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): @@ -1123,16 +1046,30 @@ 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): r"""Request for the ``CreateSnapshot`` method. - Attributes: name (str): Required. User-provided name for this snapshot. If the name @@ -1158,16 +1095,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 +1112,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 +1149,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 +1181,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 +1202,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 +1241,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/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..b171fb3e7 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,42 @@ 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 _GOOGLE_AUTH_VERSION from google.pubsub_v1.types import pubsub from google.pubsub_v1.types import schema +import google.auth + + +# 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"), + 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", +) def client_cert_source_callback(): @@ -87,7 +102,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: @@ -100,9 +115,37 @@ 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_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,]) 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 +194,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 +476,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 +489,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 +511,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 +519,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 +527,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 +544,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 +564,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 +589,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 +613,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 +627,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 +643,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 +659,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 +676,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 +689,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 +711,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 +719,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 +727,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 +744,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 +764,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 +789,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 +814,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 +825,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 +845,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 +853,6 @@ def test_publish_empty_call(): client.publish() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == pubsub.PublishRequest() @@ -850,7 +861,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 +874,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 +892,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 +917,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 +930,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 +943,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 +959,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 +978,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 +998,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 +1018,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 +1031,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 +1053,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 +1061,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 +1069,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 +1086,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 +1106,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 +1131,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 +1155,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 +1169,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 +1185,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 +1201,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 +1218,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 +1231,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 +1251,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 +1259,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 +1267,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 +1280,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 +1298,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 +1323,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 +1336,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 +1349,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 +1363,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 +1379,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 +1397,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 +1413,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 +1443,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 +1465,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 +1494,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 +1522,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 +1538,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 +1559,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 +1569,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 +1577,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 +1595,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 +1614,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 +1627,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 +1641,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 +1656,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 +1669,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 +1677,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 +1685,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 +1701,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 +1721,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 +1737,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 +1772,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 +1799,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 +1833,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 +1866,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 +1881,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 +1902,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 +1912,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 +1920,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 +1937,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 +1956,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 +1969,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 +1983,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 +1998,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 +2011,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 +2019,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 +2027,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 +2043,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 +2063,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 +2079,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 +2112,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 +2137,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 +2169,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 +2198,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 +2209,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 +2228,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 +2236,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 +2244,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 +2255,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 +2272,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 +2297,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 +2321,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 +2335,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 +2351,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 +2367,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 +2386,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 +2399,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 +2418,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 +2428,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 +2436,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 +2451,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 +2468,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 +2481,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 +2497,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 +2512,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 +2529,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 +2548,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 +2559,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 +2568,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 +2586,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 +2614,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 +2638,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 = (credentials.AnonymousCredentials(), 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 = (ga_credentials.AnonymousCredentials(), None) transport = transports.PublisherTransport( credentials_file="credentials.json", quota_project_id="octopus", ) @@ -2725,19 +2687,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 +2727,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 +2768,51 @@ def test_publisher_transport_auth_adc(): ) +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.PublisherGrpcTransport, grpc_helpers), + (transports.PublisherGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +def test_publisher_transport_create_channel(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + + create_channel.assert_called_with( + "pubsub.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/pubsub", + ), + scopes=["1", "2"], + default_host="pubsub.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ("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: @@ -2784,10 +2826,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=[ @@ -2813,7 +2852,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 +2862,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 +2913,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", @@ -2892,10 +2931,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=[ @@ -2940,10 +2976,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=[ @@ -2958,7 +2991,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 +3013,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 +3035,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 +3054,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 +3074,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 +3092,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 +3110,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 +3129,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 +3155,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 +3164,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 +3192,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 +3202,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 +3225,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 +3233,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 +3258,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 +3282,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 +3299,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 +3316,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 +3337,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 +3347,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 +3370,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 +3378,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 +3403,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 +3427,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 +3444,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 +3461,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 +3486,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 +3494,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 +3507,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 +3521,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 +3554,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 +3566,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 +3582,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 +3601,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..fcc8b68e1 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,42 @@ 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 ( + _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-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"), + 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", +) def client_cert_source_callback(): @@ -92,7 +109,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: @@ -105,11 +122,41 @@ 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_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( "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 +209,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 +497,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 +512,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 +534,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 +542,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 +550,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 +567,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 +587,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 +612,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 +638,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 +656,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 +677,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 +699,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 +723,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 +738,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 +760,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 +768,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 +776,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 +793,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 +813,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 +838,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 +864,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 +878,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 +894,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 +912,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 +931,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 +944,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 +964,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 +972,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 +980,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 +993,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 +1011,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 +1036,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 +1051,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 +1064,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 +1078,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 +1094,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 +1114,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 +1132,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 +1164,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 +1188,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 +1219,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 +1249,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 +1260,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 +1279,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 +1287,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 +1295,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 +1306,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 +1323,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 +1348,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 +1374,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 +1388,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 +1404,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 +1422,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 +1443,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 +1454,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 +1473,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 +1481,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 +1489,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 +1502,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 +1519,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 +1544,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 +1559,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 +1572,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 +1588,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 +1607,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 +1629,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 +1653,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 +1664,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 +1683,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 +1691,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 +1699,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 +1712,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 +1729,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 +1754,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 +1769,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 +1784,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 +1803,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 +1814,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 +1823,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 +1844,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 +1872,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 +1893,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 +1942,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 +1982,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 +2029,45 @@ def test_schema_service_transport_auth_adc(): ) +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.SchemaServiceGrpcTransport, grpc_helpers), + (transports.SchemaServiceGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +def test_schema_service_transport_create_channel(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + + create_channel.assert_called_with( + "pubsub.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/pubsub", + ), + scopes=["1", "2"], + default_host="pubsub.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ("grpc.keepalive_time_ms", 30000), + ], + ) + + @pytest.mark.parametrize( "transport_class", [ @@ -1956,7 +2076,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: @@ -1970,10 +2090,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=[ @@ -1999,7 +2116,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 +2126,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 +2180,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", @@ -2081,10 +2198,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=[ @@ -2132,10 +2246,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=[ @@ -2150,7 +2261,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 +2282,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 +2302,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 +2320,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 +2338,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 +2357,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 +2383,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 +2392,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 +2420,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 +2430,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 +2453,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 +2461,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 +2486,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 +2512,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 +2529,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 +2548,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 +2569,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 +2579,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 +2602,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 +2610,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 +2635,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 +2661,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 +2678,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 +2697,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 +2722,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 +2730,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 +2743,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 +2757,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 +2790,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 +2804,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 +2820,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 +2839,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..67e6b26cc 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,42 @@ 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 _GOOGLE_AUTH_VERSION from google.pubsub_v1.types import pubsub +import google.auth + + +# 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"), + 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", +) def client_cert_source_callback(): @@ -90,7 +105,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: @@ -103,9 +118,37 @@ 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_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,]) 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 +199,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 +481,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 +502,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 +528,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 +538,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 +546,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 +569,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 +593,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 +606,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 +620,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 +633,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 +646,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 +654,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 +667,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 +692,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 +715,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 +743,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 +762,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 +788,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 +796,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 +804,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 +825,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 +849,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 +876,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 +902,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 +916,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 +932,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 +948,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 +967,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 +988,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 +1014,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 +1024,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 +1032,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 +1055,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 +1079,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 +1092,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 +1109,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 +1122,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 +1141,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 +1156,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 +1176,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 +1186,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 +1194,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 +1209,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 +1227,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 +1240,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 +1254,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 +1269,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 +1282,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 +1290,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 +1298,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 +1314,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 +1334,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 +1350,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 +1390,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 +1422,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 +1461,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 +1499,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 +1512,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 +1531,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 +1541,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 +1549,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 +1562,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 +1579,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 +1592,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 +1608,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 +1621,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 +1636,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 +1644,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 +1652,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 +1668,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 +1686,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 +1705,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 +1718,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 +1737,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 +1747,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 +1755,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 +1768,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 +1785,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 +1798,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 +1814,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 +1827,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 +1842,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 +1850,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 +1862,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 +1883,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 +1905,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 +1927,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 +1938,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 +1957,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 +1965,6 @@ def test_acknowledge_empty_call(): client.acknowledge() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == pubsub.AcknowledgeRequest() @@ -2036,7 +1973,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 +1984,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 +2001,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 +2028,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 +2054,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 +2070,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 +2089,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 +2107,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 +2127,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 +2138,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 +2157,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 +2165,6 @@ def test_pull_empty_call(): client.pull() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == pubsub.PullRequest() @@ -2247,7 +2173,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 +2184,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 +2201,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 +2228,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 +2254,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 +2274,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 +2295,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 +2317,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 +2341,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 +2374,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 +2389,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 +2410,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 +2423,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 +2442,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 +2452,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 +2460,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 +2473,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 +2490,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 +2503,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 +2519,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 +2532,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 +2547,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 +2555,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 +2566,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 +2587,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 +2608,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 +2616,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 +2630,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 +2641,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 +2662,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 +2670,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 +2678,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 +2691,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 +2710,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 +2735,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 +2759,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 +2773,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 +2789,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 +2805,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 +2824,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 +2837,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 +2857,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 +2865,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 +2873,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 +2886,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 +2904,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 +2929,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 +2942,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 +2955,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 +2969,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 +2985,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 +3003,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 +3019,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 +3053,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 +3079,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 +3112,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 +3144,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 +3155,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 +3176,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 +3184,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 +3192,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 +3205,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 +3224,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 +3249,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 +3273,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 +3289,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 +3308,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 +3326,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 +3348,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 +3359,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 +3380,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 +3388,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 +3396,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 +3409,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 +3428,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 +3455,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 +3484,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 +3495,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 +3514,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 +3522,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 +3530,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 +3541,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 +3558,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 +3583,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 +3607,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 +3621,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 +3637,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 +3653,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 +3670,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 +3681,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 +3700,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 +3708,6 @@ def test_seek_empty_call(): client.seek() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == pubsub.SeekRequest() @@ -3876,7 +3716,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 +3727,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 +3744,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 +3771,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 +3799,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 +3818,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 +3829,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 +3838,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 +3856,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 +3884,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 +3915,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 +3964,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 +4004,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 +4045,51 @@ def test_subscriber_transport_auth_adc(): ) +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.SubscriberGrpcTransport, grpc_helpers), + (transports.SubscriberGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +def test_subscriber_transport_create_channel(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + + create_channel.assert_called_with( + "pubsub.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/pubsub", + ), + scopes=["1", "2"], + default_host="pubsub.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ("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: @@ -4160,10 +4103,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=[ @@ -4189,7 +4129,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 +4139,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 +4190,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", @@ -4268,10 +4208,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=[ @@ -4316,10 +4253,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=[ @@ -4334,7 +4268,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 +4290,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 +4312,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 +4331,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 +4351,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 +4369,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 +4387,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 +4406,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 +4432,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 +4441,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 +4469,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 +4479,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 +4502,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 +4510,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 +4535,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 +4559,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 +4576,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 +4593,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 +4614,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 +4624,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 +4647,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 +4655,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 +4680,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 +4704,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 +4721,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 +4738,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 +4763,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 +4771,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 +4784,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 +4798,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 +4831,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 +4843,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 +4859,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 +4878,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 2cc78d5e6110ab617227bf52d89b7413d4a32503 Mon Sep 17 00:00:00 2001 From: Anthonios Partheniou Date: Sat, 17 Jul 2021 10:53:13 +0000 Subject: [PATCH 10/14] Work around gapic generator docstring bug --- google/pubsub_v1/types/pubsub.py | 34 ++++++++++++++++++++++++++++++++ google/pubsub_v1/types/schema.py | 8 ++++++++ owlbot.py | 10 +++++++++- 3 files changed, 51 insertions(+), 1 deletion(-) diff --git a/google/pubsub_v1/types/pubsub.py b/google/pubsub_v1/types/pubsub.py index d105a9048..1aca5a7ed 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 @@ -1070,6 +1097,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 +1130,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 +1186,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 +1198,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 +1219,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 +1239,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 +1251,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/owlbot.py b/owlbot.py index 45035495a..988e8c129 100644 --- a/owlbot.py +++ b/owlbot.py @@ -25,7 +25,15 @@ default_version = "v1" -for library in s.get_staging_dirs(default_version): +for library in s.get_staging_dirs(default_version): + # Work around gapic generator bug https://github.com/googleapis/gapic-generator-python/issues/902 + s.replace(library / f"google/pubsub_{library.name}/types/*.py", + r""". + Attributes:""", + r""".\n + Attributes:""", + ) + # DEFAULT SCOPES and SERVICE_ADDRESS are being used. so let's force them in. s.replace( library / f"google/pubsub_{library.name}/services/*er/*client.py", From 4f5066bef716f2049aed2962b37e88d1764657c9 Mon Sep 17 00:00:00 2001 From: Anthonios Partheniou Date: Sat, 17 Jul 2021 11:33:21 +0000 Subject: [PATCH 11/14] 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 215f0bc519efabdf2c6a2818e48399f68a25fcb4 Mon Sep 17 00:00:00 2001 From: Anthonios Partheniou Date: Sun, 18 Jul 2021 10:24:41 +0000 Subject: [PATCH 12/14] Work around gapic generator docstring bug --- google/pubsub_v1/types/pubsub.py | 1 + owlbot.py | 8 ++++++++ 2 files changed, 9 insertions(+) diff --git a/google/pubsub_v1/types/pubsub.py b/google/pubsub_v1/types/pubsub.py index 1aca5a7ed..bfbbcaf87 100644 --- a/google/pubsub_v1/types/pubsub.py +++ b/google/pubsub_v1/types/pubsub.py @@ -1079,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 diff --git a/owlbot.py b/owlbot.py index 988e8c129..6cceccf8a 100644 --- a/owlbot.py +++ b/owlbot.py @@ -34,6 +34,14 @@ Attributes:""", ) + # Work around gapic generator bug https://github.com/googleapis/gapic-generator-python/issues/902 + s.replace(library / f"google/pubsub_{library.name}/types/*.py", + r""". + Attributes:""", + r""".\n + Attributes:""", + ) + # DEFAULT SCOPES and SERVICE_ADDRESS are being used. so let's force them in. s.replace( library / f"google/pubsub_{library.name}/services/*er/*client.py", From ab6a4a14f808a74d6b7586ea536bdafb4130746b Mon Sep 17 00:00:00 2001 From: Anthonios Partheniou Date: Sun, 18 Jul 2021 11:24:10 +0000 Subject: [PATCH 13/14] 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 From 280e41990c1b4a7d9fd18d668e8095bfa4773cfd Mon Sep 17 00:00:00 2001 From: Anthonios Partheniou Date: Sun, 18 Jul 2021 18:40:07 -0400 Subject: [PATCH 14/14] revert .coveragerc --- .coveragerc | 1 + 1 file changed, 1 insertion(+) diff --git a/.coveragerc b/.coveragerc index bcdb1c586..96190b454 100644 --- a/.coveragerc +++ b/.coveragerc @@ -4,6 +4,7 @@ branch = True [report] show_missing = True omit = + google/cloud/__init__.py google/pubsub/__init__.py exclude_lines = # Re-enable the standard pragma