diff --git a/.github/.OwlBot.lock.yaml b/.github/.OwlBot.lock.yaml new file mode 100644 index 00000000..da616c91 --- /dev/null +++ b/.github/.OwlBot.lock.yaml @@ -0,0 +1,3 @@ +docker: + image: gcr.io/repo-automation-bots/owlbot-python:latest + digest: sha256:c66ba3c8d7bc8566f47df841f98cd0097b28fff0b1864c86f5817f4c8c3e8600 diff --git a/.github/.OwlBot.yaml b/.github/.OwlBot.yaml new file mode 100644 index 00000000..e173f5a7 --- /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/cloud/tasks/(v.*)/.*-py/(.*) + dest: /owl-bot-staging/$1/$2 + +begin-after-commit-hash: 130ce904e5d546c312943d10f48799590f9c0f66 + diff --git a/.github/header-checker-lint.yml b/.github/header-checker-lint.yml index fc281c05..6fe78aa7 100644 --- a/.github/header-checker-lint.yml +++ b/.github/header-checker-lint.yml @@ -1,6 +1,6 @@ {"allowedCopyrightHolders": ["Google LLC"], "allowedLicenses": ["Apache-2.0", "MIT", "BSD-3"], - "ignoreFiles": ["**/requirements.txt", "**/requirements-test.txt"], + "ignoreFiles": ["**/requirements.txt", "**/requirements-test.txt", "**/__init__.py", "samples/**/constraints.txt", "samples/**/constraints-test.txt"], "sourceFileExtensions": [ "ts", "js", diff --git a/.github/sync-repo-settings.yaml b/.github/sync-repo-settings.yaml new file mode 100644 index 00000000..af599353 --- /dev/null +++ b/.github/sync-repo-settings.yaml @@ -0,0 +1,13 @@ +# https://github.com/googleapis/repo-automation-bots/tree/master/packages/sync-repo-settings +# Rules for master branch protection +branchProtectionRules: +# Identifies the protection rule pattern. Name of the branch to be protected. +# Defaults to `master` +- pattern: master + requiredStatusCheckContexts: + - 'Kokoro' + - 'cla/google' + - 'Samples - Lint' + - 'Samples - Python 3.6' + - 'Samples - Python 3.7' + - 'Samples - Python 3.8' diff --git a/.kokoro/release.sh b/.kokoro/release.sh index 7cce3b21..163eb07a 100755 --- a/.kokoro/release.sh +++ b/.kokoro/release.sh @@ -26,7 +26,7 @@ python3 -m pip install --upgrade twine wheel setuptools export PYTHONUNBUFFERED=1 # Move into the package, build the distribution and upload. -TWINE_PASSWORD=$(cat "${KOKORO_KEYSTORE_DIR}/73713_google_cloud_pypi_password") +TWINE_PASSWORD=$(cat "${KOKORO_GFILE_DIR}/secret_manager/google-cloud-pypi-token") cd github/python-tasks python3 setup.py sdist bdist_wheel -twine upload --username gcloudpypi --password "${TWINE_PASSWORD}" dist/* +twine upload --username __token__ --password "${TWINE_PASSWORD}" dist/* diff --git a/.kokoro/release/common.cfg b/.kokoro/release/common.cfg index bef59347..716e424e 100644 --- a/.kokoro/release/common.cfg +++ b/.kokoro/release/common.cfg @@ -23,18 +23,8 @@ env_vars: { value: "github/python-tasks/.kokoro/release.sh" } -# Fetch PyPI password -before_action { - fetch_keystore { - keystore_resource { - keystore_config_id: 73713 - keyname: "google_cloud_pypi_password" - } - } -} - # Tokens needed to report release status back to GitHub env_vars: { key: "SECRET_MANAGER_KEYS" - value: "releasetool-publish-reporter-app,releasetool-publish-reporter-googleapis-installation,releasetool-publish-reporter-pem" -} \ No newline at end of file + value: "releasetool-publish-reporter-app,releasetool-publish-reporter-googleapis-installation,releasetool-publish-reporter-pem,google-cloud-pypi-token" +} diff --git a/.kokoro/samples/python3.6/periodic-head.cfg b/.kokoro/samples/python3.6/periodic-head.cfg new file mode 100644 index 00000000..f9cfcd33 --- /dev/null +++ b/.kokoro/samples/python3.6/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.7/periodic-head.cfg b/.kokoro/samples/python3.7/periodic-head.cfg new file mode 100644 index 00000000..f9cfcd33 --- /dev/null +++ b/.kokoro/samples/python3.7/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.8/periodic-head.cfg b/.kokoro/samples/python3.8/periodic-head.cfg new file mode 100644 index 00000000..f9cfcd33 --- /dev/null +++ b/.kokoro/samples/python3.8/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/test-samples-against-head.sh b/.kokoro/test-samples-against-head.sh new file mode 100755 index 00000000..caf12508 --- /dev/null +++ b/.kokoro/test-samples-against-head.sh @@ -0,0 +1,28 @@ +#!/bin/bash +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# A customized test runner for samples. +# +# For periodic builds, you can specify this file for testing against head. + +# `-e` enables the script to automatically fail when a command fails +# `-o pipefail` sets the exit code to the rightmost comment to exit with a non-zero +set -eo pipefail +# Enables `**` to include files nested inside sub-folders +shopt -s globstar + +cd github/python-tasks + +exec .kokoro/test-samples-impl.sh diff --git a/.kokoro/test-samples-impl.sh b/.kokoro/test-samples-impl.sh new file mode 100755 index 00000000..cf5de74c --- /dev/null +++ b/.kokoro/test-samples-impl.sh @@ -0,0 +1,102 @@ +#!/bin/bash +# 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 +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + + +# `-e` enables the script to automatically fail when a command fails +# `-o pipefail` sets the exit code to the rightmost comment to exit with a non-zero +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 0 +fi + +# Disable buffering, so that the logs stream through. +export PYTHONUNBUFFERED=1 + +# Debug: show build environment +env | grep KOKORO + +# Install nox +python3.6 -m pip install --upgrade --quiet nox + +# Use secrets acessor service account to get secrets +if [[ -f "${KOKORO_GFILE_DIR}/secrets_viewer_service_account.json" ]]; then + gcloud auth activate-service-account \ + --key-file="${KOKORO_GFILE_DIR}/secrets_viewer_service_account.json" \ + --project="cloud-devrel-kokoro-resources" +fi + +# This script will create 3 files: +# - testing/test-env.sh +# - testing/service-account.json +# - testing/client-secrets.json +./scripts/decrypt-secrets.sh + +source ./testing/test-env.sh +export GOOGLE_APPLICATION_CREDENTIALS=$(pwd)/testing/service-account.json + +# For cloud-run session, we activate the service account for gcloud sdk. +gcloud auth activate-service-account \ + --key-file "${GOOGLE_APPLICATION_CREDENTIALS}" + +export GOOGLE_CLIENT_SECRETS=$(pwd)/testing/client-secrets.json + +echo -e "\n******************** TESTING PROJECTS ********************" + +# Switch to 'fail at end' to allow all tests to complete before exiting. +set +e +# Use RTN to return a non-zero value if the test fails. +RTN=0 +ROOT=$(pwd) +# Find all requirements.txt in the samples directory (may break on whitespace). +for file in samples/**/requirements.txt; do + cd "$ROOT" + # Navigate to the project folder. + file=$(dirname "$file") + cd "$file" + + echo "------------------------------------------------------------" + echo "- testing $file" + echo "------------------------------------------------------------" + + # Use nox to execute the tests for the project. + python3.6 -m nox -s "$RUN_TESTS_SESSION" + EXIT=$? + + # If this is a periodic build, send the test log to the FlakyBot. + # See https://github.com/googleapis/repo-automation-bots/tree/master/packages/flakybot. + if [[ $KOKORO_BUILD_ARTIFACTS_SUBDIR = *"periodic"* ]]; then + chmod +x $KOKORO_GFILE_DIR/linux_amd64/flakybot + $KOKORO_GFILE_DIR/linux_amd64/flakybot + fi + + if [[ $EXIT -ne 0 ]]; then + RTN=1 + echo -e "\n Testing failed: Nox returned a non-zero exit code. \n" + else + echo -e "\n Testing completed.\n" + fi + +done +cd "$ROOT" + +# Workaround for Kokoro permissions issue: delete secrets +rm testing/{test-env.sh,client-secrets.json,service-account.json} + +exit "$RTN" diff --git a/.kokoro/test-samples.sh b/.kokoro/test-samples.sh index 9ae2af48..fce0ad54 100755 --- a/.kokoro/test-samples.sh +++ b/.kokoro/test-samples.sh @@ -13,6 +13,10 @@ # See the License for the specific language governing permissions and # limitations under the License. +# The default test runner for samples. +# +# For periodic builds, we rewinds the repo to the latest release, and +# run test-samples-impl.sh. # `-e` enables the script to automatically fail when a command fails # `-o pipefail` sets the exit code to the rightmost comment to exit with a non-zero @@ -24,87 +28,19 @@ cd github/python-tasks # Run periodic samples tests at latest release if [[ $KOKORO_BUILD_ARTIFACTS_SUBDIR = *"periodic"* ]]; then + # preserving the test runner implementation. + cp .kokoro/test-samples-impl.sh "${TMPDIR}/test-samples-impl.sh" + echo "--- IMPORTANT IMPORTANT IMPORTANT ---" + echo "Now we rewind the repo back to the latest release..." LATEST_RELEASE=$(git describe --abbrev=0 --tags) git checkout $LATEST_RELEASE -fi - -# Exit early if samples directory doesn't exist -if [ ! -d "./samples" ]; then - echo "No tests run. `./samples` not found" - exit 0 -fi - -# Disable buffering, so that the logs stream through. -export PYTHONUNBUFFERED=1 - -# Debug: show build environment -env | grep KOKORO - -# Install nox -python3.6 -m pip install --upgrade --quiet nox - -# Use secrets acessor service account to get secrets -if [[ -f "${KOKORO_GFILE_DIR}/secrets_viewer_service_account.json" ]]; then - gcloud auth activate-service-account \ - --key-file="${KOKORO_GFILE_DIR}/secrets_viewer_service_account.json" \ - --project="cloud-devrel-kokoro-resources" -fi - -# This script will create 3 files: -# - testing/test-env.sh -# - testing/service-account.json -# - testing/client-secrets.json -./scripts/decrypt-secrets.sh - -source ./testing/test-env.sh -export GOOGLE_APPLICATION_CREDENTIALS=$(pwd)/testing/service-account.json - -# For cloud-run session, we activate the service account for gcloud sdk. -gcloud auth activate-service-account \ - --key-file "${GOOGLE_APPLICATION_CREDENTIALS}" - -export GOOGLE_CLIENT_SECRETS=$(pwd)/testing/client-secrets.json - -echo -e "\n******************** TESTING PROJECTS ********************" - -# Switch to 'fail at end' to allow all tests to complete before exiting. -set +e -# Use RTN to return a non-zero value if the test fails. -RTN=0 -ROOT=$(pwd) -# Find all requirements.txt in the samples directory (may break on whitespace). -for file in samples/**/requirements.txt; do - cd "$ROOT" - # Navigate to the project folder. - file=$(dirname "$file") - cd "$file" - - echo "------------------------------------------------------------" - echo "- testing $file" - echo "------------------------------------------------------------" - - # Use nox to execute the tests for the project. - python3.6 -m nox -s "$RUN_TESTS_SESSION" - EXIT=$? - - # If this is a periodic build, send the test log to the FlakyBot. - # See https://github.com/googleapis/repo-automation-bots/tree/master/packages/flakybot. - if [[ $KOKORO_BUILD_ARTIFACTS_SUBDIR = *"periodic"* ]]; then - chmod +x $KOKORO_GFILE_DIR/linux_amd64/flakybot - $KOKORO_GFILE_DIR/linux_amd64/flakybot + echo "The current head is: " + echo $(git rev-parse --verify HEAD) + echo "--- IMPORTANT IMPORTANT IMPORTANT ---" + # move back the test runner implementation if there's no file. + if [ ! -f .kokoro/test-samples-impl.sh ]; then + cp "${TMPDIR}/test-samples-impl.sh" .kokoro/test-samples-impl.sh fi +fi - if [[ $EXIT -ne 0 ]]; then - RTN=1 - echo -e "\n Testing failed: Nox returned a non-zero exit code. \n" - else - echo -e "\n Testing completed.\n" - fi - -done -cd "$ROOT" - -# Workaround for Kokoro permissions issue: delete secrets -rm testing/{test-env.sh,client-secrets.json,service-account.json} - -exit "$RTN" +exec .kokoro/test-samples-impl.sh diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index a9024b15..4f00c7cf 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -1,3 +1,17 @@ +# 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. +# # See https://pre-commit.com for more information # See https://pre-commit.com/hooks.html for more hooks repos: @@ -12,6 +26,6 @@ repos: hooks: - id: black - repo: https://gitlab.com/pycqa/flake8 - rev: 3.8.4 + rev: 3.9.2 hooks: - id: flake8 diff --git a/.repo-metadata.json b/.repo-metadata.json index cb495b91..eb967b47 100644 --- a/.repo-metadata.json +++ b/.repo-metadata.json @@ -6,6 +6,7 @@ "issue_tracker": "https://issuetracker.google.com/savedsearches/5433985", "release_level": "ga", "language": "python", + "library_type": "GAPIC_AUTO", "repo": "googleapis/python-tasks", "distribution_name": "google-cloud-tasks", "api_id": "cloudtasks.googleapis.com", diff --git a/CHANGELOG.md b/CHANGELOG.md index 2fe26573..799e65a5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,25 @@ [1]: https://pypi.org/project/google-cloud-tasks/#history +## [2.3.0](https://www.github.com/googleapis/python-tasks/compare/v2.2.0...v2.3.0) (2021-05-28) + + +### Features + +* add `from_service_account_info` ([#80](https://www.github.com/googleapis/python-tasks/issues/80)) ([2498225](https://www.github.com/googleapis/python-tasks/commit/2498225112ddb4b112b387dec71631c29a6db71e)) +* support self-signed JWT flow for service accounts ([1acf20c](https://www.github.com/googleapis/python-tasks/commit/1acf20ca440a5396ee03205b5c2301b84e368926)) + + +### Bug Fixes + +* add async client to %name_%version/init.py ([1acf20c](https://www.github.com/googleapis/python-tasks/commit/1acf20ca440a5396ee03205b5c2301b84e368926)) +* use correct retry deadlines ([2498225](https://www.github.com/googleapis/python-tasks/commit/2498225112ddb4b112b387dec71631c29a6db71e)) + + +### Documentation + +* fix grammar in documentation ([#112](https://www.github.com/googleapis/python-tasks/issues/112)) ([6f93a19](https://www.github.com/googleapis/python-tasks/commit/6f93a190311bd5468827496685072388a951e670)) + ## [2.2.0](https://www.github.com/googleapis/python-tasks/compare/v2.1.0...v2.2.0) (2021-02-24) diff --git a/CONTRIBUTING.rst b/CONTRIBUTING.rst index ad7cc2cb..463ae1ed 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/SECURITY.md b/SECURITY.md new file mode 100644 index 00000000..8b58ae9c --- /dev/null +++ b/SECURITY.md @@ -0,0 +1,7 @@ +# Security Policy + +To report a security issue, please use [g.co/vulnz](https://g.co/vulnz). + +The Google Security Team will respond within 5 working days of your report on g.co/vulnz. + +We use g.co/vulnz for our intake, and do coordination and disclosure here using GitHub Security Advisory to privately discuss and fix the issue. diff --git a/UPGRADING.md b/UPGRADING.md index 79609ef4..2b7175ad 100644 --- a/UPGRADING.md +++ b/UPGRADING.md @@ -17,10 +17,10 @@ The 2.0.0 release requires Python 3.6+. Methods expect request objects. We provide a script that will convert most common use cases. -* Install the library +* Install the library with `libcst`. ```py -python3 -m pip install google-cloud-tasks +python3 -m pip install google-cloud-tasks[libcst] ``` * The script `fixup_tasks_v2_keywords.py` is shipped with the library. It expects diff --git a/docs/_static/custom.css b/docs/_static/custom.css index bcd37bbd..b0a29546 100644 --- a/docs/_static/custom.css +++ b/docs/_static/custom.css @@ -1,9 +1,20 @@ div#python2-eol { border-color: red; border-width: medium; -} +} /* Ensure minimum width for 'Parameters' / 'Returns' column */ dl.field-list > dt { min-width: 100px } + +/* Insert space between methods for readability */ +dl.method { + padding-top: 10px; + padding-bottom: 10px +} + +/* Insert empty space between classes */ +dl.class { + padding-bottom: 50px +} diff --git a/docs/conf.py b/docs/conf.py index 00ccf92b..04ba95e8 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -1,4 +1,17 @@ # -*- coding: utf-8 -*- +# 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. # # google-cloud-tasks documentation build configuration file # @@ -350,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 1cb29d4c..536d17b2 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/docs/tasks_v2/cloud_tasks.rst b/docs/tasks_v2/cloud_tasks.rst index be98d0be..11481d7c 100644 --- a/docs/tasks_v2/cloud_tasks.rst +++ b/docs/tasks_v2/cloud_tasks.rst @@ -5,7 +5,6 @@ CloudTasks :members: :inherited-members: - .. automodule:: google.cloud.tasks_v2.services.cloud_tasks.pagers :members: :inherited-members: diff --git a/docs/tasks_v2beta2/cloud_tasks.rst b/docs/tasks_v2beta2/cloud_tasks.rst index 1fd4fc11..eacf8fb7 100644 --- a/docs/tasks_v2beta2/cloud_tasks.rst +++ b/docs/tasks_v2beta2/cloud_tasks.rst @@ -5,7 +5,6 @@ CloudTasks :members: :inherited-members: - .. automodule:: google.cloud.tasks_v2beta2.services.cloud_tasks.pagers :members: :inherited-members: diff --git a/docs/tasks_v2beta3/cloud_tasks.rst b/docs/tasks_v2beta3/cloud_tasks.rst index dfa0d867..ef422e09 100644 --- a/docs/tasks_v2beta3/cloud_tasks.rst +++ b/docs/tasks_v2beta3/cloud_tasks.rst @@ -5,7 +5,6 @@ CloudTasks :members: :inherited-members: - .. automodule:: google.cloud.tasks_v2beta3.services.cloud_tasks.pagers :members: :inherited-members: diff --git a/google/cloud/tasks/__init__.py b/google/cloud/tasks/__init__.py index 67168406..3bdc676d 100644 --- a/google/cloud/tasks/__init__.py +++ b/google/cloud/tasks/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -15,10 +14,11 @@ # limitations under the License. # +from google.cloud.tasks_v2.services.cloud_tasks.client import CloudTasksClient from google.cloud.tasks_v2.services.cloud_tasks.async_client import ( CloudTasksAsyncClient, ) -from google.cloud.tasks_v2.services.cloud_tasks.client import CloudTasksClient + from google.cloud.tasks_v2.types.cloudtasks import CreateQueueRequest from google.cloud.tasks_v2.types.cloudtasks import CreateTaskRequest from google.cloud.tasks_v2.types.cloudtasks import DeleteQueueRequest @@ -40,41 +40,41 @@ from google.cloud.tasks_v2.types.queue import StackdriverLoggingConfig from google.cloud.tasks_v2.types.target import AppEngineHttpRequest from google.cloud.tasks_v2.types.target import AppEngineRouting -from google.cloud.tasks_v2.types.target import HttpMethod from google.cloud.tasks_v2.types.target import HttpRequest from google.cloud.tasks_v2.types.target import OAuthToken from google.cloud.tasks_v2.types.target import OidcToken +from google.cloud.tasks_v2.types.target import HttpMethod from google.cloud.tasks_v2.types.task import Attempt from google.cloud.tasks_v2.types.task import Task __all__ = ( - "AppEngineHttpRequest", - "AppEngineRouting", - "Attempt", - "CloudTasksAsyncClient", "CloudTasksClient", + "CloudTasksAsyncClient", "CreateQueueRequest", "CreateTaskRequest", "DeleteQueueRequest", "DeleteTaskRequest", "GetQueueRequest", "GetTaskRequest", - "HttpMethod", - "HttpRequest", "ListQueuesRequest", "ListQueuesResponse", "ListTasksRequest", "ListTasksResponse", - "OAuthToken", - "OidcToken", "PauseQueueRequest", "PurgeQueueRequest", + "ResumeQueueRequest", + "RunTaskRequest", + "UpdateQueueRequest", "Queue", "RateLimits", - "ResumeQueueRequest", "RetryConfig", - "RunTaskRequest", "StackdriverLoggingConfig", + "AppEngineHttpRequest", + "AppEngineRouting", + "HttpRequest", + "OAuthToken", + "OidcToken", + "HttpMethod", + "Attempt", "Task", - "UpdateQueueRequest", ) diff --git a/google/cloud/tasks_v2/__init__.py b/google/cloud/tasks_v2/__init__.py index da740ea0..15f13226 100644 --- a/google/cloud/tasks_v2/__init__.py +++ b/google/cloud/tasks_v2/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -16,6 +15,8 @@ # from .services.cloud_tasks import CloudTasksClient +from .services.cloud_tasks import CloudTasksAsyncClient + from .types.cloudtasks import CreateQueueRequest from .types.cloudtasks import CreateTaskRequest from .types.cloudtasks import DeleteQueueRequest @@ -37,18 +38,19 @@ from .types.queue import StackdriverLoggingConfig from .types.target import AppEngineHttpRequest from .types.target import AppEngineRouting -from .types.target import HttpMethod from .types.target import HttpRequest from .types.target import OAuthToken from .types.target import OidcToken +from .types.target import HttpMethod from .types.task import Attempt from .types.task import Task - __all__ = ( + "CloudTasksAsyncClient", "AppEngineHttpRequest", "AppEngineRouting", "Attempt", + "CloudTasksClient", "CreateQueueRequest", "CreateTaskRequest", "DeleteQueueRequest", @@ -73,5 +75,4 @@ "StackdriverLoggingConfig", "Task", "UpdateQueueRequest", - "CloudTasksClient", ) diff --git a/google/cloud/tasks_v2/gapic_metadata.json b/google/cloud/tasks_v2/gapic_metadata.json new file mode 100644 index 00000000..5cacaba9 --- /dev/null +++ b/google/cloud/tasks_v2/gapic_metadata.json @@ -0,0 +1,183 @@ + { + "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", + "language": "python", + "libraryPackage": "google.cloud.tasks_v2", + "protoPackage": "google.cloud.tasks.v2", + "schema": "1.0", + "services": { + "CloudTasks": { + "clients": { + "grpc": { + "libraryClient": "CloudTasksClient", + "rpcs": { + "CreateQueue": { + "methods": [ + "create_queue" + ] + }, + "CreateTask": { + "methods": [ + "create_task" + ] + }, + "DeleteQueue": { + "methods": [ + "delete_queue" + ] + }, + "DeleteTask": { + "methods": [ + "delete_task" + ] + }, + "GetIamPolicy": { + "methods": [ + "get_iam_policy" + ] + }, + "GetQueue": { + "methods": [ + "get_queue" + ] + }, + "GetTask": { + "methods": [ + "get_task" + ] + }, + "ListQueues": { + "methods": [ + "list_queues" + ] + }, + "ListTasks": { + "methods": [ + "list_tasks" + ] + }, + "PauseQueue": { + "methods": [ + "pause_queue" + ] + }, + "PurgeQueue": { + "methods": [ + "purge_queue" + ] + }, + "ResumeQueue": { + "methods": [ + "resume_queue" + ] + }, + "RunTask": { + "methods": [ + "run_task" + ] + }, + "SetIamPolicy": { + "methods": [ + "set_iam_policy" + ] + }, + "TestIamPermissions": { + "methods": [ + "test_iam_permissions" + ] + }, + "UpdateQueue": { + "methods": [ + "update_queue" + ] + } + } + }, + "grpc-async": { + "libraryClient": "CloudTasksAsyncClient", + "rpcs": { + "CreateQueue": { + "methods": [ + "create_queue" + ] + }, + "CreateTask": { + "methods": [ + "create_task" + ] + }, + "DeleteQueue": { + "methods": [ + "delete_queue" + ] + }, + "DeleteTask": { + "methods": [ + "delete_task" + ] + }, + "GetIamPolicy": { + "methods": [ + "get_iam_policy" + ] + }, + "GetQueue": { + "methods": [ + "get_queue" + ] + }, + "GetTask": { + "methods": [ + "get_task" + ] + }, + "ListQueues": { + "methods": [ + "list_queues" + ] + }, + "ListTasks": { + "methods": [ + "list_tasks" + ] + }, + "PauseQueue": { + "methods": [ + "pause_queue" + ] + }, + "PurgeQueue": { + "methods": [ + "purge_queue" + ] + }, + "ResumeQueue": { + "methods": [ + "resume_queue" + ] + }, + "RunTask": { + "methods": [ + "run_task" + ] + }, + "SetIamPolicy": { + "methods": [ + "set_iam_policy" + ] + }, + "TestIamPermissions": { + "methods": [ + "test_iam_permissions" + ] + }, + "UpdateQueue": { + "methods": [ + "update_queue" + ] + } + } + } + } + } + } +} diff --git a/google/cloud/tasks_v2/services/__init__.py b/google/cloud/tasks_v2/services/__init__.py index 42ffdf2b..4de65971 100644 --- a/google/cloud/tasks_v2/services/__init__.py +++ b/google/cloud/tasks_v2/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/cloud/tasks_v2/services/cloud_tasks/__init__.py b/google/cloud/tasks_v2/services/cloud_tasks/__init__.py index 498f5941..d6abe162 100644 --- a/google/cloud/tasks_v2/services/cloud_tasks/__init__.py +++ b/google/cloud/tasks_v2/services/cloud_tasks/__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 CloudTasksClient from .async_client import CloudTasksAsyncClient diff --git a/google/cloud/tasks_v2/services/cloud_tasks/async_client.py b/google/cloud/tasks_v2/services/cloud_tasks/async_client.py index 11bc924e..c53c0ce4 100644 --- a/google/cloud/tasks_v2/services/cloud_tasks/async_client.py +++ b/google/cloud/tasks_v2/services/cloud_tasks/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,10 +20,10 @@ 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.cloud.tasks_v2.services.cloud_tasks import pagers @@ -35,12 +33,11 @@ from google.cloud.tasks_v2.types import target from google.cloud.tasks_v2.types import task from google.cloud.tasks_v2.types import task as gct_task -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 field_mask_pb2 as field_mask # 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 field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore from .transports.base import CloudTasksTransport, DEFAULT_CLIENT_INFO from .transports.grpc_asyncio import CloudTasksGrpcAsyncIOTransport from .client import CloudTasksClient @@ -60,37 +57,61 @@ class CloudTasksAsyncClient: parse_queue_path = staticmethod(CloudTasksClient.parse_queue_path) task_path = staticmethod(CloudTasksClient.task_path) parse_task_path = staticmethod(CloudTasksClient.parse_task_path) - common_billing_account_path = staticmethod( CloudTasksClient.common_billing_account_path ) parse_common_billing_account_path = staticmethod( CloudTasksClient.parse_common_billing_account_path ) - common_folder_path = staticmethod(CloudTasksClient.common_folder_path) parse_common_folder_path = staticmethod(CloudTasksClient.parse_common_folder_path) - common_organization_path = staticmethod(CloudTasksClient.common_organization_path) parse_common_organization_path = staticmethod( CloudTasksClient.parse_common_organization_path ) - common_project_path = staticmethod(CloudTasksClient.common_project_path) parse_common_project_path = staticmethod(CloudTasksClient.parse_common_project_path) - common_location_path = staticmethod(CloudTasksClient.common_location_path) parse_common_location_path = staticmethod( CloudTasksClient.parse_common_location_path ) - from_service_account_info = CloudTasksClient.from_service_account_info - from_service_account_file = CloudTasksClient.from_service_account_file + @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: + CloudTasksAsyncClient: The constructed client. + """ + return CloudTasksClient.from_service_account_info.__func__(CloudTasksAsyncClient, 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: + CloudTasksAsyncClient: The constructed client. + """ + return CloudTasksClient.from_service_account_file.__func__(CloudTasksAsyncClient, filename, *args, **kwargs) # type: ignore + from_service_account_json = from_service_account_file @property def transport(self) -> CloudTasksTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: CloudTasksTransport: The transport used by the client instance. @@ -104,12 +125,12 @@ def transport(self) -> CloudTasksTransport: def __init__( self, *, - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, transport: Union[str, CloudTasksTransport] = "grpc_asyncio", client_options: ClientOptions = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: - """Instantiate the cloud tasks client. + """Instantiates the cloud tasks client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -141,7 +162,6 @@ def __init__( google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport creation failed for any reason. """ - self._client = CloudTasksClient( credentials=credentials, transport=transport, @@ -172,7 +192,6 @@ async def list_queues( 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. @@ -202,7 +221,6 @@ async def list_queues( # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent @@ -215,8 +233,10 @@ async def list_queues( maximum=10.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), + deadline=10.0, ), default_timeout=10.0, client_info=DEFAULT_CLIENT_INFO, @@ -262,7 +282,6 @@ async def get_queue( 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. @@ -293,7 +312,6 @@ async def get_queue( # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -306,8 +324,10 @@ async def get_queue( maximum=10.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), + deadline=10.0, ), default_timeout=10.0, client_info=DEFAULT_CLIENT_INFO, @@ -372,7 +392,6 @@ async def create_queue( This corresponds to the ``queue`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -403,7 +422,6 @@ async def create_queue( # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent if queue is not None: @@ -434,7 +452,7 @@ async def update_queue( request: cloudtasks.UpdateQueueRequest = None, *, queue: gct_queue.Queue = None, - update_mask: field_mask.FieldMask = None, + update_mask: field_mask_pb2.FieldMask = None, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), @@ -482,7 +500,6 @@ async def update_queue( This corresponds to the ``update_mask`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -513,7 +530,6 @@ async def update_queue( # If we have keyword arguments corresponding to fields on the # request, apply these. - if queue is not None: request.queue = queue if update_mask is not None: @@ -574,7 +590,6 @@ async def delete_queue( 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. @@ -595,7 +610,6 @@ async def delete_queue( # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -608,8 +622,10 @@ async def delete_queue( maximum=10.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), + deadline=10.0, ), default_timeout=10.0, client_info=DEFAULT_CLIENT_INFO, @@ -653,7 +669,6 @@ async def purge_queue( 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. @@ -684,7 +699,6 @@ async def purge_queue( # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -737,7 +751,6 @@ async def pause_queue( 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. @@ -768,7 +781,6 @@ async def pause_queue( # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -828,7 +840,6 @@ async def resume_queue( 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. @@ -859,7 +870,6 @@ async def resume_queue( # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -885,13 +895,13 @@ async def resume_queue( async def get_iam_policy( self, - request: iam_policy.GetIamPolicyRequest = None, + request: iam_policy_pb2.GetIamPolicyRequest = None, *, resource: str = None, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), - ) -> policy.Policy: + ) -> policy_pb2.Policy: r"""Gets the access control policy for a [Queue][google.cloud.tasks.v2.Queue]. Returns an empty policy if the resource exists and does not have a policy set. @@ -915,7 +925,6 @@ async def get_iam_policy( This corresponds to the ``resource`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -994,10 +1003,9 @@ 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) elif not request: - request = iam_policy.GetIamPolicyRequest(resource=resource,) + request = iam_policy_pb2.GetIamPolicyRequest(resource=resource,) # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. @@ -1008,8 +1016,10 @@ async def get_iam_policy( maximum=10.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), + deadline=10.0, ), default_timeout=10.0, client_info=DEFAULT_CLIENT_INFO, @@ -1029,13 +1039,13 @@ async def get_iam_policy( async def set_iam_policy( self, - request: iam_policy.SetIamPolicyRequest = None, + request: iam_policy_pb2.SetIamPolicyRequest = None, *, resource: str = None, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), - ) -> policy.Policy: + ) -> policy_pb2.Policy: r"""Sets the access control policy for a [Queue][google.cloud.tasks.v2.Queue]. Replaces any existing policy. @@ -1063,7 +1073,6 @@ async def set_iam_policy( This corresponds to the ``resource`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -1142,10 +1151,9 @@ 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) elif not request: - request = iam_policy.SetIamPolicyRequest(resource=resource,) + request = iam_policy_pb2.SetIamPolicyRequest(resource=resource,) # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. @@ -1169,14 +1177,14 @@ async def set_iam_policy( async def test_iam_permissions( self, - request: iam_policy.TestIamPermissionsRequest = None, + request: iam_policy_pb2.TestIamPermissionsRequest = None, *, resource: str = None, permissions: Sequence[str] = None, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), - ) -> iam_policy.TestIamPermissionsResponse: + ) -> iam_policy_pb2.TestIamPermissionsResponse: r"""Returns permissions that a caller has on a [Queue][google.cloud.tasks.v2.Queue]. If the resource does not exist, this will return an empty set of permissions, not a @@ -1209,7 +1217,6 @@ async def test_iam_permissions( This corresponds to the ``permissions`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -1233,10 +1240,9 @@ 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) elif not request: - request = iam_policy.TestIamPermissionsRequest( + request = iam_policy_pb2.TestIamPermissionsRequest( resource=resource, permissions=permissions, ) @@ -1249,8 +1255,10 @@ async def test_iam_permissions( maximum=10.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), + deadline=10.0, ), default_timeout=10.0, client_info=DEFAULT_CLIENT_INFO, @@ -1300,7 +1308,6 @@ async def list_tasks( 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. @@ -1330,7 +1337,6 @@ async def list_tasks( # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent @@ -1343,8 +1349,10 @@ async def list_tasks( maximum=10.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), + deadline=10.0, ), default_timeout=10.0, client_info=DEFAULT_CLIENT_INFO, @@ -1391,7 +1399,6 @@ async def get_task( 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. @@ -1416,7 +1423,6 @@ async def get_task( # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -1429,8 +1435,10 @@ async def get_task( maximum=10.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), + deadline=10.0, ), default_timeout=10.0, client_info=DEFAULT_CLIENT_INFO, @@ -1524,7 +1532,6 @@ async def create_task( This corresponds to the ``task`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -1549,7 +1556,6 @@ async def create_task( # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent if task is not None: @@ -1601,7 +1607,6 @@ async def delete_task( 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. @@ -1622,7 +1627,6 @@ async def delete_task( # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -1635,8 +1639,10 @@ async def delete_task( maximum=10.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), + deadline=10.0, ), default_timeout=10.0, client_info=DEFAULT_CLIENT_INFO, @@ -1702,7 +1708,6 @@ async def run_task( 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. @@ -1727,7 +1732,6 @@ async def run_task( # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name diff --git a/google/cloud/tasks_v2/services/cloud_tasks/client.py b/google/cloud/tasks_v2/services/cloud_tasks/client.py index 7015960a..91180243 100644 --- a/google/cloud/tasks_v2/services/cloud_tasks/client.py +++ b/google/cloud/tasks_v2/services/cloud_tasks/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,10 +21,10 @@ 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 @@ -39,12 +37,11 @@ from google.cloud.tasks_v2.types import target from google.cloud.tasks_v2.types import task from google.cloud.tasks_v2.types import task as gct_task -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 field_mask_pb2 as field_mask # 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 field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore from .transports.base import CloudTasksTransport, DEFAULT_CLIENT_INFO from .transports.grpc import CloudTasksGrpcTransport from .transports.grpc_asyncio import CloudTasksGrpcAsyncIOTransport @@ -63,7 +60,7 @@ class CloudTasksClientMeta(type): _transport_registry["grpc_asyncio"] = CloudTasksGrpcAsyncIOTransport def get_transport_class(cls, label: str = None,) -> Type[CloudTasksTransport]: - """Return an appropriate transport class. + """Returns an appropriate transport class. Args: label: The name of the desired transport. If none is @@ -88,7 +85,8 @@ class CloudTasksClient(metaclass=CloudTasksClientMeta): @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: @@ -122,7 +120,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. @@ -139,7 +138,7 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials - file. + file. Args: filename (str): The path to the service account private key json @@ -158,23 +157,24 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> CloudTasksTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: - CloudTasksTransport: The transport used by the client instance. + CloudTasksTransport: The transport used by the client + instance. """ return self._transport @staticmethod def queue_path(project: str, location: str, queue: str,) -> str: - """Return a fully-qualified queue string.""" + """Returns a fully-qualified queue string.""" return "projects/{project}/locations/{location}/queues/{queue}".format( project=project, location=location, queue=queue, ) @staticmethod def parse_queue_path(path: str) -> Dict[str, str]: - """Parse a queue path into its component segments.""" + """Parses a queue path into its component segments.""" m = re.match( r"^projects/(?P.+?)/locations/(?P.+?)/queues/(?P.+?)$", path, @@ -183,14 +183,14 @@ def parse_queue_path(path: str) -> Dict[str, str]: @staticmethod def task_path(project: str, location: str, queue: str, task: str,) -> str: - """Return a fully-qualified task string.""" + """Returns a fully-qualified task string.""" return "projects/{project}/locations/{location}/queues/{queue}/tasks/{task}".format( project=project, location=location, queue=queue, task=task, ) @staticmethod def parse_task_path(path: str) -> Dict[str, str]: - """Parse a task path into its component segments.""" + """Parses a task path into its component segments.""" m = re.match( r"^projects/(?P.+?)/locations/(?P.+?)/queues/(?P.+?)/tasks/(?P.+?)$", path, @@ -199,7 +199,7 @@ def parse_task_path(path: str) -> Dict[str, str]: @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, ) @@ -212,7 +212,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 @@ -223,7 +223,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 @@ -234,7 +234,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 @@ -245,7 +245,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, ) @@ -259,12 +259,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, CloudTasksTransport, None] = None, client_options: Optional[client_options_lib.ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: - """Instantiate the cloud tasks client. + """Instantiates the cloud tasks client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -319,9 +319,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: @@ -333,12 +334,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. @@ -353,8 +356,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: @@ -392,7 +395,6 @@ def list_queues( 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. @@ -424,10 +426,8 @@ def list_queues( # there are no flattened fields. if not isinstance(request, cloudtasks.ListQueuesRequest): request = cloudtasks.ListQueuesRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent @@ -475,7 +475,6 @@ def get_queue( 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. @@ -508,10 +507,8 @@ def get_queue( # there are no flattened fields. if not isinstance(request, cloudtasks.GetQueueRequest): request = cloudtasks.GetQueueRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -578,7 +575,6 @@ def create_queue( This corresponds to the ``queue`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -611,10 +607,8 @@ def create_queue( # there are no flattened fields. if not isinstance(request, cloudtasks.CreateQueueRequest): request = cloudtasks.CreateQueueRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent if queue is not None: @@ -641,7 +635,7 @@ def update_queue( request: cloudtasks.UpdateQueueRequest = None, *, queue: gct_queue.Queue = None, - update_mask: field_mask.FieldMask = None, + update_mask: field_mask_pb2.FieldMask = None, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), @@ -689,7 +683,6 @@ def update_queue( This corresponds to the ``update_mask`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -722,10 +715,8 @@ def update_queue( # there are no flattened fields. if not isinstance(request, cloudtasks.UpdateQueueRequest): request = cloudtasks.UpdateQueueRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if queue is not None: request.queue = queue if update_mask is not None: @@ -782,7 +773,6 @@ def delete_queue( 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. @@ -805,10 +795,8 @@ def delete_queue( # there are no flattened fields. if not isinstance(request, cloudtasks.DeleteQueueRequest): request = cloudtasks.DeleteQueueRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -854,7 +842,6 @@ def purge_queue( 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. @@ -887,10 +874,8 @@ def purge_queue( # there are no flattened fields. if not isinstance(request, cloudtasks.PurgeQueueRequest): request = cloudtasks.PurgeQueueRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -939,7 +924,6 @@ def pause_queue( 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. @@ -972,10 +956,8 @@ def pause_queue( # there are no flattened fields. if not isinstance(request, cloudtasks.PauseQueueRequest): request = cloudtasks.PauseQueueRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -1031,7 +1013,6 @@ def resume_queue( 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. @@ -1064,10 +1045,8 @@ def resume_queue( # there are no flattened fields. if not isinstance(request, cloudtasks.ResumeQueueRequest): request = cloudtasks.ResumeQueueRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -1089,13 +1068,13 @@ def resume_queue( def get_iam_policy( self, - request: iam_policy.GetIamPolicyRequest = None, + request: iam_policy_pb2.GetIamPolicyRequest = None, *, resource: str = None, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), - ) -> policy.Policy: + ) -> policy_pb2.Policy: r"""Gets the access control policy for a [Queue][google.cloud.tasks.v2.Queue]. Returns an empty policy if the resource exists and does not have a policy set. @@ -1119,7 +1098,6 @@ def get_iam_policy( This corresponds to the ``resource`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -1195,14 +1173,13 @@ def get_iam_policy( "the individual field arguments should be set." ) - # 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) - + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + request = iam_policy_pb2.GetIamPolicyRequest(**request) elif not request: - request = iam_policy.GetIamPolicyRequest(resource=resource,) - + # Null request, just make one. + request = iam_policy_pb2.GetIamPolicyRequest() if resource is not None: request.resource = resource @@ -1224,13 +1201,13 @@ def get_iam_policy( def set_iam_policy( self, - request: iam_policy.SetIamPolicyRequest = None, + request: iam_policy_pb2.SetIamPolicyRequest = None, *, resource: str = None, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), - ) -> policy.Policy: + ) -> policy_pb2.Policy: r"""Sets the access control policy for a [Queue][google.cloud.tasks.v2.Queue]. Replaces any existing policy. @@ -1258,7 +1235,6 @@ def set_iam_policy( This corresponds to the ``resource`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -1334,14 +1310,13 @@ def set_iam_policy( "the individual field arguments should be set." ) - # 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) - + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + request = iam_policy_pb2.SetIamPolicyRequest(**request) elif not request: - request = iam_policy.SetIamPolicyRequest(resource=resource,) - + # Null request, just make one. + request = iam_policy_pb2.SetIamPolicyRequest() if resource is not None: request.resource = resource @@ -1363,14 +1338,14 @@ def set_iam_policy( def test_iam_permissions( self, - request: iam_policy.TestIamPermissionsRequest = None, + request: iam_policy_pb2.TestIamPermissionsRequest = None, *, resource: str = None, permissions: Sequence[str] = None, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), - ) -> iam_policy.TestIamPermissionsResponse: + ) -> iam_policy_pb2.TestIamPermissionsResponse: r"""Returns permissions that a caller has on a [Queue][google.cloud.tasks.v2.Queue]. If the resource does not exist, this will return an empty set of permissions, not a @@ -1403,7 +1378,6 @@ def test_iam_permissions( This corresponds to the ``permissions`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -1424,18 +1398,17 @@ def test_iam_permissions( "the individual field arguments should be set." ) - # 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) - + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + request = iam_policy_pb2.TestIamPermissionsRequest(**request) elif not request: - request = iam_policy.TestIamPermissionsRequest( - resource=resource, permissions=permissions, - ) - + # Null request, just make one. + request = iam_policy_pb2.TestIamPermissionsRequest() if resource is not None: request.resource = resource + if permissions: + request.permissions.extend(permissions) # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. @@ -1485,7 +1458,6 @@ def list_tasks( 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. @@ -1517,10 +1489,8 @@ def list_tasks( # there are no flattened fields. if not isinstance(request, cloudtasks.ListTasksRequest): request = cloudtasks.ListTasksRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent @@ -1569,7 +1539,6 @@ def get_task( 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. @@ -1596,10 +1565,8 @@ def get_task( # there are no flattened fields. if not isinstance(request, cloudtasks.GetTaskRequest): request = cloudtasks.GetTaskRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -1695,7 +1662,6 @@ def create_task( This corresponds to the ``task`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -1722,10 +1688,8 @@ def create_task( # there are no flattened fields. if not isinstance(request, cloudtasks.CreateTaskRequest): request = cloudtasks.CreateTaskRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent if task is not None: @@ -1773,7 +1737,6 @@ def delete_task( 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. @@ -1796,10 +1759,8 @@ def delete_task( # there are no flattened fields. if not isinstance(request, cloudtasks.DeleteTaskRequest): request = cloudtasks.DeleteTaskRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -1867,7 +1828,6 @@ def run_task( 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. @@ -1894,10 +1854,8 @@ def run_task( # there are no flattened fields. if not isinstance(request, cloudtasks.RunTaskRequest): request = cloudtasks.RunTaskRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name diff --git a/google/cloud/tasks_v2/services/cloud_tasks/pagers.py b/google/cloud/tasks_v2/services/cloud_tasks/pagers.py index 8d77668d..26d213e1 100644 --- a/google/cloud/tasks_v2/services/cloud_tasks/pagers.py +++ b/google/cloud/tasks_v2/services/cloud_tasks/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, @@ -119,7 +117,7 @@ def __init__( *, metadata: Sequence[Tuple[str, str]] = () ): - """Instantiate the pager. + """Instantiates the pager. Args: method (Callable): The method that was originally called, and @@ -247,7 +245,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/cloud/tasks_v2/services/cloud_tasks/transports/__init__.py b/google/cloud/tasks_v2/services/cloud_tasks/transports/__init__.py index f386bcfd..9056507e 100644 --- a/google/cloud/tasks_v2/services/cloud_tasks/transports/__init__.py +++ b/google/cloud/tasks_v2/services/cloud_tasks/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/cloud/tasks_v2/services/cloud_tasks/transports/base.py b/google/cloud/tasks_v2/services/cloud_tasks/transports/base.py index 6ba5f065..402cb230 100644 --- a/google/cloud/tasks_v2/services/cloud_tasks/transports/base.py +++ b/google/cloud/tasks_v2/services/cloud_tasks/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,26 +13,26 @@ # 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.cloud.tasks_v2.types import cloudtasks from google.cloud.tasks_v2.types import queue from google.cloud.tasks_v2.types import queue as gct_queue from google.cloud.tasks_v2.types import task from google.cloud.tasks_v2.types import task as gct_task -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 try: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( @@ -42,27 +41,41 @@ except pkg_resources.DistributionNotFound: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() +try: + # google.auth.__version__ was added in 1.26.0 + _GOOGLE_AUTH_VERSION = google.auth.__version__ +except AttributeError: + try: # try pkg_resources if it is available + _GOOGLE_AUTH_VERSION = pkg_resources.get_distribution("google-auth").version + except pkg_resources.DistributionNotFound: # pragma: NO COVER + _GOOGLE_AUTH_VERSION = None + +_API_CORE_VERSION = google.api_core.__version__ + class CloudTasksTransport(abc.ABC): """Abstract transport class for CloudTasks.""" AUTH_SCOPES = ("https://www.googleapis.com/auth/cloud-platform",) + DEFAULT_HOST: str = "cloudtasks.googleapis.com" + def __init__( self, *, - host: str = "cloudtasks.googleapis.com", - credentials: credentials.Credentials = None, - credentials_file: typing.Optional[str] = None, - scopes: typing.Optional[typing.Sequence[str]] = AUTH_SCOPES, - quota_project_id: typing.Optional[str] = None, + host: str = DEFAULT_HOST, + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, **kwargs, ) -> None: """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + host (Optional[str]): + The hostname to connect to. credentials (Optional[google.auth.credentials.Credentials]): The authorization credentials to attach to requests. These credentials identify the application to the service; if none @@ -71,13 +84,13 @@ 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): - 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 + 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. @@ -85,28 +98,75 @@ def __init__( host += ":443" self._host = host + scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) + + # Save the scopes. + self._scopes = scopes or self.AUTH_SCOPES + # If no credentials are provided, then determine the appropriate # defaults. if credentials and credentials_file: - raise exceptions.DuplicateCredentialArgs( + raise core_exceptions.DuplicateCredentialArgs( "'credentials_file' and 'credentials' are mutually exclusive" ) if credentials_file is not None: - credentials, _ = auth.load_credentials_from_file( - credentials_file, scopes=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=scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.default( + **scopes_kwargs, quota_project_id=quota_project_id ) # Save the credentials. self._credentials = credentials - # Lifted into its own function so it can be stubbed out during tests. - self._prep_wrapped_messages(client_info) + # TODO(busunkim): These two class methods are in the base transport + # to avoid duplicating code across the transport classes. These functions + # should be deleted once the minimum required versions of google-api-core + # and google-auth are increased. + + # TODO: Remove this function once google-auth >= 1.25.0 is required + @classmethod + def _get_scopes_kwargs( + cls, host: str, scopes: Optional[Sequence[str]] + ) -> Dict[str, Optional[Sequence[str]]]: + """Returns scopes kwargs to pass to google-auth methods depending on the google-auth version""" + + scopes_kwargs = {} + + if _GOOGLE_AUTH_VERSION and ( + packaging.version.parse(_GOOGLE_AUTH_VERSION) + >= packaging.version.parse("1.25.0") + ): + scopes_kwargs = {"scopes": scopes, "default_scopes": cls.AUTH_SCOPES} + else: + scopes_kwargs = {"scopes": scopes or cls.AUTH_SCOPES} + + return scopes_kwargs + + # TODO: Remove this function once google-api-core >= 1.26.0 is required + @classmethod + def _get_self_signed_jwt_kwargs( + cls, host: str, scopes: Optional[Sequence[str]] + ) -> Dict[str, Union[Optional[Sequence[str]], str]]: + """Returns kwargs to pass to grpc_helpers.create_channel depending on the google-api-core version""" + + self_signed_jwt_kwargs: Dict[str, Union[Optional[Sequence[str]], str]] = {} + + if _API_CORE_VERSION and ( + packaging.version.parse(_API_CORE_VERSION) + >= packaging.version.parse("1.26.0") + ): + self_signed_jwt_kwargs["default_scopes"] = cls.AUTH_SCOPES + self_signed_jwt_kwargs["scopes"] = scopes + self_signed_jwt_kwargs["default_host"] = cls.DEFAULT_HOST + else: + self_signed_jwt_kwargs["scopes"] = scopes or cls.AUTH_SCOPES + + return self_signed_jwt_kwargs def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. @@ -118,8 +178,10 @@ def _prep_wrapped_messages(self, client_info): maximum=10.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), + deadline=10.0, ), default_timeout=10.0, client_info=client_info, @@ -131,8 +193,10 @@ def _prep_wrapped_messages(self, client_info): maximum=10.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), + deadline=10.0, ), default_timeout=10.0, client_info=client_info, @@ -150,8 +214,10 @@ def _prep_wrapped_messages(self, client_info): maximum=10.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), + deadline=10.0, ), default_timeout=10.0, client_info=client_info, @@ -172,8 +238,10 @@ def _prep_wrapped_messages(self, client_info): maximum=10.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), + deadline=10.0, ), default_timeout=10.0, client_info=client_info, @@ -188,8 +256,10 @@ def _prep_wrapped_messages(self, client_info): maximum=10.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), + deadline=10.0, ), default_timeout=10.0, client_info=client_info, @@ -201,8 +271,10 @@ def _prep_wrapped_messages(self, client_info): maximum=10.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), + deadline=10.0, ), default_timeout=10.0, client_info=client_info, @@ -214,8 +286,10 @@ def _prep_wrapped_messages(self, client_info): maximum=10.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), + deadline=10.0, ), default_timeout=10.0, client_info=client_info, @@ -230,8 +304,10 @@ def _prep_wrapped_messages(self, client_info): maximum=10.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), + deadline=10.0, ), default_timeout=10.0, client_info=client_info, @@ -244,104 +320,97 @@ def _prep_wrapped_messages(self, client_info): @property def list_queues( self, - ) -> typing.Callable[ + ) -> Callable[ [cloudtasks.ListQueuesRequest], - typing.Union[ - cloudtasks.ListQueuesResponse, - typing.Awaitable[cloudtasks.ListQueuesResponse], - ], + Union[cloudtasks.ListQueuesResponse, Awaitable[cloudtasks.ListQueuesResponse]], ]: raise NotImplementedError() @property def get_queue( self, - ) -> typing.Callable[ - [cloudtasks.GetQueueRequest], - typing.Union[queue.Queue, typing.Awaitable[queue.Queue]], + ) -> Callable[ + [cloudtasks.GetQueueRequest], Union[queue.Queue, Awaitable[queue.Queue]] ]: raise NotImplementedError() @property def create_queue( self, - ) -> typing.Callable[ + ) -> Callable[ [cloudtasks.CreateQueueRequest], - typing.Union[gct_queue.Queue, typing.Awaitable[gct_queue.Queue]], + Union[gct_queue.Queue, Awaitable[gct_queue.Queue]], ]: raise NotImplementedError() @property def update_queue( self, - ) -> typing.Callable[ + ) -> Callable[ [cloudtasks.UpdateQueueRequest], - typing.Union[gct_queue.Queue, typing.Awaitable[gct_queue.Queue]], + Union[gct_queue.Queue, Awaitable[gct_queue.Queue]], ]: raise NotImplementedError() @property def delete_queue( self, - ) -> typing.Callable[ + ) -> Callable[ [cloudtasks.DeleteQueueRequest], - typing.Union[empty.Empty, typing.Awaitable[empty.Empty]], + Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]], ]: raise NotImplementedError() @property def purge_queue( self, - ) -> typing.Callable[ - [cloudtasks.PurgeQueueRequest], - typing.Union[queue.Queue, typing.Awaitable[queue.Queue]], + ) -> Callable[ + [cloudtasks.PurgeQueueRequest], Union[queue.Queue, Awaitable[queue.Queue]] ]: raise NotImplementedError() @property def pause_queue( self, - ) -> typing.Callable[ - [cloudtasks.PauseQueueRequest], - typing.Union[queue.Queue, typing.Awaitable[queue.Queue]], + ) -> Callable[ + [cloudtasks.PauseQueueRequest], Union[queue.Queue, Awaitable[queue.Queue]] ]: raise NotImplementedError() @property def resume_queue( self, - ) -> typing.Callable[ - [cloudtasks.ResumeQueueRequest], - typing.Union[queue.Queue, typing.Awaitable[queue.Queue]], + ) -> Callable[ + [cloudtasks.ResumeQueueRequest], Union[queue.Queue, Awaitable[queue.Queue]] ]: 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 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 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() @@ -349,48 +418,39 @@ def test_iam_permissions( @property def list_tasks( self, - ) -> typing.Callable[ + ) -> Callable[ [cloudtasks.ListTasksRequest], - typing.Union[ - cloudtasks.ListTasksResponse, typing.Awaitable[cloudtasks.ListTasksResponse] - ], + Union[cloudtasks.ListTasksResponse, Awaitable[cloudtasks.ListTasksResponse]], ]: raise NotImplementedError() @property def get_task( self, - ) -> typing.Callable[ - [cloudtasks.GetTaskRequest], - typing.Union[task.Task, typing.Awaitable[task.Task]], - ]: + ) -> Callable[[cloudtasks.GetTaskRequest], Union[task.Task, Awaitable[task.Task]]]: raise NotImplementedError() @property def create_task( self, - ) -> typing.Callable[ - [cloudtasks.CreateTaskRequest], - typing.Union[gct_task.Task, typing.Awaitable[gct_task.Task]], + ) -> Callable[ + [cloudtasks.CreateTaskRequest], Union[gct_task.Task, Awaitable[gct_task.Task]] ]: raise NotImplementedError() @property def delete_task( self, - ) -> typing.Callable[ + ) -> Callable[ [cloudtasks.DeleteTaskRequest], - typing.Union[empty.Empty, typing.Awaitable[empty.Empty]], + Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]], ]: raise NotImplementedError() @property def run_task( self, - ) -> typing.Callable[ - [cloudtasks.RunTaskRequest], - typing.Union[task.Task, typing.Awaitable[task.Task]], - ]: + ) -> Callable[[cloudtasks.RunTaskRequest], Union[task.Task, Awaitable[task.Task]]]: raise NotImplementedError() diff --git a/google/cloud/tasks_v2/services/cloud_tasks/transports/grpc.py b/google/cloud/tasks_v2/services/cloud_tasks/transports/grpc.py index c6fa24ef..e7f3ceac 100644 --- a/google/cloud/tasks_v2/services/cloud_tasks/transports/grpc.py +++ b/google/cloud/tasks_v2/services/cloud_tasks/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,14 +13,13 @@ # 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 @@ -31,10 +29,9 @@ from google.cloud.tasks_v2.types import queue as gct_queue from google.cloud.tasks_v2.types import task from google.cloud.tasks_v2.types import task as gct_task -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 .base import CloudTasksTransport, DEFAULT_CLIENT_INFO @@ -58,7 +55,7 @@ def __init__( self, *, host: str = "cloudtasks.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Sequence[str] = None, channel: grpc.Channel = None, @@ -72,7 +69,8 @@ def __init__( """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + host (Optional[str]): + The hostname to connect to. credentials (Optional[google.auth.credentials.Credentials]): The authorization credentials to attach to requests. These credentials identify the application to the service; if none @@ -114,7 +112,9 @@ def __init__( 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) @@ -122,70 +122,50 @@ def __init__( warnings.warn("client_cert_source is deprecated", DeprecationWarning) if channel: - # Sanity check: Ensure that channel and credentials are not both - # provided. + # 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 - elif api_mtls_endpoint: - host = ( - api_mtls_endpoint - if ":" in api_mtls_endpoint - else api_mtls_endpoint + ":443" - ) - if credentials is None: - credentials, _ = auth.default( - scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id - ) - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - ssl_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - ssl_credentials = SslCredentials().ssl_credentials - - # create a new channel. The provided one is ignored. - self._grpc_channel = type(self).create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - ssl_credentials=ssl_credentials, - scopes=scopes or self.AUTH_SCOPES, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - self._ssl_channel_credentials = ssl_credentials else: - host = host if ":" in host else host + ":443" + 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 - if credentials is None: - credentials, _ = auth.default( - scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id - ) + 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 + ) - 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, + ) - # create a new channel. The provided one is ignored. + if not self._grpc_channel: self._grpc_channel = type(self).create_channel( - host, - credentials=credentials, + self._host, + credentials=self._credentials, credentials_file=credentials_file, + scopes=self._scopes, ssl_credentials=self._ssl_channel_credentials, - scopes=scopes or self.AUTH_SCOPES, quota_project_id=quota_project_id, options=[ ("grpc.max_send_message_length", -1), @@ -193,23 +173,14 @@ def __init__( ], ) - self._stubs = {} # type: Dict[str, Callable] - - # Run the base constructor. - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes or self.AUTH_SCOPES, - quota_project_id=quota_project_id, - client_info=client_info, - ) + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) @classmethod def create_channel( cls, host: str = "cloudtasks.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, @@ -217,7 +188,7 @@ def create_channel( ) -> grpc.Channel: """Create and return a gRPC channel object. Args: - address (Optional[str]): The host for the channel to use. + 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 @@ -240,13 +211,15 @@ def create_channel( google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` and ``credentials_file`` are passed. """ - scopes = scopes or cls.AUTH_SCOPES + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + return grpc_helpers.create_channel( host, credentials=credentials, credentials_file=credentials_file, - scopes=scopes, quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, **kwargs, ) @@ -383,7 +356,9 @@ def update_queue( return self._stubs["update_queue"] @property - def delete_queue(self) -> Callable[[cloudtasks.DeleteQueueRequest], empty.Empty]: + def delete_queue( + self, + ) -> Callable[[cloudtasks.DeleteQueueRequest], empty_pb2.Empty]: r"""Return a callable for the delete queue method over gRPC. Deletes a queue. @@ -413,7 +388,7 @@ def delete_queue(self) -> Callable[[cloudtasks.DeleteQueueRequest], empty.Empty] self._stubs["delete_queue"] = self.grpc_channel.unary_unary( "/google.cloud.tasks.v2.CloudTasks/DeleteQueue", request_serializer=cloudtasks.DeleteQueueRequest.serialize, - response_deserializer=empty.Empty.FromString, + response_deserializer=empty_pb2.Empty.FromString, ) return self._stubs["delete_queue"] @@ -518,7 +493,7 @@ def resume_queue(self) -> Callable[[cloudtasks.ResumeQueueRequest], queue.Queue] @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 access control policy for a @@ -544,15 +519,15 @@ def get_iam_policy( if "get_iam_policy" not in self._stubs: self._stubs["get_iam_policy"] = self.grpc_channel.unary_unary( "/google.cloud.tasks.v2.CloudTasks/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"] @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 access control policy for a @@ -582,8 +557,8 @@ def set_iam_policy( if "set_iam_policy" not in self._stubs: self._stubs["set_iam_policy"] = self.grpc_channel.unary_unary( "/google.cloud.tasks.v2.CloudTasks/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"] @@ -591,7 +566,8 @@ def set_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. @@ -618,8 +594,8 @@ def test_iam_permissions( if "test_iam_permissions" not in self._stubs: self._stubs["test_iam_permissions"] = self.grpc_channel.unary_unary( "/google.cloud.tasks.v2.CloudTasks/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"] @@ -712,7 +688,7 @@ def create_task(self) -> Callable[[cloudtasks.CreateTaskRequest], gct_task.Task] return self._stubs["create_task"] @property - def delete_task(self) -> Callable[[cloudtasks.DeleteTaskRequest], empty.Empty]: + def delete_task(self) -> Callable[[cloudtasks.DeleteTaskRequest], empty_pb2.Empty]: r"""Return a callable for the delete task method over gRPC. Deletes a task. @@ -734,7 +710,7 @@ def delete_task(self) -> Callable[[cloudtasks.DeleteTaskRequest], empty.Empty]: self._stubs["delete_task"] = self.grpc_channel.unary_unary( "/google.cloud.tasks.v2.CloudTasks/DeleteTask", request_serializer=cloudtasks.DeleteTaskRequest.serialize, - response_deserializer=empty.Empty.FromString, + response_deserializer=empty_pb2.Empty.FromString, ) return self._stubs["delete_task"] diff --git a/google/cloud/tasks_v2/services/cloud_tasks/transports/grpc_asyncio.py b/google/cloud/tasks_v2/services/cloud_tasks/transports/grpc_asyncio.py index aab98e3a..4773ed21 100644 --- a/google/cloud/tasks_v2/services/cloud_tasks/transports/grpc_asyncio.py +++ b/google/cloud/tasks_v2/services/cloud_tasks/transports/grpc_asyncio.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,15 +13,14 @@ # 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 @@ -32,10 +30,9 @@ from google.cloud.tasks_v2.types import queue as gct_queue from google.cloud.tasks_v2.types import task from google.cloud.tasks_v2.types import task as gct_task -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 .base import CloudTasksTransport, DEFAULT_CLIENT_INFO from .grpc import CloudTasksGrpcTransport @@ -61,7 +58,7 @@ class CloudTasksGrpcAsyncIOTransport(CloudTasksTransport): def create_channel( cls, host: str = "cloudtasks.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, @@ -69,7 +66,7 @@ def create_channel( ) -> aio.Channel: """Create and return a gRPC AsyncIO channel object. Args: - address (Optional[str]): The host for the channel to use. + 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 @@ -88,13 +85,15 @@ def create_channel( Returns: aio.Channel: A gRPC AsyncIO channel object. """ - scopes = scopes or cls.AUTH_SCOPES + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + return grpc_helpers_async.create_channel( host, credentials=credentials, credentials_file=credentials_file, - scopes=scopes, quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, **kwargs, ) @@ -102,7 +101,7 @@ def __init__( self, *, host: str = "cloudtasks.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, @@ -116,7 +115,8 @@ def __init__( """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + host (Optional[str]): + The hostname to connect to. credentials (Optional[google.auth.credentials.Credentials]): The authorization credentials to attach to requests. These credentials identify the application to the service; if none @@ -147,10 +147,10 @@ def __init__( 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 + 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: @@ -159,7 +159,9 @@ def __init__( 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) @@ -167,70 +169,49 @@ def __init__( warnings.warn("client_cert_source is deprecated", DeprecationWarning) if channel: - # Sanity check: Ensure that channel and credentials are not both - # provided. + # 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 - elif api_mtls_endpoint: - host = ( - api_mtls_endpoint - if ":" in api_mtls_endpoint - else api_mtls_endpoint + ":443" - ) - - if credentials is None: - credentials, _ = auth.default( - scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id - ) - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - ssl_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - ssl_credentials = SslCredentials().ssl_credentials - - # create a new channel. The provided one is ignored. - self._grpc_channel = type(self).create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - ssl_credentials=ssl_credentials, - scopes=scopes or self.AUTH_SCOPES, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - self._ssl_channel_credentials = ssl_credentials else: - host = host if ":" in host else host + ":443" + 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 - if credentials is None: - credentials, _ = auth.default( - scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id - ) + 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 + ) - 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, + ) - # create a new channel. The provided one is ignored. + if not self._grpc_channel: self._grpc_channel = type(self).create_channel( - host, - credentials=credentials, + self._host, + credentials=self._credentials, credentials_file=credentials_file, + scopes=self._scopes, ssl_credentials=self._ssl_channel_credentials, - scopes=scopes or self.AUTH_SCOPES, quota_project_id=quota_project_id, options=[ ("grpc.max_send_message_length", -1), @@ -238,17 +219,8 @@ def __init__( ], ) - # Run the base constructor. - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes or self.AUTH_SCOPES, - quota_project_id=quota_project_id, - client_info=client_info, - ) - - self._stubs = {} + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) @property def grpc_channel(self) -> aio.Channel: @@ -393,7 +365,7 @@ def update_queue( @property def delete_queue( self, - ) -> Callable[[cloudtasks.DeleteQueueRequest], Awaitable[empty.Empty]]: + ) -> Callable[[cloudtasks.DeleteQueueRequest], Awaitable[empty_pb2.Empty]]: r"""Return a callable for the delete queue method over gRPC. Deletes a queue. @@ -423,7 +395,7 @@ def delete_queue( self._stubs["delete_queue"] = self.grpc_channel.unary_unary( "/google.cloud.tasks.v2.CloudTasks/DeleteQueue", request_serializer=cloudtasks.DeleteQueueRequest.serialize, - response_deserializer=empty.Empty.FromString, + response_deserializer=empty_pb2.Empty.FromString, ) return self._stubs["delete_queue"] @@ -534,7 +506,7 @@ def resume_queue( @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 access control policy for a @@ -560,15 +532,15 @@ def get_iam_policy( if "get_iam_policy" not in self._stubs: self._stubs["get_iam_policy"] = self.grpc_channel.unary_unary( "/google.cloud.tasks.v2.CloudTasks/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"] @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 access control policy for a @@ -598,8 +570,8 @@ def set_iam_policy( if "set_iam_policy" not in self._stubs: self._stubs["set_iam_policy"] = self.grpc_channel.unary_unary( "/google.cloud.tasks.v2.CloudTasks/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"] @@ -607,8 +579,8 @@ def set_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. @@ -635,8 +607,8 @@ def test_iam_permissions( if "test_iam_permissions" not in self._stubs: self._stubs["test_iam_permissions"] = self.grpc_channel.unary_unary( "/google.cloud.tasks.v2.CloudTasks/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"] @@ -735,7 +707,7 @@ def create_task( @property def delete_task( self, - ) -> Callable[[cloudtasks.DeleteTaskRequest], Awaitable[empty.Empty]]: + ) -> Callable[[cloudtasks.DeleteTaskRequest], Awaitable[empty_pb2.Empty]]: r"""Return a callable for the delete task method over gRPC. Deletes a task. @@ -757,7 +729,7 @@ def delete_task( self._stubs["delete_task"] = self.grpc_channel.unary_unary( "/google.cloud.tasks.v2.CloudTasks/DeleteTask", request_serializer=cloudtasks.DeleteTaskRequest.serialize, - response_deserializer=empty.Empty.FromString, + response_deserializer=empty_pb2.Empty.FromString, ) return self._stubs["delete_task"] diff --git a/google/cloud/tasks_v2/types/__init__.py b/google/cloud/tasks_v2/types/__init__.py index dabf6553..1b4933ee 100644 --- a/google/cloud/tasks_v2/types/__init__.py +++ b/google/cloud/tasks_v2/types/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,14 +13,22 @@ # See the License for the specific language governing permissions and # limitations under the License. # - -from .target import ( - HttpRequest, - AppEngineHttpRequest, - AppEngineRouting, - OAuthToken, - OidcToken, - HttpMethod, +from .cloudtasks import ( + CreateQueueRequest, + CreateTaskRequest, + DeleteQueueRequest, + DeleteTaskRequest, + GetQueueRequest, + GetTaskRequest, + ListQueuesRequest, + ListQueuesResponse, + ListTasksRequest, + ListTasksResponse, + PauseQueueRequest, + PurgeQueueRequest, + ResumeQueueRequest, + RunTaskRequest, + UpdateQueueRequest, ) from .queue import ( Queue, @@ -29,54 +36,45 @@ RetryConfig, StackdriverLoggingConfig, ) +from .target import ( + AppEngineHttpRequest, + AppEngineRouting, + HttpRequest, + OAuthToken, + OidcToken, + HttpMethod, +) from .task import ( - Task, Attempt, -) -from .cloudtasks import ( - ListQueuesRequest, - ListQueuesResponse, - GetQueueRequest, - CreateQueueRequest, - UpdateQueueRequest, - DeleteQueueRequest, - PurgeQueueRequest, - PauseQueueRequest, - ResumeQueueRequest, - ListTasksRequest, - ListTasksResponse, - GetTaskRequest, - CreateTaskRequest, - DeleteTaskRequest, - RunTaskRequest, + Task, ) __all__ = ( - "HttpRequest", + "CreateQueueRequest", + "CreateTaskRequest", + "DeleteQueueRequest", + "DeleteTaskRequest", + "GetQueueRequest", + "GetTaskRequest", + "ListQueuesRequest", + "ListQueuesResponse", + "ListTasksRequest", + "ListTasksResponse", + "PauseQueueRequest", + "PurgeQueueRequest", + "ResumeQueueRequest", + "RunTaskRequest", + "UpdateQueueRequest", + "Queue", + "RateLimits", + "RetryConfig", + "StackdriverLoggingConfig", "AppEngineHttpRequest", "AppEngineRouting", + "HttpRequest", "OAuthToken", "OidcToken", "HttpMethod", - "Queue", - "RateLimits", - "RetryConfig", - "StackdriverLoggingConfig", - "Task", "Attempt", - "ListQueuesRequest", - "ListQueuesResponse", - "GetQueueRequest", - "CreateQueueRequest", - "UpdateQueueRequest", - "DeleteQueueRequest", - "PurgeQueueRequest", - "PauseQueueRequest", - "ResumeQueueRequest", - "ListTasksRequest", - "ListTasksResponse", - "GetTaskRequest", - "CreateTaskRequest", - "DeleteTaskRequest", - "RunTaskRequest", + "Task", ) diff --git a/google/cloud/tasks_v2/types/cloudtasks.py b/google/cloud/tasks_v2/types/cloudtasks.py index 7354ffde..0bea3349 100644 --- a/google/cloud/tasks_v2/types/cloudtasks.py +++ b/google/cloud/tasks_v2/types/cloudtasks.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.cloud.tasks_v2.types import queue as gct_queue from google.cloud.tasks_v2.types import task as gct_task -from google.protobuf import field_mask_pb2 as field_mask # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore __protobuf__ = proto.module( @@ -87,13 +84,10 @@ class ListQueuesRequest(proto.Message): while iterating through pages. """ - parent = proto.Field(proto.STRING, number=1) - - filter = proto.Field(proto.STRING, number=2) - - page_size = proto.Field(proto.INT32, number=3) - - page_token = proto.Field(proto.STRING, number=4) + parent = proto.Field(proto.STRING, number=1,) + filter = proto.Field(proto.STRING, number=2,) + page_size = proto.Field(proto.INT32, number=3,) + page_token = proto.Field(proto.STRING, number=4,) class ListQueuesResponse(proto.Message): @@ -121,8 +115,7 @@ def raw_page(self): return self queues = proto.RepeatedField(proto.MESSAGE, number=1, message=gct_queue.Queue,) - - next_page_token = proto.Field(proto.STRING, number=2) + next_page_token = proto.Field(proto.STRING, number=2,) class GetQueueRequest(proto.Message): @@ -135,7 +128,7 @@ class GetQueueRequest(proto.Message): ``projects/PROJECT_ID/locations/LOCATION_ID/queues/QUEUE_ID`` """ - name = proto.Field(proto.STRING, number=1) + name = proto.Field(proto.STRING, number=1,) class CreateQueueRequest(proto.Message): @@ -158,8 +151,7 @@ class CreateQueueRequest(proto.Message): the same as an existing queue. """ - parent = proto.Field(proto.STRING, number=1) - + parent = proto.Field(proto.STRING, number=1,) queue = proto.Field(proto.MESSAGE, number=2, message=gct_queue.Queue,) @@ -185,8 +177,9 @@ class UpdateQueueRequest(proto.Message): """ queue = proto.Field(proto.MESSAGE, number=1, message=gct_queue.Queue,) - - 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 DeleteQueueRequest(proto.Message): @@ -199,7 +192,7 @@ class DeleteQueueRequest(proto.Message): ``projects/PROJECT_ID/locations/LOCATION_ID/queues/QUEUE_ID`` """ - name = proto.Field(proto.STRING, number=1) + name = proto.Field(proto.STRING, number=1,) class PurgeQueueRequest(proto.Message): @@ -212,7 +205,7 @@ class PurgeQueueRequest(proto.Message): ``projects/PROJECT_ID/location/LOCATION_ID/queues/QUEUE_ID`` """ - name = proto.Field(proto.STRING, number=1) + name = proto.Field(proto.STRING, number=1,) class PauseQueueRequest(proto.Message): @@ -225,7 +218,7 @@ class PauseQueueRequest(proto.Message): ``projects/PROJECT_ID/location/LOCATION_ID/queues/QUEUE_ID`` """ - name = proto.Field(proto.STRING, number=1) + name = proto.Field(proto.STRING, number=1,) class ResumeQueueRequest(proto.Message): @@ -238,7 +231,7 @@ class ResumeQueueRequest(proto.Message): ``projects/PROJECT_ID/location/LOCATION_ID/queues/QUEUE_ID`` """ - name = proto.Field(proto.STRING, number=1) + name = proto.Field(proto.STRING, number=1,) class ListTasksRequest(proto.Message): @@ -289,13 +282,10 @@ class ListTasksRequest(proto.Message): The page token is valid for only 2 hours. """ - parent = proto.Field(proto.STRING, number=1) - + parent = proto.Field(proto.STRING, number=1,) response_view = proto.Field(proto.ENUM, number=2, enum=gct_task.Task.View,) - - 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 ListTasksResponse(proto.Message): @@ -321,8 +311,7 @@ def raw_page(self): return self tasks = proto.RepeatedField(proto.MESSAGE, number=1, message=gct_task.Task,) - - next_page_token = proto.Field(proto.STRING, number=2) + next_page_token = proto.Field(proto.STRING, number=2,) class GetTaskRequest(proto.Message): @@ -351,8 +340,7 @@ class GetTaskRequest(proto.Message): [Task][google.cloud.tasks.v2.Task] resource. """ - name = proto.Field(proto.STRING, number=1) - + name = proto.Field(proto.STRING, number=1,) response_view = proto.Field(proto.ENUM, number=2, enum=gct_task.Task.View,) @@ -424,10 +412,8 @@ class CreateTaskRequest(proto.Message): [Task][google.cloud.tasks.v2.Task] resource. """ - parent = proto.Field(proto.STRING, number=1) - + parent = proto.Field(proto.STRING, number=1,) task = proto.Field(proto.MESSAGE, number=2, message=gct_task.Task,) - response_view = proto.Field(proto.ENUM, number=3, enum=gct_task.Task.View,) @@ -441,7 +427,7 @@ class DeleteTaskRequest(proto.Message): ``projects/PROJECT_ID/locations/LOCATION_ID/queues/QUEUE_ID/tasks/TASK_ID`` """ - name = proto.Field(proto.STRING, number=1) + name = proto.Field(proto.STRING, number=1,) class RunTaskRequest(proto.Message): @@ -470,8 +456,7 @@ class RunTaskRequest(proto.Message): [Task][google.cloud.tasks.v2.Task] resource. """ - name = proto.Field(proto.STRING, number=1) - + name = proto.Field(proto.STRING, number=1,) response_view = proto.Field(proto.ENUM, number=2, enum=gct_task.Task.View,) diff --git a/google/cloud/tasks_v2/types/queue.py b/google/cloud/tasks_v2/types/queue.py index 32127b78..3df202c9 100644 --- a/google/cloud/tasks_v2/types/queue.py +++ b/google/cloud/tasks_v2/types/queue.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.cloud.tasks_v2.types import target -from google.protobuf import duration_pb2 as duration # type: ignore -from google.protobuf import timestamp_pb2 as timestamp # type: ignore +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore __protobuf__ = proto.module( @@ -152,20 +149,14 @@ class State(proto.Enum): PAUSED = 2 DISABLED = 3 - name = proto.Field(proto.STRING, number=1) - + name = proto.Field(proto.STRING, number=1,) app_engine_routing_override = proto.Field( proto.MESSAGE, number=2, message=target.AppEngineRouting, ) - rate_limits = proto.Field(proto.MESSAGE, number=3, message="RateLimits",) - retry_config = proto.Field(proto.MESSAGE, number=4, message="RetryConfig",) - state = proto.Field(proto.ENUM, number=5, enum=State,) - - purge_time = proto.Field(proto.MESSAGE, number=6, message=timestamp.Timestamp,) - + purge_time = proto.Field(proto.MESSAGE, number=6, message=timestamp_pb2.Timestamp,) stackdriver_logging_config = proto.Field( proto.MESSAGE, number=9, message="StackdriverLoggingConfig", ) @@ -247,11 +238,9 @@ class RateLimits(proto.Message): queue.yaml/xml `__. """ - max_dispatches_per_second = proto.Field(proto.DOUBLE, number=1) - - max_burst_size = proto.Field(proto.INT32, number=2) - - max_concurrent_dispatches = proto.Field(proto.INT32, number=3) + max_dispatches_per_second = proto.Field(proto.DOUBLE, number=1,) + max_burst_size = proto.Field(proto.INT32, number=2,) + max_concurrent_dispatches = proto.Field(proto.INT32, number=3,) class RetryConfig(proto.Message): @@ -362,17 +351,13 @@ class RetryConfig(proto.Message): queue.yaml/xml `__. """ - max_attempts = proto.Field(proto.INT32, number=1) - + max_attempts = proto.Field(proto.INT32, number=1,) max_retry_duration = proto.Field( - proto.MESSAGE, number=2, message=duration.Duration, + proto.MESSAGE, number=2, message=duration_pb2.Duration, ) - - min_backoff = proto.Field(proto.MESSAGE, number=3, message=duration.Duration,) - - max_backoff = proto.Field(proto.MESSAGE, number=4, message=duration.Duration,) - - max_doublings = proto.Field(proto.INT32, number=5) + min_backoff = proto.Field(proto.MESSAGE, number=3, message=duration_pb2.Duration,) + max_backoff = proto.Field(proto.MESSAGE, number=4, message=duration_pb2.Duration,) + max_doublings = proto.Field(proto.INT32, number=5,) class StackdriverLoggingConfig(proto.Message): @@ -388,7 +373,7 @@ class StackdriverLoggingConfig(proto.Message): 0.0 is the default and means that no operations are logged. """ - sampling_ratio = proto.Field(proto.DOUBLE, number=1) + sampling_ratio = proto.Field(proto.DOUBLE, number=1,) __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/tasks_v2/types/target.py b/google/cloud/tasks_v2/types/target.py index 6f61465f..4556cee2 100644 --- a/google/cloud/tasks_v2/types/target.py +++ b/google/cloud/tasks_v2/types/target.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 @@ -156,18 +154,13 @@ class HttpRequest(proto.Message): to validate the token yourself. """ - url = proto.Field(proto.STRING, number=1) - + url = proto.Field(proto.STRING, number=1,) http_method = proto.Field(proto.ENUM, number=2, enum="HttpMethod",) - - headers = proto.MapField(proto.STRING, proto.STRING, number=3) - - body = proto.Field(proto.BYTES, number=4) - + headers = proto.MapField(proto.STRING, proto.STRING, number=3,) + body = proto.Field(proto.BYTES, number=4,) oauth_token = proto.Field( proto.MESSAGE, number=5, oneof="authorization_header", message="OAuthToken", ) - oidc_token = proto.Field( proto.MESSAGE, number=6, oneof="authorization_header", message="OidcToken", ) @@ -325,16 +318,12 @@ class AppEngineHttpRequest(proto.Message): """ http_method = proto.Field(proto.ENUM, number=1, enum="HttpMethod",) - app_engine_routing = proto.Field( proto.MESSAGE, number=2, message="AppEngineRouting", ) - - relative_uri = proto.Field(proto.STRING, number=3) - - headers = proto.MapField(proto.STRING, proto.STRING, number=4) - - body = proto.Field(proto.BYTES, number=5) + relative_uri = proto.Field(proto.STRING, number=3,) + headers = proto.MapField(proto.STRING, proto.STRING, number=4,) + body = proto.Field(proto.BYTES, number=5,) class AppEngineRouting(proto.Message): @@ -440,13 +429,10 @@ class AppEngineRouting(proto.Message): Routed `__. """ - service = proto.Field(proto.STRING, number=1) - - version = proto.Field(proto.STRING, number=2) - - instance = proto.Field(proto.STRING, number=3) - - host = proto.Field(proto.STRING, number=4) + service = proto.Field(proto.STRING, number=1,) + version = proto.Field(proto.STRING, number=2,) + instance = proto.Field(proto.STRING, number=3,) + host = proto.Field(proto.STRING, number=4,) class OAuthToken(proto.Message): @@ -470,9 +456,8 @@ class OAuthToken(proto.Message): will be used. """ - service_account_email = proto.Field(proto.STRING, number=1) - - scope = proto.Field(proto.STRING, number=2) + service_account_email = proto.Field(proto.STRING, number=1,) + scope = proto.Field(proto.STRING, number=2,) class OidcToken(proto.Message): @@ -496,9 +481,8 @@ class OidcToken(proto.Message): target will be used. """ - service_account_email = proto.Field(proto.STRING, number=1) - - audience = proto.Field(proto.STRING, number=2) + service_account_email = proto.Field(proto.STRING, number=1,) + audience = proto.Field(proto.STRING, number=2,) __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/tasks_v2/types/task.py b/google/cloud/tasks_v2/types/task.py index c7e8f903..969cdab8 100644 --- a/google/cloud/tasks_v2/types/task.py +++ b/google/cloud/tasks_v2/types/task.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,14 +13,12 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import proto # type: ignore - from google.cloud.tasks_v2.types import target -from google.protobuf import duration_pb2 as duration # type: ignore -from google.protobuf import timestamp_pb2 as timestamp # type: ignore -from google.rpc import status_pb2 as status # type: ignore +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from google.rpc import status_pb2 # type: ignore __protobuf__ = proto.module( @@ -31,7 +28,6 @@ class Task(proto.Message): r"""A unit of scheduled work. - Attributes: name (str): Optionally caller-specified in @@ -155,39 +151,32 @@ class View(proto.Enum): BASIC = 1 FULL = 2 - name = proto.Field(proto.STRING, number=1) - + name = proto.Field(proto.STRING, number=1,) app_engine_http_request = proto.Field( proto.MESSAGE, number=2, oneof="message_type", message=target.AppEngineHttpRequest, ) - http_request = proto.Field( proto.MESSAGE, number=3, oneof="message_type", message=target.HttpRequest, ) - - schedule_time = proto.Field(proto.MESSAGE, number=4, message=timestamp.Timestamp,) - - create_time = proto.Field(proto.MESSAGE, number=5, message=timestamp.Timestamp,) - - dispatch_deadline = proto.Field(proto.MESSAGE, number=6, message=duration.Duration,) - - dispatch_count = proto.Field(proto.INT32, number=7) - - response_count = proto.Field(proto.INT32, number=8) - + schedule_time = proto.Field( + proto.MESSAGE, number=4, message=timestamp_pb2.Timestamp, + ) + create_time = proto.Field(proto.MESSAGE, number=5, message=timestamp_pb2.Timestamp,) + dispatch_deadline = proto.Field( + proto.MESSAGE, number=6, message=duration_pb2.Duration, + ) + dispatch_count = proto.Field(proto.INT32, number=7,) + response_count = proto.Field(proto.INT32, number=8,) first_attempt = proto.Field(proto.MESSAGE, number=9, message="Attempt",) - last_attempt = proto.Field(proto.MESSAGE, number=10, message="Attempt",) - view = proto.Field(proto.ENUM, number=11, enum=View,) class Attempt(proto.Message): r"""The status of a task attempt. - Attributes: schedule_time (google.protobuf.timestamp_pb2.Timestamp): Output only. The time that this attempt was scheduled. @@ -213,13 +202,16 @@ class Attempt(proto.Message): ``response_status`` field is meaningless. """ - schedule_time = proto.Field(proto.MESSAGE, number=1, message=timestamp.Timestamp,) - - dispatch_time = proto.Field(proto.MESSAGE, number=2, message=timestamp.Timestamp,) - - response_time = proto.Field(proto.MESSAGE, number=3, message=timestamp.Timestamp,) - - response_status = proto.Field(proto.MESSAGE, number=4, message=status.Status,) + schedule_time = proto.Field( + proto.MESSAGE, number=1, message=timestamp_pb2.Timestamp, + ) + dispatch_time = proto.Field( + proto.MESSAGE, number=2, message=timestamp_pb2.Timestamp, + ) + response_time = proto.Field( + proto.MESSAGE, number=3, message=timestamp_pb2.Timestamp, + ) + response_status = proto.Field(proto.MESSAGE, number=4, message=status_pb2.Status,) __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/tasks_v2beta2/__init__.py b/google/cloud/tasks_v2beta2/__init__.py index 9b0b1201..97b2af65 100644 --- a/google/cloud/tasks_v2beta2/__init__.py +++ b/google/cloud/tasks_v2beta2/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -16,6 +15,8 @@ # from .services.cloud_tasks import CloudTasksClient +from .services.cloud_tasks import CloudTasksAsyncClient + from .types.cloudtasks import AcknowledgeTaskRequest from .types.cloudtasks import CancelLeaseRequest from .types.cloudtasks import CreateQueueRequest @@ -43,21 +44,22 @@ from .types.target import AppEngineHttpRequest from .types.target import AppEngineHttpTarget from .types.target import AppEngineRouting -from .types.target import HttpMethod from .types.target import PullMessage from .types.target import PullTarget +from .types.target import HttpMethod from .types.task import AttemptStatus from .types.task import Task from .types.task import TaskStatus - __all__ = ( + "CloudTasksAsyncClient", "AcknowledgeTaskRequest", "AppEngineHttpRequest", "AppEngineHttpTarget", "AppEngineRouting", "AttemptStatus", "CancelLeaseRequest", + "CloudTasksClient", "CreateQueueRequest", "CreateTaskRequest", "DeleteQueueRequest", @@ -85,5 +87,4 @@ "Task", "TaskStatus", "UpdateQueueRequest", - "CloudTasksClient", ) diff --git a/google/cloud/tasks_v2beta2/gapic_metadata.json b/google/cloud/tasks_v2beta2/gapic_metadata.json new file mode 100644 index 00000000..777cbb14 --- /dev/null +++ b/google/cloud/tasks_v2beta2/gapic_metadata.json @@ -0,0 +1,223 @@ + { + "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", + "language": "python", + "libraryPackage": "google.cloud.tasks_v2beta2", + "protoPackage": "google.cloud.tasks.v2beta2", + "schema": "1.0", + "services": { + "CloudTasks": { + "clients": { + "grpc": { + "libraryClient": "CloudTasksClient", + "rpcs": { + "AcknowledgeTask": { + "methods": [ + "acknowledge_task" + ] + }, + "CancelLease": { + "methods": [ + "cancel_lease" + ] + }, + "CreateQueue": { + "methods": [ + "create_queue" + ] + }, + "CreateTask": { + "methods": [ + "create_task" + ] + }, + "DeleteQueue": { + "methods": [ + "delete_queue" + ] + }, + "DeleteTask": { + "methods": [ + "delete_task" + ] + }, + "GetIamPolicy": { + "methods": [ + "get_iam_policy" + ] + }, + "GetQueue": { + "methods": [ + "get_queue" + ] + }, + "GetTask": { + "methods": [ + "get_task" + ] + }, + "LeaseTasks": { + "methods": [ + "lease_tasks" + ] + }, + "ListQueues": { + "methods": [ + "list_queues" + ] + }, + "ListTasks": { + "methods": [ + "list_tasks" + ] + }, + "PauseQueue": { + "methods": [ + "pause_queue" + ] + }, + "PurgeQueue": { + "methods": [ + "purge_queue" + ] + }, + "RenewLease": { + "methods": [ + "renew_lease" + ] + }, + "ResumeQueue": { + "methods": [ + "resume_queue" + ] + }, + "RunTask": { + "methods": [ + "run_task" + ] + }, + "SetIamPolicy": { + "methods": [ + "set_iam_policy" + ] + }, + "TestIamPermissions": { + "methods": [ + "test_iam_permissions" + ] + }, + "UpdateQueue": { + "methods": [ + "update_queue" + ] + } + } + }, + "grpc-async": { + "libraryClient": "CloudTasksAsyncClient", + "rpcs": { + "AcknowledgeTask": { + "methods": [ + "acknowledge_task" + ] + }, + "CancelLease": { + "methods": [ + "cancel_lease" + ] + }, + "CreateQueue": { + "methods": [ + "create_queue" + ] + }, + "CreateTask": { + "methods": [ + "create_task" + ] + }, + "DeleteQueue": { + "methods": [ + "delete_queue" + ] + }, + "DeleteTask": { + "methods": [ + "delete_task" + ] + }, + "GetIamPolicy": { + "methods": [ + "get_iam_policy" + ] + }, + "GetQueue": { + "methods": [ + "get_queue" + ] + }, + "GetTask": { + "methods": [ + "get_task" + ] + }, + "LeaseTasks": { + "methods": [ + "lease_tasks" + ] + }, + "ListQueues": { + "methods": [ + "list_queues" + ] + }, + "ListTasks": { + "methods": [ + "list_tasks" + ] + }, + "PauseQueue": { + "methods": [ + "pause_queue" + ] + }, + "PurgeQueue": { + "methods": [ + "purge_queue" + ] + }, + "RenewLease": { + "methods": [ + "renew_lease" + ] + }, + "ResumeQueue": { + "methods": [ + "resume_queue" + ] + }, + "RunTask": { + "methods": [ + "run_task" + ] + }, + "SetIamPolicy": { + "methods": [ + "set_iam_policy" + ] + }, + "TestIamPermissions": { + "methods": [ + "test_iam_permissions" + ] + }, + "UpdateQueue": { + "methods": [ + "update_queue" + ] + } + } + } + } + } + } +} diff --git a/google/cloud/tasks_v2beta2/services/__init__.py b/google/cloud/tasks_v2beta2/services/__init__.py index 42ffdf2b..4de65971 100644 --- a/google/cloud/tasks_v2beta2/services/__init__.py +++ b/google/cloud/tasks_v2beta2/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/cloud/tasks_v2beta2/services/cloud_tasks/__init__.py b/google/cloud/tasks_v2beta2/services/cloud_tasks/__init__.py index 498f5941..d6abe162 100644 --- a/google/cloud/tasks_v2beta2/services/cloud_tasks/__init__.py +++ b/google/cloud/tasks_v2beta2/services/cloud_tasks/__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 CloudTasksClient from .async_client import CloudTasksAsyncClient diff --git a/google/cloud/tasks_v2beta2/services/cloud_tasks/async_client.py b/google/cloud/tasks_v2beta2/services/cloud_tasks/async_client.py index dfd2f03e..b53ccc34 100644 --- a/google/cloud/tasks_v2beta2/services/cloud_tasks/async_client.py +++ b/google/cloud/tasks_v2beta2/services/cloud_tasks/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,10 +20,10 @@ 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.cloud.tasks_v2beta2.services.cloud_tasks import pagers @@ -35,12 +33,11 @@ from google.cloud.tasks_v2beta2.types import target from google.cloud.tasks_v2beta2.types import task from google.cloud.tasks_v2beta2.types import task as gct_task -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 field_mask_pb2 as field_mask # 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 field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore from .transports.base import CloudTasksTransport, DEFAULT_CLIENT_INFO from .transports.grpc_asyncio import CloudTasksGrpcAsyncIOTransport from .client import CloudTasksClient @@ -60,37 +57,61 @@ class CloudTasksAsyncClient: parse_queue_path = staticmethod(CloudTasksClient.parse_queue_path) task_path = staticmethod(CloudTasksClient.task_path) parse_task_path = staticmethod(CloudTasksClient.parse_task_path) - common_billing_account_path = staticmethod( CloudTasksClient.common_billing_account_path ) parse_common_billing_account_path = staticmethod( CloudTasksClient.parse_common_billing_account_path ) - common_folder_path = staticmethod(CloudTasksClient.common_folder_path) parse_common_folder_path = staticmethod(CloudTasksClient.parse_common_folder_path) - common_organization_path = staticmethod(CloudTasksClient.common_organization_path) parse_common_organization_path = staticmethod( CloudTasksClient.parse_common_organization_path ) - common_project_path = staticmethod(CloudTasksClient.common_project_path) parse_common_project_path = staticmethod(CloudTasksClient.parse_common_project_path) - common_location_path = staticmethod(CloudTasksClient.common_location_path) parse_common_location_path = staticmethod( CloudTasksClient.parse_common_location_path ) - from_service_account_info = CloudTasksClient.from_service_account_info - from_service_account_file = CloudTasksClient.from_service_account_file + @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: + CloudTasksAsyncClient: The constructed client. + """ + return CloudTasksClient.from_service_account_info.__func__(CloudTasksAsyncClient, 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: + CloudTasksAsyncClient: The constructed client. + """ + return CloudTasksClient.from_service_account_file.__func__(CloudTasksAsyncClient, filename, *args, **kwargs) # type: ignore + from_service_account_json = from_service_account_file @property def transport(self) -> CloudTasksTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: CloudTasksTransport: The transport used by the client instance. @@ -104,12 +125,12 @@ def transport(self) -> CloudTasksTransport: def __init__( self, *, - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, transport: Union[str, CloudTasksTransport] = "grpc_asyncio", client_options: ClientOptions = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: - """Instantiate the cloud tasks client. + """Instantiates the cloud tasks client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -141,7 +162,6 @@ def __init__( google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport creation failed for any reason. """ - self._client = CloudTasksClient( credentials=credentials, transport=transport, @@ -172,7 +192,6 @@ async def list_queues( 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. @@ -202,7 +221,6 @@ async def list_queues( # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent @@ -215,8 +233,10 @@ async def list_queues( maximum=10.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), + deadline=20.0, ), default_timeout=20.0, client_info=DEFAULT_CLIENT_INFO, @@ -262,7 +282,6 @@ async def get_queue( 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. @@ -293,7 +312,6 @@ async def get_queue( # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -306,8 +324,10 @@ async def get_queue( maximum=10.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), + deadline=20.0, ), default_timeout=20.0, client_info=DEFAULT_CLIENT_INFO, @@ -372,7 +392,6 @@ async def create_queue( This corresponds to the ``queue`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -403,7 +422,6 @@ async def create_queue( # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent if queue is not None: @@ -434,7 +452,7 @@ async def update_queue( request: cloudtasks.UpdateQueueRequest = None, *, queue: gct_queue.Queue = None, - update_mask: field_mask.FieldMask = None, + update_mask: field_mask_pb2.FieldMask = None, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), @@ -483,7 +501,6 @@ async def update_queue( This corresponds to the ``update_mask`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -514,7 +531,6 @@ async def update_queue( # If we have keyword arguments corresponding to fields on the # request, apply these. - if queue is not None: request.queue = queue if update_mask is not None: @@ -575,7 +591,6 @@ async def delete_queue( 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. @@ -596,7 +611,6 @@ async def delete_queue( # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -609,8 +623,10 @@ async def delete_queue( maximum=10.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), + deadline=20.0, ), default_timeout=20.0, client_info=DEFAULT_CLIENT_INFO, @@ -654,7 +670,6 @@ async def purge_queue( 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. @@ -685,7 +700,6 @@ async def purge_queue( # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -738,7 +752,6 @@ async def pause_queue( 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. @@ -769,7 +782,6 @@ async def pause_queue( # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -829,7 +841,6 @@ async def resume_queue( 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. @@ -860,7 +871,6 @@ async def resume_queue( # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -886,13 +896,13 @@ async def resume_queue( async def get_iam_policy( self, - request: iam_policy.GetIamPolicyRequest = None, + request: iam_policy_pb2.GetIamPolicyRequest = None, *, resource: str = None, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), - ) -> policy.Policy: + ) -> policy_pb2.Policy: r"""Gets the access control policy for a [Queue][google.cloud.tasks.v2beta2.Queue]. Returns an empty policy if the resource exists and does not have a policy set. @@ -916,7 +926,6 @@ async def get_iam_policy( This corresponds to the ``resource`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -995,10 +1004,9 @@ 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) elif not request: - request = iam_policy.GetIamPolicyRequest(resource=resource,) + request = iam_policy_pb2.GetIamPolicyRequest(resource=resource,) # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. @@ -1009,8 +1017,10 @@ async def get_iam_policy( maximum=10.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), + deadline=20.0, ), default_timeout=20.0, client_info=DEFAULT_CLIENT_INFO, @@ -1030,13 +1040,13 @@ async def get_iam_policy( async def set_iam_policy( self, - request: iam_policy.SetIamPolicyRequest = None, + request: iam_policy_pb2.SetIamPolicyRequest = None, *, resource: str = None, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), - ) -> policy.Policy: + ) -> policy_pb2.Policy: r"""Sets the access control policy for a [Queue][google.cloud.tasks.v2beta2.Queue]. Replaces any existing policy. @@ -1064,7 +1074,6 @@ async def set_iam_policy( This corresponds to the ``resource`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -1143,10 +1152,9 @@ 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) elif not request: - request = iam_policy.SetIamPolicyRequest(resource=resource,) + request = iam_policy_pb2.SetIamPolicyRequest(resource=resource,) # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. @@ -1170,14 +1178,14 @@ async def set_iam_policy( async def test_iam_permissions( self, - request: iam_policy.TestIamPermissionsRequest = None, + request: iam_policy_pb2.TestIamPermissionsRequest = None, *, resource: str = None, permissions: Sequence[str] = None, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), - ) -> iam_policy.TestIamPermissionsResponse: + ) -> iam_policy_pb2.TestIamPermissionsResponse: r"""Returns permissions that a caller has on a [Queue][google.cloud.tasks.v2beta2.Queue]. If the resource does not exist, this will return an empty set of permissions, not a @@ -1210,7 +1218,6 @@ async def test_iam_permissions( This corresponds to the ``permissions`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -1234,10 +1241,9 @@ 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) elif not request: - request = iam_policy.TestIamPermissionsRequest( + request = iam_policy_pb2.TestIamPermissionsRequest( resource=resource, permissions=permissions, ) @@ -1250,8 +1256,10 @@ async def test_iam_permissions( maximum=10.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), + deadline=20.0, ), default_timeout=20.0, client_info=DEFAULT_CLIENT_INFO, @@ -1301,7 +1309,6 @@ async def list_tasks( 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. @@ -1331,7 +1338,6 @@ async def list_tasks( # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent @@ -1344,8 +1350,10 @@ async def list_tasks( maximum=10.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), + deadline=20.0, ), default_timeout=20.0, client_info=DEFAULT_CLIENT_INFO, @@ -1392,7 +1400,6 @@ async def get_task( 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. @@ -1417,7 +1424,6 @@ async def get_task( # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -1430,8 +1436,10 @@ async def get_task( maximum=10.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), + deadline=20.0, ), default_timeout=20.0, client_info=DEFAULT_CLIENT_INFO, @@ -1529,7 +1537,6 @@ async def create_task( This corresponds to the ``task`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -1554,7 +1561,6 @@ async def create_task( # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent if task is not None: @@ -1606,7 +1612,6 @@ async def delete_task( 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. @@ -1627,7 +1632,6 @@ async def delete_task( # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -1640,8 +1644,10 @@ async def delete_task( maximum=10.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), + deadline=20.0, ), default_timeout=20.0, client_info=DEFAULT_CLIENT_INFO, @@ -1663,7 +1669,7 @@ async def lease_tasks( request: cloudtasks.LeaseTasksRequest = None, *, parent: str = None, - lease_duration: duration.Duration = None, + lease_duration: duration_pb2.Duration = None, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), @@ -1735,7 +1741,6 @@ async def lease_tasks( This corresponds to the ``lease_duration`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -1762,7 +1767,6 @@ async def lease_tasks( # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent if lease_duration is not None: @@ -1793,7 +1797,7 @@ async def acknowledge_task( request: cloudtasks.AcknowledgeTaskRequest = None, *, name: str = None, - schedule_time: timestamp.Timestamp = None, + schedule_time: timestamp_pb2.Timestamp = None, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), @@ -1840,7 +1844,6 @@ async def acknowledge_task( This corresponds to the ``schedule_time`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -1861,7 +1864,6 @@ async def acknowledge_task( # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name if schedule_time is not None: @@ -1891,8 +1893,8 @@ async def renew_lease( request: cloudtasks.RenewLeaseRequest = None, *, name: str = None, - schedule_time: timestamp.Timestamp = None, - lease_duration: duration.Duration = None, + schedule_time: timestamp_pb2.Timestamp = None, + lease_duration: duration_pb2.Duration = None, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), @@ -1940,7 +1942,6 @@ async def renew_lease( This corresponds to the ``lease_duration`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -1965,7 +1966,6 @@ async def renew_lease( # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name if schedule_time is not None: @@ -1998,7 +1998,7 @@ async def cancel_lease( request: cloudtasks.CancelLeaseRequest = None, *, name: str = None, - schedule_time: timestamp.Timestamp = None, + schedule_time: timestamp_pb2.Timestamp = None, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), @@ -2038,7 +2038,6 @@ async def cancel_lease( This corresponds to the ``schedule_time`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -2063,7 +2062,6 @@ async def cancel_lease( # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name if schedule_time is not None: @@ -2144,7 +2142,6 @@ async def run_task( 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. @@ -2169,7 +2166,6 @@ async def run_task( # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name diff --git a/google/cloud/tasks_v2beta2/services/cloud_tasks/client.py b/google/cloud/tasks_v2beta2/services/cloud_tasks/client.py index 47a1a809..62541341 100644 --- a/google/cloud/tasks_v2beta2/services/cloud_tasks/client.py +++ b/google/cloud/tasks_v2beta2/services/cloud_tasks/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,10 +21,10 @@ 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 @@ -39,12 +37,11 @@ from google.cloud.tasks_v2beta2.types import target from google.cloud.tasks_v2beta2.types import task from google.cloud.tasks_v2beta2.types import task as gct_task -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 field_mask_pb2 as field_mask # 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 field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore from .transports.base import CloudTasksTransport, DEFAULT_CLIENT_INFO from .transports.grpc import CloudTasksGrpcTransport from .transports.grpc_asyncio import CloudTasksGrpcAsyncIOTransport @@ -63,7 +60,7 @@ class CloudTasksClientMeta(type): _transport_registry["grpc_asyncio"] = CloudTasksGrpcAsyncIOTransport def get_transport_class(cls, label: str = None,) -> Type[CloudTasksTransport]: - """Return an appropriate transport class. + """Returns an appropriate transport class. Args: label: The name of the desired transport. If none is @@ -88,7 +85,8 @@ class CloudTasksClient(metaclass=CloudTasksClientMeta): @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: @@ -122,7 +120,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. @@ -139,7 +138,7 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials - file. + file. Args: filename (str): The path to the service account private key json @@ -158,23 +157,24 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> CloudTasksTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: - CloudTasksTransport: The transport used by the client instance. + CloudTasksTransport: The transport used by the client + instance. """ return self._transport @staticmethod def queue_path(project: str, location: str, queue: str,) -> str: - """Return a fully-qualified queue string.""" + """Returns a fully-qualified queue string.""" return "projects/{project}/locations/{location}/queues/{queue}".format( project=project, location=location, queue=queue, ) @staticmethod def parse_queue_path(path: str) -> Dict[str, str]: - """Parse a queue path into its component segments.""" + """Parses a queue path into its component segments.""" m = re.match( r"^projects/(?P.+?)/locations/(?P.+?)/queues/(?P.+?)$", path, @@ -183,14 +183,14 @@ def parse_queue_path(path: str) -> Dict[str, str]: @staticmethod def task_path(project: str, location: str, queue: str, task: str,) -> str: - """Return a fully-qualified task string.""" + """Returns a fully-qualified task string.""" return "projects/{project}/locations/{location}/queues/{queue}/tasks/{task}".format( project=project, location=location, queue=queue, task=task, ) @staticmethod def parse_task_path(path: str) -> Dict[str, str]: - """Parse a task path into its component segments.""" + """Parses a task path into its component segments.""" m = re.match( r"^projects/(?P.+?)/locations/(?P.+?)/queues/(?P.+?)/tasks/(?P.+?)$", path, @@ -199,7 +199,7 @@ def parse_task_path(path: str) -> Dict[str, str]: @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, ) @@ -212,7 +212,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 @@ -223,7 +223,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 @@ -234,7 +234,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 @@ -245,7 +245,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, ) @@ -259,12 +259,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, CloudTasksTransport, None] = None, client_options: Optional[client_options_lib.ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: - """Instantiate the cloud tasks client. + """Instantiates the cloud tasks client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -319,9 +319,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: @@ -333,12 +334,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. @@ -353,8 +356,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: @@ -392,7 +395,6 @@ def list_queues( 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. @@ -424,10 +426,8 @@ def list_queues( # there are no flattened fields. if not isinstance(request, cloudtasks.ListQueuesRequest): request = cloudtasks.ListQueuesRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent @@ -475,7 +475,6 @@ def get_queue( 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. @@ -508,10 +507,8 @@ def get_queue( # there are no flattened fields. if not isinstance(request, cloudtasks.GetQueueRequest): request = cloudtasks.GetQueueRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -578,7 +575,6 @@ def create_queue( This corresponds to the ``queue`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -611,10 +607,8 @@ def create_queue( # there are no flattened fields. if not isinstance(request, cloudtasks.CreateQueueRequest): request = cloudtasks.CreateQueueRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent if queue is not None: @@ -641,7 +635,7 @@ def update_queue( request: cloudtasks.UpdateQueueRequest = None, *, queue: gct_queue.Queue = None, - update_mask: field_mask.FieldMask = None, + update_mask: field_mask_pb2.FieldMask = None, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), @@ -690,7 +684,6 @@ def update_queue( This corresponds to the ``update_mask`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -723,10 +716,8 @@ def update_queue( # there are no flattened fields. if not isinstance(request, cloudtasks.UpdateQueueRequest): request = cloudtasks.UpdateQueueRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if queue is not None: request.queue = queue if update_mask is not None: @@ -783,7 +774,6 @@ def delete_queue( 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. @@ -806,10 +796,8 @@ def delete_queue( # there are no flattened fields. if not isinstance(request, cloudtasks.DeleteQueueRequest): request = cloudtasks.DeleteQueueRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -855,7 +843,6 @@ def purge_queue( 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. @@ -888,10 +875,8 @@ def purge_queue( # there are no flattened fields. if not isinstance(request, cloudtasks.PurgeQueueRequest): request = cloudtasks.PurgeQueueRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -940,7 +925,6 @@ def pause_queue( 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. @@ -973,10 +957,8 @@ def pause_queue( # there are no flattened fields. if not isinstance(request, cloudtasks.PauseQueueRequest): request = cloudtasks.PauseQueueRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -1032,7 +1014,6 @@ def resume_queue( 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. @@ -1065,10 +1046,8 @@ def resume_queue( # there are no flattened fields. if not isinstance(request, cloudtasks.ResumeQueueRequest): request = cloudtasks.ResumeQueueRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -1090,13 +1069,13 @@ def resume_queue( def get_iam_policy( self, - request: iam_policy.GetIamPolicyRequest = None, + request: iam_policy_pb2.GetIamPolicyRequest = None, *, resource: str = None, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), - ) -> policy.Policy: + ) -> policy_pb2.Policy: r"""Gets the access control policy for a [Queue][google.cloud.tasks.v2beta2.Queue]. Returns an empty policy if the resource exists and does not have a policy set. @@ -1120,7 +1099,6 @@ def get_iam_policy( This corresponds to the ``resource`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -1196,14 +1174,13 @@ def get_iam_policy( "the individual field arguments should be set." ) - # 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) - + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + request = iam_policy_pb2.GetIamPolicyRequest(**request) elif not request: - request = iam_policy.GetIamPolicyRequest(resource=resource,) - + # Null request, just make one. + request = iam_policy_pb2.GetIamPolicyRequest() if resource is not None: request.resource = resource @@ -1225,13 +1202,13 @@ def get_iam_policy( def set_iam_policy( self, - request: iam_policy.SetIamPolicyRequest = None, + request: iam_policy_pb2.SetIamPolicyRequest = None, *, resource: str = None, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), - ) -> policy.Policy: + ) -> policy_pb2.Policy: r"""Sets the access control policy for a [Queue][google.cloud.tasks.v2beta2.Queue]. Replaces any existing policy. @@ -1259,7 +1236,6 @@ def set_iam_policy( This corresponds to the ``resource`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -1335,14 +1311,13 @@ def set_iam_policy( "the individual field arguments should be set." ) - # 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) - + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + request = iam_policy_pb2.SetIamPolicyRequest(**request) elif not request: - request = iam_policy.SetIamPolicyRequest(resource=resource,) - + # Null request, just make one. + request = iam_policy_pb2.SetIamPolicyRequest() if resource is not None: request.resource = resource @@ -1364,14 +1339,14 @@ def set_iam_policy( def test_iam_permissions( self, - request: iam_policy.TestIamPermissionsRequest = None, + request: iam_policy_pb2.TestIamPermissionsRequest = None, *, resource: str = None, permissions: Sequence[str] = None, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), - ) -> iam_policy.TestIamPermissionsResponse: + ) -> iam_policy_pb2.TestIamPermissionsResponse: r"""Returns permissions that a caller has on a [Queue][google.cloud.tasks.v2beta2.Queue]. If the resource does not exist, this will return an empty set of permissions, not a @@ -1404,7 +1379,6 @@ def test_iam_permissions( This corresponds to the ``permissions`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -1425,18 +1399,17 @@ def test_iam_permissions( "the individual field arguments should be set." ) - # 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) - + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + request = iam_policy_pb2.TestIamPermissionsRequest(**request) elif not request: - request = iam_policy.TestIamPermissionsRequest( - resource=resource, permissions=permissions, - ) - + # Null request, just make one. + request = iam_policy_pb2.TestIamPermissionsRequest() if resource is not None: request.resource = resource + if permissions: + request.permissions.extend(permissions) # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. @@ -1486,7 +1459,6 @@ def list_tasks( 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. @@ -1518,10 +1490,8 @@ def list_tasks( # there are no flattened fields. if not isinstance(request, cloudtasks.ListTasksRequest): request = cloudtasks.ListTasksRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent @@ -1570,7 +1540,6 @@ def get_task( 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. @@ -1597,10 +1566,8 @@ def get_task( # there are no flattened fields. if not isinstance(request, cloudtasks.GetTaskRequest): request = cloudtasks.GetTaskRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -1700,7 +1667,6 @@ def create_task( This corresponds to the ``task`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -1727,10 +1693,8 @@ def create_task( # there are no flattened fields. if not isinstance(request, cloudtasks.CreateTaskRequest): request = cloudtasks.CreateTaskRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent if task is not None: @@ -1778,7 +1742,6 @@ def delete_task( 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. @@ -1801,10 +1764,8 @@ def delete_task( # there are no flattened fields. if not isinstance(request, cloudtasks.DeleteTaskRequest): request = cloudtasks.DeleteTaskRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -1828,7 +1789,7 @@ def lease_tasks( request: cloudtasks.LeaseTasksRequest = None, *, parent: str = None, - lease_duration: duration.Duration = None, + lease_duration: duration_pb2.Duration = None, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), @@ -1900,7 +1861,6 @@ def lease_tasks( This corresponds to the ``lease_duration`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -1929,10 +1889,8 @@ def lease_tasks( # there are no flattened fields. if not isinstance(request, cloudtasks.LeaseTasksRequest): request = cloudtasks.LeaseTasksRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent if lease_duration is not None: @@ -1959,7 +1917,7 @@ def acknowledge_task( request: cloudtasks.AcknowledgeTaskRequest = None, *, name: str = None, - schedule_time: timestamp.Timestamp = None, + schedule_time: timestamp_pb2.Timestamp = None, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), @@ -2006,7 +1964,6 @@ def acknowledge_task( This corresponds to the ``schedule_time`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -2029,10 +1986,8 @@ def acknowledge_task( # there are no flattened fields. if not isinstance(request, cloudtasks.AcknowledgeTaskRequest): request = cloudtasks.AcknowledgeTaskRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name if schedule_time is not None: @@ -2058,8 +2013,8 @@ def renew_lease( request: cloudtasks.RenewLeaseRequest = None, *, name: str = None, - schedule_time: timestamp.Timestamp = None, - lease_duration: duration.Duration = None, + schedule_time: timestamp_pb2.Timestamp = None, + lease_duration: duration_pb2.Duration = None, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), @@ -2107,7 +2062,6 @@ def renew_lease( This corresponds to the ``lease_duration`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -2134,10 +2088,8 @@ def renew_lease( # there are no flattened fields. if not isinstance(request, cloudtasks.RenewLeaseRequest): request = cloudtasks.RenewLeaseRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name if schedule_time is not None: @@ -2166,7 +2118,7 @@ def cancel_lease( request: cloudtasks.CancelLeaseRequest = None, *, name: str = None, - schedule_time: timestamp.Timestamp = None, + schedule_time: timestamp_pb2.Timestamp = None, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), @@ -2206,7 +2158,6 @@ def cancel_lease( This corresponds to the ``schedule_time`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -2233,10 +2184,8 @@ def cancel_lease( # there are no flattened fields. if not isinstance(request, cloudtasks.CancelLeaseRequest): request = cloudtasks.CancelLeaseRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name if schedule_time is not None: @@ -2313,7 +2262,6 @@ def run_task( 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. @@ -2340,10 +2288,8 @@ def run_task( # there are no flattened fields. if not isinstance(request, cloudtasks.RunTaskRequest): request = cloudtasks.RunTaskRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name diff --git a/google/cloud/tasks_v2beta2/services/cloud_tasks/pagers.py b/google/cloud/tasks_v2beta2/services/cloud_tasks/pagers.py index f7b1a01d..abfb5bd3 100644 --- a/google/cloud/tasks_v2beta2/services/cloud_tasks/pagers.py +++ b/google/cloud/tasks_v2beta2/services/cloud_tasks/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, @@ -119,7 +117,7 @@ def __init__( *, metadata: Sequence[Tuple[str, str]] = () ): - """Instantiate the pager. + """Instantiates the pager. Args: method (Callable): The method that was originally called, and @@ -247,7 +245,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/cloud/tasks_v2beta2/services/cloud_tasks/transports/__init__.py b/google/cloud/tasks_v2beta2/services/cloud_tasks/transports/__init__.py index f386bcfd..9056507e 100644 --- a/google/cloud/tasks_v2beta2/services/cloud_tasks/transports/__init__.py +++ b/google/cloud/tasks_v2beta2/services/cloud_tasks/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/cloud/tasks_v2beta2/services/cloud_tasks/transports/base.py b/google/cloud/tasks_v2beta2/services/cloud_tasks/transports/base.py index eecfe295..3af4ea62 100644 --- a/google/cloud/tasks_v2beta2/services/cloud_tasks/transports/base.py +++ b/google/cloud/tasks_v2beta2/services/cloud_tasks/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,26 +13,26 @@ # 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.cloud.tasks_v2beta2.types import cloudtasks from google.cloud.tasks_v2beta2.types import queue from google.cloud.tasks_v2beta2.types import queue as gct_queue from google.cloud.tasks_v2beta2.types import task from google.cloud.tasks_v2beta2.types import task as gct_task -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 try: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( @@ -42,27 +41,41 @@ except pkg_resources.DistributionNotFound: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() +try: + # google.auth.__version__ was added in 1.26.0 + _GOOGLE_AUTH_VERSION = google.auth.__version__ +except AttributeError: + try: # try pkg_resources if it is available + _GOOGLE_AUTH_VERSION = pkg_resources.get_distribution("google-auth").version + except pkg_resources.DistributionNotFound: # pragma: NO COVER + _GOOGLE_AUTH_VERSION = None + +_API_CORE_VERSION = google.api_core.__version__ + class CloudTasksTransport(abc.ABC): """Abstract transport class for CloudTasks.""" AUTH_SCOPES = ("https://www.googleapis.com/auth/cloud-platform",) + DEFAULT_HOST: str = "cloudtasks.googleapis.com" + def __init__( self, *, - host: str = "cloudtasks.googleapis.com", - credentials: credentials.Credentials = None, - credentials_file: typing.Optional[str] = None, - scopes: typing.Optional[typing.Sequence[str]] = AUTH_SCOPES, - quota_project_id: typing.Optional[str] = None, + host: str = DEFAULT_HOST, + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, **kwargs, ) -> None: """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + host (Optional[str]): + The hostname to connect to. credentials (Optional[google.auth.credentials.Credentials]): The authorization credentials to attach to requests. These credentials identify the application to the service; if none @@ -71,13 +84,13 @@ 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): - 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 + 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. @@ -85,28 +98,75 @@ def __init__( host += ":443" self._host = host + scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) + + # Save the scopes. + self._scopes = scopes or self.AUTH_SCOPES + # If no credentials are provided, then determine the appropriate # defaults. if credentials and credentials_file: - raise exceptions.DuplicateCredentialArgs( + raise core_exceptions.DuplicateCredentialArgs( "'credentials_file' and 'credentials' are mutually exclusive" ) if credentials_file is not None: - credentials, _ = auth.load_credentials_from_file( - credentials_file, scopes=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=scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.default( + **scopes_kwargs, quota_project_id=quota_project_id ) # Save the credentials. self._credentials = credentials - # Lifted into its own function so it can be stubbed out during tests. - self._prep_wrapped_messages(client_info) + # TODO(busunkim): These two class methods are in the base transport + # to avoid duplicating code across the transport classes. These functions + # should be deleted once the minimum required versions of google-api-core + # and google-auth are increased. + + # TODO: Remove this function once google-auth >= 1.25.0 is required + @classmethod + def _get_scopes_kwargs( + cls, host: str, scopes: Optional[Sequence[str]] + ) -> Dict[str, Optional[Sequence[str]]]: + """Returns scopes kwargs to pass to google-auth methods depending on the google-auth version""" + + scopes_kwargs = {} + + if _GOOGLE_AUTH_VERSION and ( + packaging.version.parse(_GOOGLE_AUTH_VERSION) + >= packaging.version.parse("1.25.0") + ): + scopes_kwargs = {"scopes": scopes, "default_scopes": cls.AUTH_SCOPES} + else: + scopes_kwargs = {"scopes": scopes or cls.AUTH_SCOPES} + + return scopes_kwargs + + # TODO: Remove this function once google-api-core >= 1.26.0 is required + @classmethod + def _get_self_signed_jwt_kwargs( + cls, host: str, scopes: Optional[Sequence[str]] + ) -> Dict[str, Union[Optional[Sequence[str]], str]]: + """Returns kwargs to pass to grpc_helpers.create_channel depending on the google-api-core version""" + + self_signed_jwt_kwargs: Dict[str, Union[Optional[Sequence[str]], str]] = {} + + if _API_CORE_VERSION and ( + packaging.version.parse(_API_CORE_VERSION) + >= packaging.version.parse("1.26.0") + ): + self_signed_jwt_kwargs["default_scopes"] = cls.AUTH_SCOPES + self_signed_jwt_kwargs["scopes"] = scopes + self_signed_jwt_kwargs["default_host"] = cls.DEFAULT_HOST + else: + self_signed_jwt_kwargs["scopes"] = scopes or cls.AUTH_SCOPES + + return self_signed_jwt_kwargs def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. @@ -118,8 +178,10 @@ def _prep_wrapped_messages(self, client_info): maximum=10.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), + deadline=20.0, ), default_timeout=20.0, client_info=client_info, @@ -131,8 +193,10 @@ def _prep_wrapped_messages(self, client_info): maximum=10.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), + deadline=20.0, ), default_timeout=20.0, client_info=client_info, @@ -150,8 +214,10 @@ def _prep_wrapped_messages(self, client_info): maximum=10.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), + deadline=20.0, ), default_timeout=20.0, client_info=client_info, @@ -172,8 +238,10 @@ def _prep_wrapped_messages(self, client_info): maximum=10.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), + deadline=20.0, ), default_timeout=20.0, client_info=client_info, @@ -188,8 +256,10 @@ def _prep_wrapped_messages(self, client_info): maximum=10.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), + deadline=20.0, ), default_timeout=20.0, client_info=client_info, @@ -201,8 +271,10 @@ def _prep_wrapped_messages(self, client_info): maximum=10.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), + deadline=20.0, ), default_timeout=20.0, client_info=client_info, @@ -214,8 +286,10 @@ def _prep_wrapped_messages(self, client_info): maximum=10.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), + deadline=20.0, ), default_timeout=20.0, client_info=client_info, @@ -230,8 +304,10 @@ def _prep_wrapped_messages(self, client_info): maximum=10.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), + deadline=20.0, ), default_timeout=20.0, client_info=client_info, @@ -256,104 +332,97 @@ def _prep_wrapped_messages(self, client_info): @property def list_queues( self, - ) -> typing.Callable[ + ) -> Callable[ [cloudtasks.ListQueuesRequest], - typing.Union[ - cloudtasks.ListQueuesResponse, - typing.Awaitable[cloudtasks.ListQueuesResponse], - ], + Union[cloudtasks.ListQueuesResponse, Awaitable[cloudtasks.ListQueuesResponse]], ]: raise NotImplementedError() @property def get_queue( self, - ) -> typing.Callable[ - [cloudtasks.GetQueueRequest], - typing.Union[queue.Queue, typing.Awaitable[queue.Queue]], + ) -> Callable[ + [cloudtasks.GetQueueRequest], Union[queue.Queue, Awaitable[queue.Queue]] ]: raise NotImplementedError() @property def create_queue( self, - ) -> typing.Callable[ + ) -> Callable[ [cloudtasks.CreateQueueRequest], - typing.Union[gct_queue.Queue, typing.Awaitable[gct_queue.Queue]], + Union[gct_queue.Queue, Awaitable[gct_queue.Queue]], ]: raise NotImplementedError() @property def update_queue( self, - ) -> typing.Callable[ + ) -> Callable[ [cloudtasks.UpdateQueueRequest], - typing.Union[gct_queue.Queue, typing.Awaitable[gct_queue.Queue]], + Union[gct_queue.Queue, Awaitable[gct_queue.Queue]], ]: raise NotImplementedError() @property def delete_queue( self, - ) -> typing.Callable[ + ) -> Callable[ [cloudtasks.DeleteQueueRequest], - typing.Union[empty.Empty, typing.Awaitable[empty.Empty]], + Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]], ]: raise NotImplementedError() @property def purge_queue( self, - ) -> typing.Callable[ - [cloudtasks.PurgeQueueRequest], - typing.Union[queue.Queue, typing.Awaitable[queue.Queue]], + ) -> Callable[ + [cloudtasks.PurgeQueueRequest], Union[queue.Queue, Awaitable[queue.Queue]] ]: raise NotImplementedError() @property def pause_queue( self, - ) -> typing.Callable[ - [cloudtasks.PauseQueueRequest], - typing.Union[queue.Queue, typing.Awaitable[queue.Queue]], + ) -> Callable[ + [cloudtasks.PauseQueueRequest], Union[queue.Queue, Awaitable[queue.Queue]] ]: raise NotImplementedError() @property def resume_queue( self, - ) -> typing.Callable[ - [cloudtasks.ResumeQueueRequest], - typing.Union[queue.Queue, typing.Awaitable[queue.Queue]], + ) -> Callable[ + [cloudtasks.ResumeQueueRequest], Union[queue.Queue, Awaitable[queue.Queue]] ]: 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 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 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() @@ -361,87 +430,73 @@ def test_iam_permissions( @property def list_tasks( self, - ) -> typing.Callable[ + ) -> Callable[ [cloudtasks.ListTasksRequest], - typing.Union[ - cloudtasks.ListTasksResponse, typing.Awaitable[cloudtasks.ListTasksResponse] - ], + Union[cloudtasks.ListTasksResponse, Awaitable[cloudtasks.ListTasksResponse]], ]: raise NotImplementedError() @property def get_task( self, - ) -> typing.Callable[ - [cloudtasks.GetTaskRequest], - typing.Union[task.Task, typing.Awaitable[task.Task]], - ]: + ) -> Callable[[cloudtasks.GetTaskRequest], Union[task.Task, Awaitable[task.Task]]]: raise NotImplementedError() @property def create_task( self, - ) -> typing.Callable[ - [cloudtasks.CreateTaskRequest], - typing.Union[gct_task.Task, typing.Awaitable[gct_task.Task]], + ) -> Callable[ + [cloudtasks.CreateTaskRequest], Union[gct_task.Task, Awaitable[gct_task.Task]] ]: raise NotImplementedError() @property def delete_task( self, - ) -> typing.Callable[ + ) -> Callable[ [cloudtasks.DeleteTaskRequest], - typing.Union[empty.Empty, typing.Awaitable[empty.Empty]], + Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]], ]: raise NotImplementedError() @property def lease_tasks( self, - ) -> typing.Callable[ + ) -> Callable[ [cloudtasks.LeaseTasksRequest], - typing.Union[ - cloudtasks.LeaseTasksResponse, - typing.Awaitable[cloudtasks.LeaseTasksResponse], - ], + Union[cloudtasks.LeaseTasksResponse, Awaitable[cloudtasks.LeaseTasksResponse]], ]: raise NotImplementedError() @property def acknowledge_task( self, - ) -> typing.Callable[ + ) -> Callable[ [cloudtasks.AcknowledgeTaskRequest], - typing.Union[empty.Empty, typing.Awaitable[empty.Empty]], + Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]], ]: raise NotImplementedError() @property def renew_lease( self, - ) -> typing.Callable[ - [cloudtasks.RenewLeaseRequest], - typing.Union[task.Task, typing.Awaitable[task.Task]], + ) -> Callable[ + [cloudtasks.RenewLeaseRequest], Union[task.Task, Awaitable[task.Task]] ]: raise NotImplementedError() @property def cancel_lease( self, - ) -> typing.Callable[ - [cloudtasks.CancelLeaseRequest], - typing.Union[task.Task, typing.Awaitable[task.Task]], + ) -> Callable[ + [cloudtasks.CancelLeaseRequest], Union[task.Task, Awaitable[task.Task]] ]: raise NotImplementedError() @property def run_task( self, - ) -> typing.Callable[ - [cloudtasks.RunTaskRequest], - typing.Union[task.Task, typing.Awaitable[task.Task]], - ]: + ) -> Callable[[cloudtasks.RunTaskRequest], Union[task.Task, Awaitable[task.Task]]]: raise NotImplementedError() diff --git a/google/cloud/tasks_v2beta2/services/cloud_tasks/transports/grpc.py b/google/cloud/tasks_v2beta2/services/cloud_tasks/transports/grpc.py index 5534bead..72838fc7 100644 --- a/google/cloud/tasks_v2beta2/services/cloud_tasks/transports/grpc.py +++ b/google/cloud/tasks_v2beta2/services/cloud_tasks/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,14 +13,13 @@ # 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 @@ -31,10 +29,9 @@ from google.cloud.tasks_v2beta2.types import queue as gct_queue from google.cloud.tasks_v2beta2.types import task from google.cloud.tasks_v2beta2.types import task as gct_task -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 .base import CloudTasksTransport, DEFAULT_CLIENT_INFO @@ -58,7 +55,7 @@ def __init__( self, *, host: str = "cloudtasks.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Sequence[str] = None, channel: grpc.Channel = None, @@ -72,7 +69,8 @@ def __init__( """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + host (Optional[str]): + The hostname to connect to. credentials (Optional[google.auth.credentials.Credentials]): The authorization credentials to attach to requests. These credentials identify the application to the service; if none @@ -114,7 +112,9 @@ def __init__( 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) @@ -122,70 +122,50 @@ def __init__( warnings.warn("client_cert_source is deprecated", DeprecationWarning) if channel: - # Sanity check: Ensure that channel and credentials are not both - # provided. + # 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 - elif api_mtls_endpoint: - host = ( - api_mtls_endpoint - if ":" in api_mtls_endpoint - else api_mtls_endpoint + ":443" - ) - if credentials is None: - credentials, _ = auth.default( - scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id - ) - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - ssl_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - ssl_credentials = SslCredentials().ssl_credentials - - # create a new channel. The provided one is ignored. - self._grpc_channel = type(self).create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - ssl_credentials=ssl_credentials, - scopes=scopes or self.AUTH_SCOPES, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - self._ssl_channel_credentials = ssl_credentials else: - host = host if ":" in host else host + ":443" + 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 - if credentials is None: - credentials, _ = auth.default( - scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id - ) + 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 + ) - 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, + ) - # create a new channel. The provided one is ignored. + if not self._grpc_channel: self._grpc_channel = type(self).create_channel( - host, - credentials=credentials, + self._host, + credentials=self._credentials, credentials_file=credentials_file, + scopes=self._scopes, ssl_credentials=self._ssl_channel_credentials, - scopes=scopes or self.AUTH_SCOPES, quota_project_id=quota_project_id, options=[ ("grpc.max_send_message_length", -1), @@ -193,23 +173,14 @@ def __init__( ], ) - self._stubs = {} # type: Dict[str, Callable] - - # Run the base constructor. - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes or self.AUTH_SCOPES, - quota_project_id=quota_project_id, - client_info=client_info, - ) + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) @classmethod def create_channel( cls, host: str = "cloudtasks.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, @@ -217,7 +188,7 @@ def create_channel( ) -> grpc.Channel: """Create and return a gRPC channel object. Args: - address (Optional[str]): The host for the channel to use. + 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 @@ -240,13 +211,15 @@ def create_channel( google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` and ``credentials_file`` are passed. """ - scopes = scopes or cls.AUTH_SCOPES + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + return grpc_helpers.create_channel( host, credentials=credentials, credentials_file=credentials_file, - scopes=scopes, quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, **kwargs, ) @@ -383,7 +356,9 @@ def update_queue( return self._stubs["update_queue"] @property - def delete_queue(self) -> Callable[[cloudtasks.DeleteQueueRequest], empty.Empty]: + def delete_queue( + self, + ) -> Callable[[cloudtasks.DeleteQueueRequest], empty_pb2.Empty]: r"""Return a callable for the delete queue method over gRPC. Deletes a queue. @@ -413,7 +388,7 @@ def delete_queue(self) -> Callable[[cloudtasks.DeleteQueueRequest], empty.Empty] self._stubs["delete_queue"] = self.grpc_channel.unary_unary( "/google.cloud.tasks.v2beta2.CloudTasks/DeleteQueue", request_serializer=cloudtasks.DeleteQueueRequest.serialize, - response_deserializer=empty.Empty.FromString, + response_deserializer=empty_pb2.Empty.FromString, ) return self._stubs["delete_queue"] @@ -518,7 +493,7 @@ def resume_queue(self) -> Callable[[cloudtasks.ResumeQueueRequest], queue.Queue] @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 access control policy for a @@ -544,15 +519,15 @@ def get_iam_policy( if "get_iam_policy" not in self._stubs: self._stubs["get_iam_policy"] = self.grpc_channel.unary_unary( "/google.cloud.tasks.v2beta2.CloudTasks/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"] @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 access control policy for a @@ -582,8 +557,8 @@ def set_iam_policy( if "set_iam_policy" not in self._stubs: self._stubs["set_iam_policy"] = self.grpc_channel.unary_unary( "/google.cloud.tasks.v2beta2.CloudTasks/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"] @@ -591,7 +566,8 @@ def set_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. @@ -618,8 +594,8 @@ def test_iam_permissions( if "test_iam_permissions" not in self._stubs: self._stubs["test_iam_permissions"] = self.grpc_channel.unary_unary( "/google.cloud.tasks.v2beta2.CloudTasks/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"] @@ -716,7 +692,7 @@ def create_task(self) -> Callable[[cloudtasks.CreateTaskRequest], gct_task.Task] return self._stubs["create_task"] @property - def delete_task(self) -> Callable[[cloudtasks.DeleteTaskRequest], empty.Empty]: + def delete_task(self) -> Callable[[cloudtasks.DeleteTaskRequest], empty_pb2.Empty]: r"""Return a callable for the delete task method over gRPC. Deletes a task. @@ -738,7 +714,7 @@ def delete_task(self) -> Callable[[cloudtasks.DeleteTaskRequest], empty.Empty]: self._stubs["delete_task"] = self.grpc_channel.unary_unary( "/google.cloud.tasks.v2beta2.CloudTasks/DeleteTask", request_serializer=cloudtasks.DeleteTaskRequest.serialize, - response_deserializer=empty.Empty.FromString, + response_deserializer=empty_pb2.Empty.FromString, ) return self._stubs["delete_task"] @@ -794,7 +770,7 @@ def lease_tasks( @property def acknowledge_task( self, - ) -> Callable[[cloudtasks.AcknowledgeTaskRequest], empty.Empty]: + ) -> Callable[[cloudtasks.AcknowledgeTaskRequest], empty_pb2.Empty]: r"""Return a callable for the acknowledge task method over gRPC. Acknowledges a pull task. @@ -827,7 +803,7 @@ def acknowledge_task( self._stubs["acknowledge_task"] = self.grpc_channel.unary_unary( "/google.cloud.tasks.v2beta2.CloudTasks/AcknowledgeTask", request_serializer=cloudtasks.AcknowledgeTaskRequest.serialize, - response_deserializer=empty.Empty.FromString, + response_deserializer=empty_pb2.Empty.FromString, ) return self._stubs["acknowledge_task"] diff --git a/google/cloud/tasks_v2beta2/services/cloud_tasks/transports/grpc_asyncio.py b/google/cloud/tasks_v2beta2/services/cloud_tasks/transports/grpc_asyncio.py index 3fe7a075..a5c5bea9 100644 --- a/google/cloud/tasks_v2beta2/services/cloud_tasks/transports/grpc_asyncio.py +++ b/google/cloud/tasks_v2beta2/services/cloud_tasks/transports/grpc_asyncio.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,15 +13,14 @@ # 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 @@ -32,10 +30,9 @@ from google.cloud.tasks_v2beta2.types import queue as gct_queue from google.cloud.tasks_v2beta2.types import task from google.cloud.tasks_v2beta2.types import task as gct_task -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 .base import CloudTasksTransport, DEFAULT_CLIENT_INFO from .grpc import CloudTasksGrpcTransport @@ -61,7 +58,7 @@ class CloudTasksGrpcAsyncIOTransport(CloudTasksTransport): def create_channel( cls, host: str = "cloudtasks.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, @@ -69,7 +66,7 @@ def create_channel( ) -> aio.Channel: """Create and return a gRPC AsyncIO channel object. Args: - address (Optional[str]): The host for the channel to use. + 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 @@ -88,13 +85,15 @@ def create_channel( Returns: aio.Channel: A gRPC AsyncIO channel object. """ - scopes = scopes or cls.AUTH_SCOPES + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + return grpc_helpers_async.create_channel( host, credentials=credentials, credentials_file=credentials_file, - scopes=scopes, quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, **kwargs, ) @@ -102,7 +101,7 @@ def __init__( self, *, host: str = "cloudtasks.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, @@ -116,7 +115,8 @@ def __init__( """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + host (Optional[str]): + The hostname to connect to. credentials (Optional[google.auth.credentials.Credentials]): The authorization credentials to attach to requests. These credentials identify the application to the service; if none @@ -147,10 +147,10 @@ def __init__( 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 + 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: @@ -159,7 +159,9 @@ def __init__( 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) @@ -167,70 +169,49 @@ def __init__( warnings.warn("client_cert_source is deprecated", DeprecationWarning) if channel: - # Sanity check: Ensure that channel and credentials are not both - # provided. + # 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 - elif api_mtls_endpoint: - host = ( - api_mtls_endpoint - if ":" in api_mtls_endpoint - else api_mtls_endpoint + ":443" - ) - - if credentials is None: - credentials, _ = auth.default( - scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id - ) - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - ssl_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - ssl_credentials = SslCredentials().ssl_credentials - - # create a new channel. The provided one is ignored. - self._grpc_channel = type(self).create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - ssl_credentials=ssl_credentials, - scopes=scopes or self.AUTH_SCOPES, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - self._ssl_channel_credentials = ssl_credentials else: - host = host if ":" in host else host + ":443" + 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 - if credentials is None: - credentials, _ = auth.default( - scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id - ) + 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 + ) - 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, + ) - # create a new channel. The provided one is ignored. + if not self._grpc_channel: self._grpc_channel = type(self).create_channel( - host, - credentials=credentials, + self._host, + credentials=self._credentials, credentials_file=credentials_file, + scopes=self._scopes, ssl_credentials=self._ssl_channel_credentials, - scopes=scopes or self.AUTH_SCOPES, quota_project_id=quota_project_id, options=[ ("grpc.max_send_message_length", -1), @@ -238,17 +219,8 @@ def __init__( ], ) - # Run the base constructor. - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes or self.AUTH_SCOPES, - quota_project_id=quota_project_id, - client_info=client_info, - ) - - self._stubs = {} + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) @property def grpc_channel(self) -> aio.Channel: @@ -393,7 +365,7 @@ def update_queue( @property def delete_queue( self, - ) -> Callable[[cloudtasks.DeleteQueueRequest], Awaitable[empty.Empty]]: + ) -> Callable[[cloudtasks.DeleteQueueRequest], Awaitable[empty_pb2.Empty]]: r"""Return a callable for the delete queue method over gRPC. Deletes a queue. @@ -423,7 +395,7 @@ def delete_queue( self._stubs["delete_queue"] = self.grpc_channel.unary_unary( "/google.cloud.tasks.v2beta2.CloudTasks/DeleteQueue", request_serializer=cloudtasks.DeleteQueueRequest.serialize, - response_deserializer=empty.Empty.FromString, + response_deserializer=empty_pb2.Empty.FromString, ) return self._stubs["delete_queue"] @@ -534,7 +506,7 @@ def resume_queue( @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 access control policy for a @@ -560,15 +532,15 @@ def get_iam_policy( if "get_iam_policy" not in self._stubs: self._stubs["get_iam_policy"] = self.grpc_channel.unary_unary( "/google.cloud.tasks.v2beta2.CloudTasks/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"] @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 access control policy for a @@ -598,8 +570,8 @@ def set_iam_policy( if "set_iam_policy" not in self._stubs: self._stubs["set_iam_policy"] = self.grpc_channel.unary_unary( "/google.cloud.tasks.v2beta2.CloudTasks/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"] @@ -607,8 +579,8 @@ def set_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. @@ -635,8 +607,8 @@ def test_iam_permissions( if "test_iam_permissions" not in self._stubs: self._stubs["test_iam_permissions"] = self.grpc_channel.unary_unary( "/google.cloud.tasks.v2beta2.CloudTasks/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"] @@ -739,7 +711,7 @@ def create_task( @property def delete_task( self, - ) -> Callable[[cloudtasks.DeleteTaskRequest], Awaitable[empty.Empty]]: + ) -> Callable[[cloudtasks.DeleteTaskRequest], Awaitable[empty_pb2.Empty]]: r"""Return a callable for the delete task method over gRPC. Deletes a task. @@ -761,7 +733,7 @@ def delete_task( self._stubs["delete_task"] = self.grpc_channel.unary_unary( "/google.cloud.tasks.v2beta2.CloudTasks/DeleteTask", request_serializer=cloudtasks.DeleteTaskRequest.serialize, - response_deserializer=empty.Empty.FromString, + response_deserializer=empty_pb2.Empty.FromString, ) return self._stubs["delete_task"] @@ -819,7 +791,7 @@ def lease_tasks( @property def acknowledge_task( self, - ) -> Callable[[cloudtasks.AcknowledgeTaskRequest], Awaitable[empty.Empty]]: + ) -> Callable[[cloudtasks.AcknowledgeTaskRequest], Awaitable[empty_pb2.Empty]]: r"""Return a callable for the acknowledge task method over gRPC. Acknowledges a pull task. @@ -852,7 +824,7 @@ def acknowledge_task( self._stubs["acknowledge_task"] = self.grpc_channel.unary_unary( "/google.cloud.tasks.v2beta2.CloudTasks/AcknowledgeTask", request_serializer=cloudtasks.AcknowledgeTaskRequest.serialize, - response_deserializer=empty.Empty.FromString, + response_deserializer=empty_pb2.Empty.FromString, ) return self._stubs["acknowledge_task"] diff --git a/google/cloud/tasks_v2beta2/types/__init__.py b/google/cloud/tasks_v2beta2/types/__init__.py index 7407d142..062a010e 100644 --- a/google/cloud/tasks_v2beta2/types/__init__.py +++ b/google/cloud/tasks_v2beta2/types/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,81 +13,80 @@ # See the License for the specific language governing permissions and # limitations under the License. # - -from .target import ( - PullTarget, - PullMessage, - AppEngineHttpTarget, - AppEngineHttpRequest, - AppEngineRouting, - HttpMethod, +from .cloudtasks import ( + AcknowledgeTaskRequest, + CancelLeaseRequest, + CreateQueueRequest, + CreateTaskRequest, + DeleteQueueRequest, + DeleteTaskRequest, + GetQueueRequest, + GetTaskRequest, + LeaseTasksRequest, + LeaseTasksResponse, + ListQueuesRequest, + ListQueuesResponse, + ListTasksRequest, + ListTasksResponse, + PauseQueueRequest, + PurgeQueueRequest, + RenewLeaseRequest, + ResumeQueueRequest, + RunTaskRequest, + UpdateQueueRequest, ) from .queue import ( Queue, + QueueStats, RateLimits, RetryConfig, - QueueStats, +) +from .target import ( + AppEngineHttpRequest, + AppEngineHttpTarget, + AppEngineRouting, + PullMessage, + PullTarget, + HttpMethod, ) from .task import ( + AttemptStatus, Task, TaskStatus, - AttemptStatus, -) -from .cloudtasks import ( - ListQueuesRequest, - ListQueuesResponse, - GetQueueRequest, - CreateQueueRequest, - UpdateQueueRequest, - DeleteQueueRequest, - PurgeQueueRequest, - PauseQueueRequest, - ResumeQueueRequest, - ListTasksRequest, - ListTasksResponse, - GetTaskRequest, - CreateTaskRequest, - DeleteTaskRequest, - LeaseTasksRequest, - LeaseTasksResponse, - AcknowledgeTaskRequest, - RenewLeaseRequest, - CancelLeaseRequest, - RunTaskRequest, ) __all__ = ( - "PullTarget", - "PullMessage", - "AppEngineHttpTarget", - "AppEngineHttpRequest", - "AppEngineRouting", - "HttpMethod", - "Queue", - "RateLimits", - "RetryConfig", - "QueueStats", - "Task", - "TaskStatus", - "AttemptStatus", - "ListQueuesRequest", - "ListQueuesResponse", - "GetQueueRequest", + "AcknowledgeTaskRequest", + "CancelLeaseRequest", "CreateQueueRequest", - "UpdateQueueRequest", - "DeleteQueueRequest", - "PurgeQueueRequest", - "PauseQueueRequest", - "ResumeQueueRequest", - "ListTasksRequest", - "ListTasksResponse", - "GetTaskRequest", "CreateTaskRequest", + "DeleteQueueRequest", "DeleteTaskRequest", + "GetQueueRequest", + "GetTaskRequest", "LeaseTasksRequest", "LeaseTasksResponse", - "AcknowledgeTaskRequest", + "ListQueuesRequest", + "ListQueuesResponse", + "ListTasksRequest", + "ListTasksResponse", + "PauseQueueRequest", + "PurgeQueueRequest", "RenewLeaseRequest", - "CancelLeaseRequest", + "ResumeQueueRequest", "RunTaskRequest", + "UpdateQueueRequest", + "Queue", + "QueueStats", + "RateLimits", + "RetryConfig", + "AppEngineHttpRequest", + "AppEngineHttpTarget", + "AppEngineRouting", + "PullMessage", + "PullTarget", + "HttpMethod", + "AttemptStatus", + "Task", + "TaskStatus", ) diff --git a/google/cloud/tasks_v2beta2/types/cloudtasks.py b/google/cloud/tasks_v2beta2/types/cloudtasks.py index e216e819..20849ca3 100644 --- a/google/cloud/tasks_v2beta2/types/cloudtasks.py +++ b/google/cloud/tasks_v2beta2/types/cloudtasks.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,15 +13,13 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import proto # type: ignore - from google.cloud.tasks_v2beta2.types import queue as gct_queue from google.cloud.tasks_v2beta2.types import task as gct_task -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 __protobuf__ = proto.module( @@ -99,15 +96,11 @@ class ListQueuesRequest(proto.Message): returned only if it was explicitly specified in the mask. """ - parent = proto.Field(proto.STRING, number=1) - - filter = proto.Field(proto.STRING, number=2) - - page_size = proto.Field(proto.INT32, number=3) - - page_token = proto.Field(proto.STRING, number=4) - - read_mask = proto.Field(proto.MESSAGE, number=5, message=field_mask.FieldMask,) + parent = proto.Field(proto.STRING, number=1,) + filter = proto.Field(proto.STRING, number=2,) + page_size = proto.Field(proto.INT32, number=3,) + page_token = proto.Field(proto.STRING, number=4,) + read_mask = proto.Field(proto.MESSAGE, number=5, message=field_mask_pb2.FieldMask,) class ListQueuesResponse(proto.Message): @@ -135,8 +128,7 @@ def raw_page(self): return self queues = proto.RepeatedField(proto.MESSAGE, number=1, message=gct_queue.Queue,) - - next_page_token = proto.Field(proto.STRING, number=2) + next_page_token = proto.Field(proto.STRING, number=2,) class GetQueueRequest(proto.Message): @@ -154,9 +146,8 @@ class GetQueueRequest(proto.Message): returned only if it was explicitly specified in the mask. """ - name = proto.Field(proto.STRING, number=1) - - read_mask = proto.Field(proto.MESSAGE, number=2, message=field_mask.FieldMask,) + name = proto.Field(proto.STRING, number=1,) + read_mask = proto.Field(proto.MESSAGE, number=2, message=field_mask_pb2.FieldMask,) class CreateQueueRequest(proto.Message): @@ -179,8 +170,7 @@ class CreateQueueRequest(proto.Message): be the same as an existing queue. """ - parent = proto.Field(proto.STRING, number=1) - + parent = proto.Field(proto.STRING, number=1,) queue = proto.Field(proto.MESSAGE, number=2, message=gct_queue.Queue,) @@ -206,8 +196,9 @@ class UpdateQueueRequest(proto.Message): """ queue = proto.Field(proto.MESSAGE, number=1, message=gct_queue.Queue,) - - 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 DeleteQueueRequest(proto.Message): @@ -220,7 +211,7 @@ class DeleteQueueRequest(proto.Message): ``projects/PROJECT_ID/locations/LOCATION_ID/queues/QUEUE_ID`` """ - name = proto.Field(proto.STRING, number=1) + name = proto.Field(proto.STRING, number=1,) class PurgeQueueRequest(proto.Message): @@ -233,7 +224,7 @@ class PurgeQueueRequest(proto.Message): ``projects/PROJECT_ID/location/LOCATION_ID/queues/QUEUE_ID`` """ - name = proto.Field(proto.STRING, number=1) + name = proto.Field(proto.STRING, number=1,) class PauseQueueRequest(proto.Message): @@ -246,7 +237,7 @@ class PauseQueueRequest(proto.Message): ``projects/PROJECT_ID/location/LOCATION_ID/queues/QUEUE_ID`` """ - name = proto.Field(proto.STRING, number=1) + name = proto.Field(proto.STRING, number=1,) class ResumeQueueRequest(proto.Message): @@ -259,7 +250,7 @@ class ResumeQueueRequest(proto.Message): ``projects/PROJECT_ID/location/LOCATION_ID/queues/QUEUE_ID`` """ - name = proto.Field(proto.STRING, number=1) + name = proto.Field(proto.STRING, number=1,) class ListTasksRequest(proto.Message): @@ -310,13 +301,10 @@ class ListTasksRequest(proto.Message): The page token is valid for only 2 hours. """ - parent = proto.Field(proto.STRING, number=1) - + parent = proto.Field(proto.STRING, number=1,) response_view = proto.Field(proto.ENUM, number=2, enum=gct_task.Task.View,) - - page_size = proto.Field(proto.INT32, number=4) - - page_token = proto.Field(proto.STRING, number=5) + page_size = proto.Field(proto.INT32, number=4,) + page_token = proto.Field(proto.STRING, number=5,) class ListTasksResponse(proto.Message): @@ -342,8 +330,7 @@ def raw_page(self): return self tasks = proto.RepeatedField(proto.MESSAGE, number=1, message=gct_task.Task,) - - next_page_token = proto.Field(proto.STRING, number=2) + next_page_token = proto.Field(proto.STRING, number=2,) class GetTaskRequest(proto.Message): @@ -372,8 +359,7 @@ class GetTaskRequest(proto.Message): [Task][google.cloud.tasks.v2beta2.Task] resource. """ - name = proto.Field(proto.STRING, number=1) - + name = proto.Field(proto.STRING, number=1,) response_view = proto.Field(proto.ENUM, number=2, enum=gct_task.Task.View,) @@ -446,10 +432,8 @@ class CreateTaskRequest(proto.Message): [Task][google.cloud.tasks.v2beta2.Task] resource. """ - parent = proto.Field(proto.STRING, number=1) - + parent = proto.Field(proto.STRING, number=1,) task = proto.Field(proto.MESSAGE, number=2, message=gct_task.Task,) - response_view = proto.Field(proto.ENUM, number=3, enum=gct_task.Task.View,) @@ -463,7 +447,7 @@ class DeleteTaskRequest(proto.Message): ``projects/PROJECT_ID/locations/LOCATION_ID/queues/QUEUE_ID/tasks/TASK_ID`` """ - name = proto.Field(proto.STRING, number=1) + name = proto.Field(proto.STRING, number=1,) class LeaseTasksRequest(proto.Message): @@ -567,15 +551,13 @@ class LeaseTasksRequest(proto.Message): displayed as empty in Cloud Tasks. """ - parent = proto.Field(proto.STRING, number=1) - - max_tasks = proto.Field(proto.INT32, number=2) - - lease_duration = proto.Field(proto.MESSAGE, number=3, message=duration.Duration,) - + parent = proto.Field(proto.STRING, number=1,) + max_tasks = proto.Field(proto.INT32, number=2,) + lease_duration = proto.Field( + proto.MESSAGE, number=3, message=duration_pb2.Duration, + ) response_view = proto.Field(proto.ENUM, number=4, enum=gct_task.Task.View,) - - filter = proto.Field(proto.STRING, number=5) + filter = proto.Field(proto.STRING, number=5,) class LeaseTasksResponse(proto.Message): @@ -609,9 +591,10 @@ class AcknowledgeTaskRequest(proto.Message): currently holds the lease. """ - name = proto.Field(proto.STRING, number=1) - - schedule_time = proto.Field(proto.MESSAGE, number=2, message=timestamp.Timestamp,) + name = proto.Field(proto.STRING, number=1,) + schedule_time = proto.Field( + proto.MESSAGE, number=2, message=timestamp_pb2.Timestamp, + ) class RenewLeaseRequest(proto.Message): @@ -654,12 +637,13 @@ class RenewLeaseRequest(proto.Message): [Task][google.cloud.tasks.v2beta2.Task] resource. """ - name = proto.Field(proto.STRING, number=1) - - schedule_time = proto.Field(proto.MESSAGE, number=2, message=timestamp.Timestamp,) - - lease_duration = proto.Field(proto.MESSAGE, number=3, message=duration.Duration,) - + name = proto.Field(proto.STRING, number=1,) + schedule_time = proto.Field( + proto.MESSAGE, number=2, message=timestamp_pb2.Timestamp, + ) + lease_duration = proto.Field( + proto.MESSAGE, number=3, message=duration_pb2.Duration, + ) response_view = proto.Field(proto.ENUM, number=4, enum=gct_task.Task.View,) @@ -698,10 +682,10 @@ class CancelLeaseRequest(proto.Message): [Task][google.cloud.tasks.v2beta2.Task] resource. """ - name = proto.Field(proto.STRING, number=1) - - schedule_time = proto.Field(proto.MESSAGE, number=2, message=timestamp.Timestamp,) - + name = proto.Field(proto.STRING, number=1,) + schedule_time = proto.Field( + proto.MESSAGE, number=2, message=timestamp_pb2.Timestamp, + ) response_view = proto.Field(proto.ENUM, number=3, enum=gct_task.Task.View,) @@ -731,8 +715,7 @@ class RunTaskRequest(proto.Message): [Task][google.cloud.tasks.v2beta2.Task] resource. """ - name = proto.Field(proto.STRING, number=1) - + name = proto.Field(proto.STRING, number=1,) response_view = proto.Field(proto.ENUM, number=2, enum=gct_task.Task.View,) diff --git a/google/cloud/tasks_v2beta2/types/queue.py b/google/cloud/tasks_v2beta2/types/queue.py index 093e1400..597f6fc0 100644 --- a/google/cloud/tasks_v2beta2/types/queue.py +++ b/google/cloud/tasks_v2beta2/types/queue.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.cloud.tasks_v2beta2.types import target -from google.protobuf import duration_pb2 as duration # type: ignore -from google.protobuf import timestamp_pb2 as timestamp # type: ignore +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore __protobuf__ = proto.module( @@ -104,7 +101,7 @@ class Queue(proto.Message): state (google.cloud.tasks_v2beta2.types.Queue.State): Output only. The state of the queue. - ``state`` can only be changed by called + ``state`` can only be changed by calling [PauseQueue][google.cloud.tasks.v2beta2.CloudTasks.PauseQueue], [ResumeQueue][google.cloud.tasks.v2beta2.CloudTasks.ResumeQueue], or uploading @@ -167,31 +164,24 @@ class State(proto.Enum): PAUSED = 2 DISABLED = 3 - name = proto.Field(proto.STRING, number=1) - + name = proto.Field(proto.STRING, number=1,) app_engine_http_target = proto.Field( proto.MESSAGE, number=3, oneof="target_type", message=target.AppEngineHttpTarget, ) - pull_target = proto.Field( proto.MESSAGE, number=4, oneof="target_type", message=target.PullTarget, ) - rate_limits = proto.Field(proto.MESSAGE, number=5, message="RateLimits",) - retry_config = proto.Field(proto.MESSAGE, number=6, message="RetryConfig",) - state = proto.Field(proto.ENUM, number=7, enum=State,) - - purge_time = proto.Field(proto.MESSAGE, number=8, message=timestamp.Timestamp,) - - task_ttl = proto.Field(proto.MESSAGE, number=9, message=duration.Duration,) - - tombstone_ttl = proto.Field(proto.MESSAGE, number=10, message=duration.Duration,) - + purge_time = proto.Field(proto.MESSAGE, number=8, message=timestamp_pb2.Timestamp,) + task_ttl = proto.Field(proto.MESSAGE, number=9, message=duration_pb2.Duration,) + tombstone_ttl = proto.Field( + proto.MESSAGE, number=10, message=duration_pb2.Duration, + ) stats = proto.Field(proto.MESSAGE, number=16, message="QueueStats",) @@ -286,11 +276,9 @@ class RateLimits(proto.Message): queue.yaml/xml `__. """ - max_tasks_dispatched_per_second = proto.Field(proto.DOUBLE, number=1) - - max_burst_size = proto.Field(proto.INT32, number=2) - - max_concurrent_tasks = proto.Field(proto.INT32, number=3) + max_tasks_dispatched_per_second = proto.Field(proto.DOUBLE, number=1,) + max_burst_size = proto.Field(proto.INT32, number=2,) + max_concurrent_tasks = proto.Field(proto.INT32, number=3,) class RetryConfig(proto.Message): @@ -408,24 +396,18 @@ class RetryConfig(proto.Message): queue.yaml/xml `__. """ - max_attempts = proto.Field(proto.INT32, number=1, oneof="num_attempts") - - unlimited_attempts = proto.Field(proto.BOOL, number=2, oneof="num_attempts") - + max_attempts = proto.Field(proto.INT32, number=1, oneof="num_attempts",) + unlimited_attempts = proto.Field(proto.BOOL, number=2, oneof="num_attempts",) max_retry_duration = proto.Field( - proto.MESSAGE, number=3, message=duration.Duration, + proto.MESSAGE, number=3, message=duration_pb2.Duration, ) - - min_backoff = proto.Field(proto.MESSAGE, number=4, message=duration.Duration,) - - max_backoff = proto.Field(proto.MESSAGE, number=5, message=duration.Duration,) - - max_doublings = proto.Field(proto.INT32, number=6) + min_backoff = proto.Field(proto.MESSAGE, number=4, message=duration_pb2.Duration,) + max_backoff = proto.Field(proto.MESSAGE, number=5, message=duration_pb2.Duration,) + max_doublings = proto.Field(proto.INT32, number=6,) class QueueStats(proto.Message): r"""Statistics for a queue. - Attributes: tasks_count (int): Output only. An estimation of the number of @@ -456,17 +438,13 @@ class QueueStats(proto.Message): tasks in the queue are targeting. """ - tasks_count = proto.Field(proto.INT64, number=1) - + tasks_count = proto.Field(proto.INT64, number=1,) oldest_estimated_arrival_time = proto.Field( - proto.MESSAGE, number=2, message=timestamp.Timestamp, + proto.MESSAGE, number=2, message=timestamp_pb2.Timestamp, ) - - executed_last_minute_count = proto.Field(proto.INT64, number=3) - - concurrent_dispatches_count = proto.Field(proto.INT64, number=4) - - effective_execution_rate = proto.Field(proto.DOUBLE, number=5) + executed_last_minute_count = proto.Field(proto.INT64, number=3,) + concurrent_dispatches_count = proto.Field(proto.INT64, number=4,) + effective_execution_rate = proto.Field(proto.DOUBLE, number=5,) __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/tasks_v2beta2/types/target.py b/google/cloud/tasks_v2beta2/types/target.py index 5c976b10..2b043d55 100644 --- a/google/cloud/tasks_v2beta2/types/target.py +++ b/google/cloud/tasks_v2beta2/types/target.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 @@ -42,7 +40,7 @@ class HttpMethod(proto.Enum): class PullTarget(proto.Message): - r"""Pull target.""" + r"""Pull target. """ class PullMessage(proto.Message): @@ -82,9 +80,8 @@ class PullMessage(proto.Message): returned by Cloud Tasks. """ - payload = proto.Field(proto.BYTES, number=1) - - tag = proto.Field(proto.STRING, number=2) + payload = proto.Field(proto.BYTES, number=1,) + tag = proto.Field(proto.STRING, number=2,) class AppEngineHttpTarget(proto.Message): @@ -281,16 +278,12 @@ class AppEngineHttpRequest(proto.Message): """ http_method = proto.Field(proto.ENUM, number=1, enum="HttpMethod",) - app_engine_routing = proto.Field( proto.MESSAGE, number=2, message="AppEngineRouting", ) - - relative_url = proto.Field(proto.STRING, number=3) - - headers = proto.MapField(proto.STRING, proto.STRING, number=4) - - payload = proto.Field(proto.BYTES, number=5) + relative_url = proto.Field(proto.STRING, number=3,) + headers = proto.MapField(proto.STRING, proto.STRING, number=4,) + payload = proto.Field(proto.BYTES, number=5,) class AppEngineRouting(proto.Message): @@ -449,13 +442,10 @@ class AppEngineRouting(proto.Message): version of the default service when the task is attempted. """ - service = proto.Field(proto.STRING, number=1) - - version = proto.Field(proto.STRING, number=2) - - instance = proto.Field(proto.STRING, number=3) - - host = proto.Field(proto.STRING, number=4) + service = proto.Field(proto.STRING, number=1,) + version = proto.Field(proto.STRING, number=2,) + instance = proto.Field(proto.STRING, number=3,) + host = proto.Field(proto.STRING, number=4,) __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/tasks_v2beta2/types/task.py b/google/cloud/tasks_v2beta2/types/task.py index 3d009018..877fd334 100644 --- a/google/cloud/tasks_v2beta2/types/task.py +++ b/google/cloud/tasks_v2beta2/types/task.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.cloud.tasks_v2beta2.types import target -from google.protobuf import timestamp_pb2 as timestamp # type: ignore -from google.rpc import status_pb2 as gr_status # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from google.rpc import status_pb2 # type: ignore __protobuf__ = proto.module( @@ -31,7 +28,6 @@ class Task(proto.Message): r"""A unit of scheduled work. - Attributes: name (str): Optionally caller-specified in @@ -113,31 +109,26 @@ class View(proto.Enum): BASIC = 1 FULL = 2 - name = proto.Field(proto.STRING, number=1) - + name = proto.Field(proto.STRING, number=1,) app_engine_http_request = proto.Field( proto.MESSAGE, number=3, oneof="payload_type", message=target.AppEngineHttpRequest, ) - pull_message = proto.Field( proto.MESSAGE, number=4, oneof="payload_type", message=target.PullMessage, ) - - schedule_time = proto.Field(proto.MESSAGE, number=5, message=timestamp.Timestamp,) - - create_time = proto.Field(proto.MESSAGE, number=6, message=timestamp.Timestamp,) - + schedule_time = proto.Field( + proto.MESSAGE, number=5, message=timestamp_pb2.Timestamp, + ) + create_time = proto.Field(proto.MESSAGE, number=6, message=timestamp_pb2.Timestamp,) status = proto.Field(proto.MESSAGE, number=7, message="TaskStatus",) - view = proto.Field(proto.ENUM, number=8, enum=View,) class TaskStatus(proto.Message): r"""Status of the task. - Attributes: attempt_dispatch_count (int): Output only. The number of attempts @@ -168,20 +159,16 @@ class TaskStatus(proto.Message): tasks][google.cloud.tasks.v2beta2.PullMessage]. """ - attempt_dispatch_count = proto.Field(proto.INT32, number=1) - - attempt_response_count = proto.Field(proto.INT32, number=2) - + attempt_dispatch_count = proto.Field(proto.INT32, number=1,) + attempt_response_count = proto.Field(proto.INT32, number=2,) first_attempt_status = proto.Field( proto.MESSAGE, number=3, message="AttemptStatus", ) - last_attempt_status = proto.Field(proto.MESSAGE, number=4, message="AttemptStatus",) class AttemptStatus(proto.Message): r"""The status of a task attempt. - Attributes: schedule_time (google.protobuf.timestamp_pb2.Timestamp): Output only. The time that this attempt was scheduled. @@ -207,13 +194,16 @@ class AttemptStatus(proto.Message): unset. """ - schedule_time = proto.Field(proto.MESSAGE, number=1, message=timestamp.Timestamp,) - - dispatch_time = proto.Field(proto.MESSAGE, number=2, message=timestamp.Timestamp,) - - response_time = proto.Field(proto.MESSAGE, number=3, message=timestamp.Timestamp,) - - response_status = proto.Field(proto.MESSAGE, number=4, message=gr_status.Status,) + schedule_time = proto.Field( + proto.MESSAGE, number=1, message=timestamp_pb2.Timestamp, + ) + dispatch_time = proto.Field( + proto.MESSAGE, number=2, message=timestamp_pb2.Timestamp, + ) + response_time = proto.Field( + proto.MESSAGE, number=3, message=timestamp_pb2.Timestamp, + ) + response_status = proto.Field(proto.MESSAGE, number=4, message=status_pb2.Status,) __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/tasks_v2beta3/__init__.py b/google/cloud/tasks_v2beta3/__init__.py index 143c0ff3..67f9d9ee 100644 --- a/google/cloud/tasks_v2beta3/__init__.py +++ b/google/cloud/tasks_v2beta3/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -16,6 +15,8 @@ # from .services.cloud_tasks import CloudTasksClient +from .services.cloud_tasks import CloudTasksAsyncClient + from .types.cloudtasks import CreateQueueRequest from .types.cloudtasks import CreateTaskRequest from .types.cloudtasks import DeleteQueueRequest @@ -39,20 +40,21 @@ from .types.target import AppEngineHttpQueue from .types.target import AppEngineHttpRequest from .types.target import AppEngineRouting -from .types.target import HttpMethod from .types.target import HttpRequest from .types.target import OAuthToken from .types.target import OidcToken from .types.target import PullMessage +from .types.target import HttpMethod from .types.task import Attempt from .types.task import Task - __all__ = ( + "CloudTasksAsyncClient", "AppEngineHttpQueue", "AppEngineHttpRequest", "AppEngineRouting", "Attempt", + "CloudTasksClient", "CreateQueueRequest", "CreateTaskRequest", "DeleteQueueRequest", @@ -79,5 +81,4 @@ "StackdriverLoggingConfig", "Task", "UpdateQueueRequest", - "CloudTasksClient", ) diff --git a/google/cloud/tasks_v2beta3/gapic_metadata.json b/google/cloud/tasks_v2beta3/gapic_metadata.json new file mode 100644 index 00000000..1f8cc2e7 --- /dev/null +++ b/google/cloud/tasks_v2beta3/gapic_metadata.json @@ -0,0 +1,183 @@ + { + "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", + "language": "python", + "libraryPackage": "google.cloud.tasks_v2beta3", + "protoPackage": "google.cloud.tasks.v2beta3", + "schema": "1.0", + "services": { + "CloudTasks": { + "clients": { + "grpc": { + "libraryClient": "CloudTasksClient", + "rpcs": { + "CreateQueue": { + "methods": [ + "create_queue" + ] + }, + "CreateTask": { + "methods": [ + "create_task" + ] + }, + "DeleteQueue": { + "methods": [ + "delete_queue" + ] + }, + "DeleteTask": { + "methods": [ + "delete_task" + ] + }, + "GetIamPolicy": { + "methods": [ + "get_iam_policy" + ] + }, + "GetQueue": { + "methods": [ + "get_queue" + ] + }, + "GetTask": { + "methods": [ + "get_task" + ] + }, + "ListQueues": { + "methods": [ + "list_queues" + ] + }, + "ListTasks": { + "methods": [ + "list_tasks" + ] + }, + "PauseQueue": { + "methods": [ + "pause_queue" + ] + }, + "PurgeQueue": { + "methods": [ + "purge_queue" + ] + }, + "ResumeQueue": { + "methods": [ + "resume_queue" + ] + }, + "RunTask": { + "methods": [ + "run_task" + ] + }, + "SetIamPolicy": { + "methods": [ + "set_iam_policy" + ] + }, + "TestIamPermissions": { + "methods": [ + "test_iam_permissions" + ] + }, + "UpdateQueue": { + "methods": [ + "update_queue" + ] + } + } + }, + "grpc-async": { + "libraryClient": "CloudTasksAsyncClient", + "rpcs": { + "CreateQueue": { + "methods": [ + "create_queue" + ] + }, + "CreateTask": { + "methods": [ + "create_task" + ] + }, + "DeleteQueue": { + "methods": [ + "delete_queue" + ] + }, + "DeleteTask": { + "methods": [ + "delete_task" + ] + }, + "GetIamPolicy": { + "methods": [ + "get_iam_policy" + ] + }, + "GetQueue": { + "methods": [ + "get_queue" + ] + }, + "GetTask": { + "methods": [ + "get_task" + ] + }, + "ListQueues": { + "methods": [ + "list_queues" + ] + }, + "ListTasks": { + "methods": [ + "list_tasks" + ] + }, + "PauseQueue": { + "methods": [ + "pause_queue" + ] + }, + "PurgeQueue": { + "methods": [ + "purge_queue" + ] + }, + "ResumeQueue": { + "methods": [ + "resume_queue" + ] + }, + "RunTask": { + "methods": [ + "run_task" + ] + }, + "SetIamPolicy": { + "methods": [ + "set_iam_policy" + ] + }, + "TestIamPermissions": { + "methods": [ + "test_iam_permissions" + ] + }, + "UpdateQueue": { + "methods": [ + "update_queue" + ] + } + } + } + } + } + } +} diff --git a/google/cloud/tasks_v2beta3/services/__init__.py b/google/cloud/tasks_v2beta3/services/__init__.py index 42ffdf2b..4de65971 100644 --- a/google/cloud/tasks_v2beta3/services/__init__.py +++ b/google/cloud/tasks_v2beta3/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/cloud/tasks_v2beta3/services/cloud_tasks/__init__.py b/google/cloud/tasks_v2beta3/services/cloud_tasks/__init__.py index 498f5941..d6abe162 100644 --- a/google/cloud/tasks_v2beta3/services/cloud_tasks/__init__.py +++ b/google/cloud/tasks_v2beta3/services/cloud_tasks/__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 CloudTasksClient from .async_client import CloudTasksAsyncClient diff --git a/google/cloud/tasks_v2beta3/services/cloud_tasks/async_client.py b/google/cloud/tasks_v2beta3/services/cloud_tasks/async_client.py index 2107df3f..363ec98a 100644 --- a/google/cloud/tasks_v2beta3/services/cloud_tasks/async_client.py +++ b/google/cloud/tasks_v2beta3/services/cloud_tasks/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,10 +20,10 @@ 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.cloud.tasks_v2beta3.services.cloud_tasks import pagers @@ -35,12 +33,11 @@ from google.cloud.tasks_v2beta3.types import target from google.cloud.tasks_v2beta3.types import task from google.cloud.tasks_v2beta3.types import task as gct_task -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 field_mask_pb2 as field_mask # 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 field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore from .transports.base import CloudTasksTransport, DEFAULT_CLIENT_INFO from .transports.grpc_asyncio import CloudTasksGrpcAsyncIOTransport from .client import CloudTasksClient @@ -60,37 +57,61 @@ class CloudTasksAsyncClient: parse_queue_path = staticmethod(CloudTasksClient.parse_queue_path) task_path = staticmethod(CloudTasksClient.task_path) parse_task_path = staticmethod(CloudTasksClient.parse_task_path) - common_billing_account_path = staticmethod( CloudTasksClient.common_billing_account_path ) parse_common_billing_account_path = staticmethod( CloudTasksClient.parse_common_billing_account_path ) - common_folder_path = staticmethod(CloudTasksClient.common_folder_path) parse_common_folder_path = staticmethod(CloudTasksClient.parse_common_folder_path) - common_organization_path = staticmethod(CloudTasksClient.common_organization_path) parse_common_organization_path = staticmethod( CloudTasksClient.parse_common_organization_path ) - common_project_path = staticmethod(CloudTasksClient.common_project_path) parse_common_project_path = staticmethod(CloudTasksClient.parse_common_project_path) - common_location_path = staticmethod(CloudTasksClient.common_location_path) parse_common_location_path = staticmethod( CloudTasksClient.parse_common_location_path ) - from_service_account_info = CloudTasksClient.from_service_account_info - from_service_account_file = CloudTasksClient.from_service_account_file + @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: + CloudTasksAsyncClient: The constructed client. + """ + return CloudTasksClient.from_service_account_info.__func__(CloudTasksAsyncClient, 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: + CloudTasksAsyncClient: The constructed client. + """ + return CloudTasksClient.from_service_account_file.__func__(CloudTasksAsyncClient, filename, *args, **kwargs) # type: ignore + from_service_account_json = from_service_account_file @property def transport(self) -> CloudTasksTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: CloudTasksTransport: The transport used by the client instance. @@ -104,12 +125,12 @@ def transport(self) -> CloudTasksTransport: def __init__( self, *, - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, transport: Union[str, CloudTasksTransport] = "grpc_asyncio", client_options: ClientOptions = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: - """Instantiate the cloud tasks client. + """Instantiates the cloud tasks client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -141,7 +162,6 @@ def __init__( google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport creation failed for any reason. """ - self._client = CloudTasksClient( credentials=credentials, transport=transport, @@ -172,7 +192,6 @@ async def list_queues( 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. @@ -202,7 +221,6 @@ async def list_queues( # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent @@ -215,8 +233,10 @@ async def list_queues( maximum=10.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), + deadline=20.0, ), default_timeout=20.0, client_info=DEFAULT_CLIENT_INFO, @@ -262,7 +282,6 @@ async def get_queue( 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. @@ -293,7 +312,6 @@ async def get_queue( # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -306,8 +324,10 @@ async def get_queue( maximum=10.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), + deadline=20.0, ), default_timeout=20.0, client_info=DEFAULT_CLIENT_INFO, @@ -372,7 +392,6 @@ async def create_queue( This corresponds to the ``queue`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -403,7 +422,6 @@ async def create_queue( # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent if queue is not None: @@ -434,7 +452,7 @@ async def update_queue( request: cloudtasks.UpdateQueueRequest = None, *, queue: gct_queue.Queue = None, - update_mask: field_mask.FieldMask = None, + update_mask: field_mask_pb2.FieldMask = None, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), @@ -483,7 +501,6 @@ async def update_queue( This corresponds to the ``update_mask`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -514,7 +531,6 @@ async def update_queue( # If we have keyword arguments corresponding to fields on the # request, apply these. - if queue is not None: request.queue = queue if update_mask is not None: @@ -575,7 +591,6 @@ async def delete_queue( 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. @@ -596,7 +611,6 @@ async def delete_queue( # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -609,8 +623,10 @@ async def delete_queue( maximum=10.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), + deadline=20.0, ), default_timeout=20.0, client_info=DEFAULT_CLIENT_INFO, @@ -654,7 +670,6 @@ async def purge_queue( 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. @@ -685,7 +700,6 @@ async def purge_queue( # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -738,7 +752,6 @@ async def pause_queue( 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. @@ -769,7 +782,6 @@ async def pause_queue( # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -829,7 +841,6 @@ async def resume_queue( 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. @@ -860,7 +871,6 @@ async def resume_queue( # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -886,13 +896,13 @@ async def resume_queue( async def get_iam_policy( self, - request: iam_policy.GetIamPolicyRequest = None, + request: iam_policy_pb2.GetIamPolicyRequest = None, *, resource: str = None, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), - ) -> policy.Policy: + ) -> policy_pb2.Policy: r"""Gets the access control policy for a [Queue][google.cloud.tasks.v2beta3.Queue]. Returns an empty policy if the resource exists and does not have a policy set. @@ -916,7 +926,6 @@ async def get_iam_policy( This corresponds to the ``resource`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -995,10 +1004,9 @@ 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) elif not request: - request = iam_policy.GetIamPolicyRequest(resource=resource,) + request = iam_policy_pb2.GetIamPolicyRequest(resource=resource,) # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. @@ -1009,8 +1017,10 @@ async def get_iam_policy( maximum=10.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), + deadline=20.0, ), default_timeout=20.0, client_info=DEFAULT_CLIENT_INFO, @@ -1030,13 +1040,13 @@ async def get_iam_policy( async def set_iam_policy( self, - request: iam_policy.SetIamPolicyRequest = None, + request: iam_policy_pb2.SetIamPolicyRequest = None, *, resource: str = None, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), - ) -> policy.Policy: + ) -> policy_pb2.Policy: r"""Sets the access control policy for a [Queue][google.cloud.tasks.v2beta3.Queue]. Replaces any existing policy. @@ -1064,7 +1074,6 @@ async def set_iam_policy( This corresponds to the ``resource`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -1143,10 +1152,9 @@ 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) elif not request: - request = iam_policy.SetIamPolicyRequest(resource=resource,) + request = iam_policy_pb2.SetIamPolicyRequest(resource=resource,) # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. @@ -1170,14 +1178,14 @@ async def set_iam_policy( async def test_iam_permissions( self, - request: iam_policy.TestIamPermissionsRequest = None, + request: iam_policy_pb2.TestIamPermissionsRequest = None, *, resource: str = None, permissions: Sequence[str] = None, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), - ) -> iam_policy.TestIamPermissionsResponse: + ) -> iam_policy_pb2.TestIamPermissionsResponse: r"""Returns permissions that a caller has on a [Queue][google.cloud.tasks.v2beta3.Queue]. If the resource does not exist, this will return an empty set of permissions, not a @@ -1210,7 +1218,6 @@ async def test_iam_permissions( This corresponds to the ``permissions`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -1234,10 +1241,9 @@ 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) elif not request: - request = iam_policy.TestIamPermissionsRequest( + request = iam_policy_pb2.TestIamPermissionsRequest( resource=resource, permissions=permissions, ) @@ -1250,8 +1256,10 @@ async def test_iam_permissions( maximum=10.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), + deadline=20.0, ), default_timeout=20.0, client_info=DEFAULT_CLIENT_INFO, @@ -1301,7 +1309,6 @@ async def list_tasks( 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. @@ -1331,7 +1338,6 @@ async def list_tasks( # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent @@ -1344,8 +1350,10 @@ async def list_tasks( maximum=10.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), + deadline=20.0, ), default_timeout=20.0, client_info=DEFAULT_CLIENT_INFO, @@ -1392,7 +1400,6 @@ async def get_task( 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. @@ -1417,7 +1424,6 @@ async def get_task( # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -1430,8 +1436,10 @@ async def get_task( maximum=10.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), + deadline=20.0, ), default_timeout=20.0, client_info=DEFAULT_CLIENT_INFO, @@ -1525,7 +1533,6 @@ async def create_task( This corresponds to the ``task`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -1550,7 +1557,6 @@ async def create_task( # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent if task is not None: @@ -1602,7 +1608,6 @@ async def delete_task( 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. @@ -1623,7 +1628,6 @@ async def delete_task( # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -1636,8 +1640,10 @@ async def delete_task( maximum=10.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), + deadline=20.0, ), default_timeout=20.0, client_info=DEFAULT_CLIENT_INFO, @@ -1704,7 +1710,6 @@ async def run_task( 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. @@ -1729,7 +1734,6 @@ async def run_task( # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name diff --git a/google/cloud/tasks_v2beta3/services/cloud_tasks/client.py b/google/cloud/tasks_v2beta3/services/cloud_tasks/client.py index 0dd8eacd..cb91665f 100644 --- a/google/cloud/tasks_v2beta3/services/cloud_tasks/client.py +++ b/google/cloud/tasks_v2beta3/services/cloud_tasks/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,10 +21,10 @@ 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 @@ -39,12 +37,11 @@ from google.cloud.tasks_v2beta3.types import target from google.cloud.tasks_v2beta3.types import task from google.cloud.tasks_v2beta3.types import task as gct_task -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 field_mask_pb2 as field_mask # 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 field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore from .transports.base import CloudTasksTransport, DEFAULT_CLIENT_INFO from .transports.grpc import CloudTasksGrpcTransport from .transports.grpc_asyncio import CloudTasksGrpcAsyncIOTransport @@ -63,7 +60,7 @@ class CloudTasksClientMeta(type): _transport_registry["grpc_asyncio"] = CloudTasksGrpcAsyncIOTransport def get_transport_class(cls, label: str = None,) -> Type[CloudTasksTransport]: - """Return an appropriate transport class. + """Returns an appropriate transport class. Args: label: The name of the desired transport. If none is @@ -88,7 +85,8 @@ class CloudTasksClient(metaclass=CloudTasksClientMeta): @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: @@ -122,7 +120,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. @@ -139,7 +138,7 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials - file. + file. Args: filename (str): The path to the service account private key json @@ -158,23 +157,24 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> CloudTasksTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: - CloudTasksTransport: The transport used by the client instance. + CloudTasksTransport: The transport used by the client + instance. """ return self._transport @staticmethod def queue_path(project: str, location: str, queue: str,) -> str: - """Return a fully-qualified queue string.""" + """Returns a fully-qualified queue string.""" return "projects/{project}/locations/{location}/queues/{queue}".format( project=project, location=location, queue=queue, ) @staticmethod def parse_queue_path(path: str) -> Dict[str, str]: - """Parse a queue path into its component segments.""" + """Parses a queue path into its component segments.""" m = re.match( r"^projects/(?P.+?)/locations/(?P.+?)/queues/(?P.+?)$", path, @@ -183,14 +183,14 @@ def parse_queue_path(path: str) -> Dict[str, str]: @staticmethod def task_path(project: str, location: str, queue: str, task: str,) -> str: - """Return a fully-qualified task string.""" + """Returns a fully-qualified task string.""" return "projects/{project}/locations/{location}/queues/{queue}/tasks/{task}".format( project=project, location=location, queue=queue, task=task, ) @staticmethod def parse_task_path(path: str) -> Dict[str, str]: - """Parse a task path into its component segments.""" + """Parses a task path into its component segments.""" m = re.match( r"^projects/(?P.+?)/locations/(?P.+?)/queues/(?P.+?)/tasks/(?P.+?)$", path, @@ -199,7 +199,7 @@ def parse_task_path(path: str) -> Dict[str, str]: @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, ) @@ -212,7 +212,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 @@ -223,7 +223,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 @@ -234,7 +234,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 @@ -245,7 +245,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, ) @@ -259,12 +259,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, CloudTasksTransport, None] = None, client_options: Optional[client_options_lib.ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: - """Instantiate the cloud tasks client. + """Instantiates the cloud tasks client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -319,9 +319,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: @@ -333,12 +334,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. @@ -353,8 +356,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: @@ -392,7 +395,6 @@ def list_queues( 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. @@ -424,10 +426,8 @@ def list_queues( # there are no flattened fields. if not isinstance(request, cloudtasks.ListQueuesRequest): request = cloudtasks.ListQueuesRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent @@ -475,7 +475,6 @@ def get_queue( 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. @@ -508,10 +507,8 @@ def get_queue( # there are no flattened fields. if not isinstance(request, cloudtasks.GetQueueRequest): request = cloudtasks.GetQueueRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -578,7 +575,6 @@ def create_queue( This corresponds to the ``queue`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -611,10 +607,8 @@ def create_queue( # there are no flattened fields. if not isinstance(request, cloudtasks.CreateQueueRequest): request = cloudtasks.CreateQueueRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent if queue is not None: @@ -641,7 +635,7 @@ def update_queue( request: cloudtasks.UpdateQueueRequest = None, *, queue: gct_queue.Queue = None, - update_mask: field_mask.FieldMask = None, + update_mask: field_mask_pb2.FieldMask = None, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), @@ -690,7 +684,6 @@ def update_queue( This corresponds to the ``update_mask`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -723,10 +716,8 @@ def update_queue( # there are no flattened fields. if not isinstance(request, cloudtasks.UpdateQueueRequest): request = cloudtasks.UpdateQueueRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if queue is not None: request.queue = queue if update_mask is not None: @@ -783,7 +774,6 @@ def delete_queue( 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. @@ -806,10 +796,8 @@ def delete_queue( # there are no flattened fields. if not isinstance(request, cloudtasks.DeleteQueueRequest): request = cloudtasks.DeleteQueueRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -855,7 +843,6 @@ def purge_queue( 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. @@ -888,10 +875,8 @@ def purge_queue( # there are no flattened fields. if not isinstance(request, cloudtasks.PurgeQueueRequest): request = cloudtasks.PurgeQueueRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -940,7 +925,6 @@ def pause_queue( 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. @@ -973,10 +957,8 @@ def pause_queue( # there are no flattened fields. if not isinstance(request, cloudtasks.PauseQueueRequest): request = cloudtasks.PauseQueueRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -1032,7 +1014,6 @@ def resume_queue( 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. @@ -1065,10 +1046,8 @@ def resume_queue( # there are no flattened fields. if not isinstance(request, cloudtasks.ResumeQueueRequest): request = cloudtasks.ResumeQueueRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -1090,13 +1069,13 @@ def resume_queue( def get_iam_policy( self, - request: iam_policy.GetIamPolicyRequest = None, + request: iam_policy_pb2.GetIamPolicyRequest = None, *, resource: str = None, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), - ) -> policy.Policy: + ) -> policy_pb2.Policy: r"""Gets the access control policy for a [Queue][google.cloud.tasks.v2beta3.Queue]. Returns an empty policy if the resource exists and does not have a policy set. @@ -1120,7 +1099,6 @@ def get_iam_policy( This corresponds to the ``resource`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -1196,14 +1174,13 @@ def get_iam_policy( "the individual field arguments should be set." ) - # 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) - + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + request = iam_policy_pb2.GetIamPolicyRequest(**request) elif not request: - request = iam_policy.GetIamPolicyRequest(resource=resource,) - + # Null request, just make one. + request = iam_policy_pb2.GetIamPolicyRequest() if resource is not None: request.resource = resource @@ -1225,13 +1202,13 @@ def get_iam_policy( def set_iam_policy( self, - request: iam_policy.SetIamPolicyRequest = None, + request: iam_policy_pb2.SetIamPolicyRequest = None, *, resource: str = None, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), - ) -> policy.Policy: + ) -> policy_pb2.Policy: r"""Sets the access control policy for a [Queue][google.cloud.tasks.v2beta3.Queue]. Replaces any existing policy. @@ -1259,7 +1236,6 @@ def set_iam_policy( This corresponds to the ``resource`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -1335,14 +1311,13 @@ def set_iam_policy( "the individual field arguments should be set." ) - # 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) - + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + request = iam_policy_pb2.SetIamPolicyRequest(**request) elif not request: - request = iam_policy.SetIamPolicyRequest(resource=resource,) - + # Null request, just make one. + request = iam_policy_pb2.SetIamPolicyRequest() if resource is not None: request.resource = resource @@ -1364,14 +1339,14 @@ def set_iam_policy( def test_iam_permissions( self, - request: iam_policy.TestIamPermissionsRequest = None, + request: iam_policy_pb2.TestIamPermissionsRequest = None, *, resource: str = None, permissions: Sequence[str] = None, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), - ) -> iam_policy.TestIamPermissionsResponse: + ) -> iam_policy_pb2.TestIamPermissionsResponse: r"""Returns permissions that a caller has on a [Queue][google.cloud.tasks.v2beta3.Queue]. If the resource does not exist, this will return an empty set of permissions, not a @@ -1404,7 +1379,6 @@ def test_iam_permissions( This corresponds to the ``permissions`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -1425,18 +1399,17 @@ def test_iam_permissions( "the individual field arguments should be set." ) - # 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) - + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + request = iam_policy_pb2.TestIamPermissionsRequest(**request) elif not request: - request = iam_policy.TestIamPermissionsRequest( - resource=resource, permissions=permissions, - ) - + # Null request, just make one. + request = iam_policy_pb2.TestIamPermissionsRequest() if resource is not None: request.resource = resource + if permissions: + request.permissions.extend(permissions) # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. @@ -1486,7 +1459,6 @@ def list_tasks( 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. @@ -1518,10 +1490,8 @@ def list_tasks( # there are no flattened fields. if not isinstance(request, cloudtasks.ListTasksRequest): request = cloudtasks.ListTasksRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent @@ -1570,7 +1540,6 @@ def get_task( 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. @@ -1597,10 +1566,8 @@ def get_task( # there are no flattened fields. if not isinstance(request, cloudtasks.GetTaskRequest): request = cloudtasks.GetTaskRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -1696,7 +1663,6 @@ def create_task( This corresponds to the ``task`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -1723,10 +1689,8 @@ def create_task( # there are no flattened fields. if not isinstance(request, cloudtasks.CreateTaskRequest): request = cloudtasks.CreateTaskRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent if task is not None: @@ -1774,7 +1738,6 @@ def delete_task( 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. @@ -1797,10 +1760,8 @@ def delete_task( # there are no flattened fields. if not isinstance(request, cloudtasks.DeleteTaskRequest): request = cloudtasks.DeleteTaskRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -1869,7 +1830,6 @@ def run_task( 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. @@ -1896,10 +1856,8 @@ def run_task( # there are no flattened fields. if not isinstance(request, cloudtasks.RunTaskRequest): request = cloudtasks.RunTaskRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name diff --git a/google/cloud/tasks_v2beta3/services/cloud_tasks/pagers.py b/google/cloud/tasks_v2beta3/services/cloud_tasks/pagers.py index eeb07fe4..b4e1ecdb 100644 --- a/google/cloud/tasks_v2beta3/services/cloud_tasks/pagers.py +++ b/google/cloud/tasks_v2beta3/services/cloud_tasks/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, @@ -119,7 +117,7 @@ def __init__( *, metadata: Sequence[Tuple[str, str]] = () ): - """Instantiate the pager. + """Instantiates the pager. Args: method (Callable): The method that was originally called, and @@ -247,7 +245,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/cloud/tasks_v2beta3/services/cloud_tasks/transports/__init__.py b/google/cloud/tasks_v2beta3/services/cloud_tasks/transports/__init__.py index f386bcfd..9056507e 100644 --- a/google/cloud/tasks_v2beta3/services/cloud_tasks/transports/__init__.py +++ b/google/cloud/tasks_v2beta3/services/cloud_tasks/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/cloud/tasks_v2beta3/services/cloud_tasks/transports/base.py b/google/cloud/tasks_v2beta3/services/cloud_tasks/transports/base.py index d5c25b51..5c331ac6 100644 --- a/google/cloud/tasks_v2beta3/services/cloud_tasks/transports/base.py +++ b/google/cloud/tasks_v2beta3/services/cloud_tasks/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,26 +13,26 @@ # 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.cloud.tasks_v2beta3.types import cloudtasks from google.cloud.tasks_v2beta3.types import queue from google.cloud.tasks_v2beta3.types import queue as gct_queue from google.cloud.tasks_v2beta3.types import task from google.cloud.tasks_v2beta3.types import task as gct_task -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 try: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( @@ -42,27 +41,41 @@ except pkg_resources.DistributionNotFound: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() +try: + # google.auth.__version__ was added in 1.26.0 + _GOOGLE_AUTH_VERSION = google.auth.__version__ +except AttributeError: + try: # try pkg_resources if it is available + _GOOGLE_AUTH_VERSION = pkg_resources.get_distribution("google-auth").version + except pkg_resources.DistributionNotFound: # pragma: NO COVER + _GOOGLE_AUTH_VERSION = None + +_API_CORE_VERSION = google.api_core.__version__ + class CloudTasksTransport(abc.ABC): """Abstract transport class for CloudTasks.""" AUTH_SCOPES = ("https://www.googleapis.com/auth/cloud-platform",) + DEFAULT_HOST: str = "cloudtasks.googleapis.com" + def __init__( self, *, - host: str = "cloudtasks.googleapis.com", - credentials: credentials.Credentials = None, - credentials_file: typing.Optional[str] = None, - scopes: typing.Optional[typing.Sequence[str]] = AUTH_SCOPES, - quota_project_id: typing.Optional[str] = None, + host: str = DEFAULT_HOST, + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, **kwargs, ) -> None: """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + host (Optional[str]): + The hostname to connect to. credentials (Optional[google.auth.credentials.Credentials]): The authorization credentials to attach to requests. These credentials identify the application to the service; if none @@ -71,13 +84,13 @@ 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): - 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 + 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. @@ -85,28 +98,75 @@ def __init__( host += ":443" self._host = host + scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) + + # Save the scopes. + self._scopes = scopes or self.AUTH_SCOPES + # If no credentials are provided, then determine the appropriate # defaults. if credentials and credentials_file: - raise exceptions.DuplicateCredentialArgs( + raise core_exceptions.DuplicateCredentialArgs( "'credentials_file' and 'credentials' are mutually exclusive" ) if credentials_file is not None: - credentials, _ = auth.load_credentials_from_file( - credentials_file, scopes=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=scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.default( + **scopes_kwargs, quota_project_id=quota_project_id ) # Save the credentials. self._credentials = credentials - # Lifted into its own function so it can be stubbed out during tests. - self._prep_wrapped_messages(client_info) + # TODO(busunkim): These two class methods are in the base transport + # to avoid duplicating code across the transport classes. These functions + # should be deleted once the minimum required versions of google-api-core + # and google-auth are increased. + + # TODO: Remove this function once google-auth >= 1.25.0 is required + @classmethod + def _get_scopes_kwargs( + cls, host: str, scopes: Optional[Sequence[str]] + ) -> Dict[str, Optional[Sequence[str]]]: + """Returns scopes kwargs to pass to google-auth methods depending on the google-auth version""" + + scopes_kwargs = {} + + if _GOOGLE_AUTH_VERSION and ( + packaging.version.parse(_GOOGLE_AUTH_VERSION) + >= packaging.version.parse("1.25.0") + ): + scopes_kwargs = {"scopes": scopes, "default_scopes": cls.AUTH_SCOPES} + else: + scopes_kwargs = {"scopes": scopes or cls.AUTH_SCOPES} + + return scopes_kwargs + + # TODO: Remove this function once google-api-core >= 1.26.0 is required + @classmethod + def _get_self_signed_jwt_kwargs( + cls, host: str, scopes: Optional[Sequence[str]] + ) -> Dict[str, Union[Optional[Sequence[str]], str]]: + """Returns kwargs to pass to grpc_helpers.create_channel depending on the google-api-core version""" + + self_signed_jwt_kwargs: Dict[str, Union[Optional[Sequence[str]], str]] = {} + + if _API_CORE_VERSION and ( + packaging.version.parse(_API_CORE_VERSION) + >= packaging.version.parse("1.26.0") + ): + self_signed_jwt_kwargs["default_scopes"] = cls.AUTH_SCOPES + self_signed_jwt_kwargs["scopes"] = scopes + self_signed_jwt_kwargs["default_host"] = cls.DEFAULT_HOST + else: + self_signed_jwt_kwargs["scopes"] = scopes or cls.AUTH_SCOPES + + return self_signed_jwt_kwargs def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. @@ -118,8 +178,10 @@ def _prep_wrapped_messages(self, client_info): maximum=10.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), + deadline=20.0, ), default_timeout=20.0, client_info=client_info, @@ -131,8 +193,10 @@ def _prep_wrapped_messages(self, client_info): maximum=10.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), + deadline=20.0, ), default_timeout=20.0, client_info=client_info, @@ -150,8 +214,10 @@ def _prep_wrapped_messages(self, client_info): maximum=10.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), + deadline=20.0, ), default_timeout=20.0, client_info=client_info, @@ -172,8 +238,10 @@ def _prep_wrapped_messages(self, client_info): maximum=10.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), + deadline=20.0, ), default_timeout=20.0, client_info=client_info, @@ -188,8 +256,10 @@ def _prep_wrapped_messages(self, client_info): maximum=10.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), + deadline=20.0, ), default_timeout=20.0, client_info=client_info, @@ -201,8 +271,10 @@ def _prep_wrapped_messages(self, client_info): maximum=10.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), + deadline=20.0, ), default_timeout=20.0, client_info=client_info, @@ -214,8 +286,10 @@ def _prep_wrapped_messages(self, client_info): maximum=10.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), + deadline=20.0, ), default_timeout=20.0, client_info=client_info, @@ -230,8 +304,10 @@ def _prep_wrapped_messages(self, client_info): maximum=10.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), + deadline=20.0, ), default_timeout=20.0, client_info=client_info, @@ -244,104 +320,97 @@ def _prep_wrapped_messages(self, client_info): @property def list_queues( self, - ) -> typing.Callable[ + ) -> Callable[ [cloudtasks.ListQueuesRequest], - typing.Union[ - cloudtasks.ListQueuesResponse, - typing.Awaitable[cloudtasks.ListQueuesResponse], - ], + Union[cloudtasks.ListQueuesResponse, Awaitable[cloudtasks.ListQueuesResponse]], ]: raise NotImplementedError() @property def get_queue( self, - ) -> typing.Callable[ - [cloudtasks.GetQueueRequest], - typing.Union[queue.Queue, typing.Awaitable[queue.Queue]], + ) -> Callable[ + [cloudtasks.GetQueueRequest], Union[queue.Queue, Awaitable[queue.Queue]] ]: raise NotImplementedError() @property def create_queue( self, - ) -> typing.Callable[ + ) -> Callable[ [cloudtasks.CreateQueueRequest], - typing.Union[gct_queue.Queue, typing.Awaitable[gct_queue.Queue]], + Union[gct_queue.Queue, Awaitable[gct_queue.Queue]], ]: raise NotImplementedError() @property def update_queue( self, - ) -> typing.Callable[ + ) -> Callable[ [cloudtasks.UpdateQueueRequest], - typing.Union[gct_queue.Queue, typing.Awaitable[gct_queue.Queue]], + Union[gct_queue.Queue, Awaitable[gct_queue.Queue]], ]: raise NotImplementedError() @property def delete_queue( self, - ) -> typing.Callable[ + ) -> Callable[ [cloudtasks.DeleteQueueRequest], - typing.Union[empty.Empty, typing.Awaitable[empty.Empty]], + Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]], ]: raise NotImplementedError() @property def purge_queue( self, - ) -> typing.Callable[ - [cloudtasks.PurgeQueueRequest], - typing.Union[queue.Queue, typing.Awaitable[queue.Queue]], + ) -> Callable[ + [cloudtasks.PurgeQueueRequest], Union[queue.Queue, Awaitable[queue.Queue]] ]: raise NotImplementedError() @property def pause_queue( self, - ) -> typing.Callable[ - [cloudtasks.PauseQueueRequest], - typing.Union[queue.Queue, typing.Awaitable[queue.Queue]], + ) -> Callable[ + [cloudtasks.PauseQueueRequest], Union[queue.Queue, Awaitable[queue.Queue]] ]: raise NotImplementedError() @property def resume_queue( self, - ) -> typing.Callable[ - [cloudtasks.ResumeQueueRequest], - typing.Union[queue.Queue, typing.Awaitable[queue.Queue]], + ) -> Callable[ + [cloudtasks.ResumeQueueRequest], Union[queue.Queue, Awaitable[queue.Queue]] ]: 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 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 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() @@ -349,48 +418,39 @@ def test_iam_permissions( @property def list_tasks( self, - ) -> typing.Callable[ + ) -> Callable[ [cloudtasks.ListTasksRequest], - typing.Union[ - cloudtasks.ListTasksResponse, typing.Awaitable[cloudtasks.ListTasksResponse] - ], + Union[cloudtasks.ListTasksResponse, Awaitable[cloudtasks.ListTasksResponse]], ]: raise NotImplementedError() @property def get_task( self, - ) -> typing.Callable[ - [cloudtasks.GetTaskRequest], - typing.Union[task.Task, typing.Awaitable[task.Task]], - ]: + ) -> Callable[[cloudtasks.GetTaskRequest], Union[task.Task, Awaitable[task.Task]]]: raise NotImplementedError() @property def create_task( self, - ) -> typing.Callable[ - [cloudtasks.CreateTaskRequest], - typing.Union[gct_task.Task, typing.Awaitable[gct_task.Task]], + ) -> Callable[ + [cloudtasks.CreateTaskRequest], Union[gct_task.Task, Awaitable[gct_task.Task]] ]: raise NotImplementedError() @property def delete_task( self, - ) -> typing.Callable[ + ) -> Callable[ [cloudtasks.DeleteTaskRequest], - typing.Union[empty.Empty, typing.Awaitable[empty.Empty]], + Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]], ]: raise NotImplementedError() @property def run_task( self, - ) -> typing.Callable[ - [cloudtasks.RunTaskRequest], - typing.Union[task.Task, typing.Awaitable[task.Task]], - ]: + ) -> Callable[[cloudtasks.RunTaskRequest], Union[task.Task, Awaitable[task.Task]]]: raise NotImplementedError() diff --git a/google/cloud/tasks_v2beta3/services/cloud_tasks/transports/grpc.py b/google/cloud/tasks_v2beta3/services/cloud_tasks/transports/grpc.py index fe4b8a2b..8437327f 100644 --- a/google/cloud/tasks_v2beta3/services/cloud_tasks/transports/grpc.py +++ b/google/cloud/tasks_v2beta3/services/cloud_tasks/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,14 +13,13 @@ # 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 @@ -31,10 +29,9 @@ from google.cloud.tasks_v2beta3.types import queue as gct_queue from google.cloud.tasks_v2beta3.types import task from google.cloud.tasks_v2beta3.types import task as gct_task -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 .base import CloudTasksTransport, DEFAULT_CLIENT_INFO @@ -58,7 +55,7 @@ def __init__( self, *, host: str = "cloudtasks.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Sequence[str] = None, channel: grpc.Channel = None, @@ -72,7 +69,8 @@ def __init__( """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + host (Optional[str]): + The hostname to connect to. credentials (Optional[google.auth.credentials.Credentials]): The authorization credentials to attach to requests. These credentials identify the application to the service; if none @@ -114,7 +112,9 @@ def __init__( 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) @@ -122,70 +122,50 @@ def __init__( warnings.warn("client_cert_source is deprecated", DeprecationWarning) if channel: - # Sanity check: Ensure that channel and credentials are not both - # provided. + # 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 - elif api_mtls_endpoint: - host = ( - api_mtls_endpoint - if ":" in api_mtls_endpoint - else api_mtls_endpoint + ":443" - ) - if credentials is None: - credentials, _ = auth.default( - scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id - ) - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - ssl_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - ssl_credentials = SslCredentials().ssl_credentials - - # create a new channel. The provided one is ignored. - self._grpc_channel = type(self).create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - ssl_credentials=ssl_credentials, - scopes=scopes or self.AUTH_SCOPES, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - self._ssl_channel_credentials = ssl_credentials else: - host = host if ":" in host else host + ":443" + 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 - if credentials is None: - credentials, _ = auth.default( - scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id - ) + 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 + ) - 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, + ) - # create a new channel. The provided one is ignored. + if not self._grpc_channel: self._grpc_channel = type(self).create_channel( - host, - credentials=credentials, + self._host, + credentials=self._credentials, credentials_file=credentials_file, + scopes=self._scopes, ssl_credentials=self._ssl_channel_credentials, - scopes=scopes or self.AUTH_SCOPES, quota_project_id=quota_project_id, options=[ ("grpc.max_send_message_length", -1), @@ -193,23 +173,14 @@ def __init__( ], ) - self._stubs = {} # type: Dict[str, Callable] - - # Run the base constructor. - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes or self.AUTH_SCOPES, - quota_project_id=quota_project_id, - client_info=client_info, - ) + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) @classmethod def create_channel( cls, host: str = "cloudtasks.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, @@ -217,7 +188,7 @@ def create_channel( ) -> grpc.Channel: """Create and return a gRPC channel object. Args: - address (Optional[str]): The host for the channel to use. + 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 @@ -240,13 +211,15 @@ def create_channel( google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` and ``credentials_file`` are passed. """ - scopes = scopes or cls.AUTH_SCOPES + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + return grpc_helpers.create_channel( host, credentials=credentials, credentials_file=credentials_file, - scopes=scopes, quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, **kwargs, ) @@ -383,7 +356,9 @@ def update_queue( return self._stubs["update_queue"] @property - def delete_queue(self) -> Callable[[cloudtasks.DeleteQueueRequest], empty.Empty]: + def delete_queue( + self, + ) -> Callable[[cloudtasks.DeleteQueueRequest], empty_pb2.Empty]: r"""Return a callable for the delete queue method over gRPC. Deletes a queue. @@ -413,7 +388,7 @@ def delete_queue(self) -> Callable[[cloudtasks.DeleteQueueRequest], empty.Empty] self._stubs["delete_queue"] = self.grpc_channel.unary_unary( "/google.cloud.tasks.v2beta3.CloudTasks/DeleteQueue", request_serializer=cloudtasks.DeleteQueueRequest.serialize, - response_deserializer=empty.Empty.FromString, + response_deserializer=empty_pb2.Empty.FromString, ) return self._stubs["delete_queue"] @@ -518,7 +493,7 @@ def resume_queue(self) -> Callable[[cloudtasks.ResumeQueueRequest], queue.Queue] @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 access control policy for a @@ -544,15 +519,15 @@ def get_iam_policy( if "get_iam_policy" not in self._stubs: self._stubs["get_iam_policy"] = self.grpc_channel.unary_unary( "/google.cloud.tasks.v2beta3.CloudTasks/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"] @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 access control policy for a @@ -582,8 +557,8 @@ def set_iam_policy( if "set_iam_policy" not in self._stubs: self._stubs["set_iam_policy"] = self.grpc_channel.unary_unary( "/google.cloud.tasks.v2beta3.CloudTasks/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"] @@ -591,7 +566,8 @@ def set_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. @@ -618,8 +594,8 @@ def test_iam_permissions( if "test_iam_permissions" not in self._stubs: self._stubs["test_iam_permissions"] = self.grpc_channel.unary_unary( "/google.cloud.tasks.v2beta3.CloudTasks/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"] @@ -712,7 +688,7 @@ def create_task(self) -> Callable[[cloudtasks.CreateTaskRequest], gct_task.Task] return self._stubs["create_task"] @property - def delete_task(self) -> Callable[[cloudtasks.DeleteTaskRequest], empty.Empty]: + def delete_task(self) -> Callable[[cloudtasks.DeleteTaskRequest], empty_pb2.Empty]: r"""Return a callable for the delete task method over gRPC. Deletes a task. @@ -734,7 +710,7 @@ def delete_task(self) -> Callable[[cloudtasks.DeleteTaskRequest], empty.Empty]: self._stubs["delete_task"] = self.grpc_channel.unary_unary( "/google.cloud.tasks.v2beta3.CloudTasks/DeleteTask", request_serializer=cloudtasks.DeleteTaskRequest.serialize, - response_deserializer=empty.Empty.FromString, + response_deserializer=empty_pb2.Empty.FromString, ) return self._stubs["delete_task"] diff --git a/google/cloud/tasks_v2beta3/services/cloud_tasks/transports/grpc_asyncio.py b/google/cloud/tasks_v2beta3/services/cloud_tasks/transports/grpc_asyncio.py index 8b5c85db..cc327a61 100644 --- a/google/cloud/tasks_v2beta3/services/cloud_tasks/transports/grpc_asyncio.py +++ b/google/cloud/tasks_v2beta3/services/cloud_tasks/transports/grpc_asyncio.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,15 +13,14 @@ # 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 @@ -32,10 +30,9 @@ from google.cloud.tasks_v2beta3.types import queue as gct_queue from google.cloud.tasks_v2beta3.types import task from google.cloud.tasks_v2beta3.types import task as gct_task -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 .base import CloudTasksTransport, DEFAULT_CLIENT_INFO from .grpc import CloudTasksGrpcTransport @@ -61,7 +58,7 @@ class CloudTasksGrpcAsyncIOTransport(CloudTasksTransport): def create_channel( cls, host: str = "cloudtasks.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, @@ -69,7 +66,7 @@ def create_channel( ) -> aio.Channel: """Create and return a gRPC AsyncIO channel object. Args: - address (Optional[str]): The host for the channel to use. + 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 @@ -88,13 +85,15 @@ def create_channel( Returns: aio.Channel: A gRPC AsyncIO channel object. """ - scopes = scopes or cls.AUTH_SCOPES + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + return grpc_helpers_async.create_channel( host, credentials=credentials, credentials_file=credentials_file, - scopes=scopes, quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, **kwargs, ) @@ -102,7 +101,7 @@ def __init__( self, *, host: str = "cloudtasks.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, @@ -116,7 +115,8 @@ def __init__( """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + host (Optional[str]): + The hostname to connect to. credentials (Optional[google.auth.credentials.Credentials]): The authorization credentials to attach to requests. These credentials identify the application to the service; if none @@ -147,10 +147,10 @@ def __init__( 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 + 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: @@ -159,7 +159,9 @@ def __init__( 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) @@ -167,70 +169,49 @@ def __init__( warnings.warn("client_cert_source is deprecated", DeprecationWarning) if channel: - # Sanity check: Ensure that channel and credentials are not both - # provided. + # 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 - elif api_mtls_endpoint: - host = ( - api_mtls_endpoint - if ":" in api_mtls_endpoint - else api_mtls_endpoint + ":443" - ) - - if credentials is None: - credentials, _ = auth.default( - scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id - ) - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - ssl_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - ssl_credentials = SslCredentials().ssl_credentials - - # create a new channel. The provided one is ignored. - self._grpc_channel = type(self).create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - ssl_credentials=ssl_credentials, - scopes=scopes or self.AUTH_SCOPES, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - self._ssl_channel_credentials = ssl_credentials else: - host = host if ":" in host else host + ":443" + 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 - if credentials is None: - credentials, _ = auth.default( - scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id - ) + 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 + ) - 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, + ) - # create a new channel. The provided one is ignored. + if not self._grpc_channel: self._grpc_channel = type(self).create_channel( - host, - credentials=credentials, + self._host, + credentials=self._credentials, credentials_file=credentials_file, + scopes=self._scopes, ssl_credentials=self._ssl_channel_credentials, - scopes=scopes or self.AUTH_SCOPES, quota_project_id=quota_project_id, options=[ ("grpc.max_send_message_length", -1), @@ -238,17 +219,8 @@ def __init__( ], ) - # Run the base constructor. - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes or self.AUTH_SCOPES, - quota_project_id=quota_project_id, - client_info=client_info, - ) - - self._stubs = {} + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) @property def grpc_channel(self) -> aio.Channel: @@ -393,7 +365,7 @@ def update_queue( @property def delete_queue( self, - ) -> Callable[[cloudtasks.DeleteQueueRequest], Awaitable[empty.Empty]]: + ) -> Callable[[cloudtasks.DeleteQueueRequest], Awaitable[empty_pb2.Empty]]: r"""Return a callable for the delete queue method over gRPC. Deletes a queue. @@ -423,7 +395,7 @@ def delete_queue( self._stubs["delete_queue"] = self.grpc_channel.unary_unary( "/google.cloud.tasks.v2beta3.CloudTasks/DeleteQueue", request_serializer=cloudtasks.DeleteQueueRequest.serialize, - response_deserializer=empty.Empty.FromString, + response_deserializer=empty_pb2.Empty.FromString, ) return self._stubs["delete_queue"] @@ -534,7 +506,7 @@ def resume_queue( @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 access control policy for a @@ -560,15 +532,15 @@ def get_iam_policy( if "get_iam_policy" not in self._stubs: self._stubs["get_iam_policy"] = self.grpc_channel.unary_unary( "/google.cloud.tasks.v2beta3.CloudTasks/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"] @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 access control policy for a @@ -598,8 +570,8 @@ def set_iam_policy( if "set_iam_policy" not in self._stubs: self._stubs["set_iam_policy"] = self.grpc_channel.unary_unary( "/google.cloud.tasks.v2beta3.CloudTasks/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"] @@ -607,8 +579,8 @@ def set_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. @@ -635,8 +607,8 @@ def test_iam_permissions( if "test_iam_permissions" not in self._stubs: self._stubs["test_iam_permissions"] = self.grpc_channel.unary_unary( "/google.cloud.tasks.v2beta3.CloudTasks/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"] @@ -735,7 +707,7 @@ def create_task( @property def delete_task( self, - ) -> Callable[[cloudtasks.DeleteTaskRequest], Awaitable[empty.Empty]]: + ) -> Callable[[cloudtasks.DeleteTaskRequest], Awaitable[empty_pb2.Empty]]: r"""Return a callable for the delete task method over gRPC. Deletes a task. @@ -757,7 +729,7 @@ def delete_task( self._stubs["delete_task"] = self.grpc_channel.unary_unary( "/google.cloud.tasks.v2beta3.CloudTasks/DeleteTask", request_serializer=cloudtasks.DeleteTaskRequest.serialize, - response_deserializer=empty.Empty.FromString, + response_deserializer=empty_pb2.Empty.FromString, ) return self._stubs["delete_task"] diff --git a/google/cloud/tasks_v2beta3/types/__init__.py b/google/cloud/tasks_v2beta3/types/__init__.py index 1e26bdf8..d96563f4 100644 --- a/google/cloud/tasks_v2beta3/types/__init__.py +++ b/google/cloud/tasks_v2beta3/types/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,75 +13,74 @@ # See the License for the specific language governing permissions and # limitations under the License. # - +from .cloudtasks import ( + CreateQueueRequest, + CreateTaskRequest, + DeleteQueueRequest, + DeleteTaskRequest, + GetQueueRequest, + GetTaskRequest, + ListQueuesRequest, + ListQueuesResponse, + ListTasksRequest, + ListTasksResponse, + PauseQueueRequest, + PurgeQueueRequest, + ResumeQueueRequest, + RunTaskRequest, + UpdateQueueRequest, +) +from .queue import ( + Queue, + QueueStats, + RateLimits, + RetryConfig, + StackdriverLoggingConfig, +) from .target import ( - PullMessage, - HttpRequest, AppEngineHttpQueue, AppEngineHttpRequest, AppEngineRouting, + HttpRequest, OAuthToken, OidcToken, + PullMessage, HttpMethod, ) -from .queue import ( - Queue, - RateLimits, - RetryConfig, - StackdriverLoggingConfig, - QueueStats, -) from .task import ( - Task, Attempt, -) -from .cloudtasks import ( - ListQueuesRequest, - ListQueuesResponse, - GetQueueRequest, - CreateQueueRequest, - UpdateQueueRequest, - DeleteQueueRequest, - PurgeQueueRequest, - PauseQueueRequest, - ResumeQueueRequest, - ListTasksRequest, - ListTasksResponse, - GetTaskRequest, - CreateTaskRequest, - DeleteTaskRequest, - RunTaskRequest, + Task, ) __all__ = ( - "PullMessage", - "HttpRequest", + "CreateQueueRequest", + "CreateTaskRequest", + "DeleteQueueRequest", + "DeleteTaskRequest", + "GetQueueRequest", + "GetTaskRequest", + "ListQueuesRequest", + "ListQueuesResponse", + "ListTasksRequest", + "ListTasksResponse", + "PauseQueueRequest", + "PurgeQueueRequest", + "ResumeQueueRequest", + "RunTaskRequest", + "UpdateQueueRequest", + "Queue", + "QueueStats", + "RateLimits", + "RetryConfig", + "StackdriverLoggingConfig", "AppEngineHttpQueue", "AppEngineHttpRequest", "AppEngineRouting", + "HttpRequest", "OAuthToken", "OidcToken", + "PullMessage", "HttpMethod", - "Queue", - "RateLimits", - "RetryConfig", - "StackdriverLoggingConfig", - "QueueStats", - "Task", "Attempt", - "ListQueuesRequest", - "ListQueuesResponse", - "GetQueueRequest", - "CreateQueueRequest", - "UpdateQueueRequest", - "DeleteQueueRequest", - "PurgeQueueRequest", - "PauseQueueRequest", - "ResumeQueueRequest", - "ListTasksRequest", - "ListTasksResponse", - "GetTaskRequest", - "CreateTaskRequest", - "DeleteTaskRequest", - "RunTaskRequest", + "Task", ) diff --git a/google/cloud/tasks_v2beta3/types/cloudtasks.py b/google/cloud/tasks_v2beta3/types/cloudtasks.py index ec659ea1..6b65776c 100644 --- a/google/cloud/tasks_v2beta3/types/cloudtasks.py +++ b/google/cloud/tasks_v2beta3/types/cloudtasks.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.cloud.tasks_v2beta3.types import queue as gct_queue from google.cloud.tasks_v2beta3.types import task as gct_task -from google.protobuf import field_mask_pb2 as field_mask # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore __protobuf__ = proto.module( @@ -92,15 +89,11 @@ class ListQueuesRequest(proto.Message): returned only if it was explicitly specified in the mask. """ - parent = proto.Field(proto.STRING, number=1) - - filter = proto.Field(proto.STRING, number=2) - - page_size = proto.Field(proto.INT32, number=3) - - page_token = proto.Field(proto.STRING, number=4) - - read_mask = proto.Field(proto.MESSAGE, number=5, message=field_mask.FieldMask,) + parent = proto.Field(proto.STRING, number=1,) + filter = proto.Field(proto.STRING, number=2,) + page_size = proto.Field(proto.INT32, number=3,) + page_token = proto.Field(proto.STRING, number=4,) + read_mask = proto.Field(proto.MESSAGE, number=5, message=field_mask_pb2.FieldMask,) class ListQueuesResponse(proto.Message): @@ -128,8 +121,7 @@ def raw_page(self): return self queues = proto.RepeatedField(proto.MESSAGE, number=1, message=gct_queue.Queue,) - - next_page_token = proto.Field(proto.STRING, number=2) + next_page_token = proto.Field(proto.STRING, number=2,) class GetQueueRequest(proto.Message): @@ -147,9 +139,8 @@ class GetQueueRequest(proto.Message): returned only if it was explicitly specified in the mask. """ - name = proto.Field(proto.STRING, number=1) - - read_mask = proto.Field(proto.MESSAGE, number=2, message=field_mask.FieldMask,) + name = proto.Field(proto.STRING, number=1,) + read_mask = proto.Field(proto.MESSAGE, number=2, message=field_mask_pb2.FieldMask,) class CreateQueueRequest(proto.Message): @@ -172,8 +163,7 @@ class CreateQueueRequest(proto.Message): be the same as an existing queue. """ - parent = proto.Field(proto.STRING, number=1) - + parent = proto.Field(proto.STRING, number=1,) queue = proto.Field(proto.MESSAGE, number=2, message=gct_queue.Queue,) @@ -199,8 +189,9 @@ class UpdateQueueRequest(proto.Message): """ queue = proto.Field(proto.MESSAGE, number=1, message=gct_queue.Queue,) - - 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 DeleteQueueRequest(proto.Message): @@ -213,7 +204,7 @@ class DeleteQueueRequest(proto.Message): ``projects/PROJECT_ID/locations/LOCATION_ID/queues/QUEUE_ID`` """ - name = proto.Field(proto.STRING, number=1) + name = proto.Field(proto.STRING, number=1,) class PurgeQueueRequest(proto.Message): @@ -226,7 +217,7 @@ class PurgeQueueRequest(proto.Message): ``projects/PROJECT_ID/location/LOCATION_ID/queues/QUEUE_ID`` """ - name = proto.Field(proto.STRING, number=1) + name = proto.Field(proto.STRING, number=1,) class PauseQueueRequest(proto.Message): @@ -239,7 +230,7 @@ class PauseQueueRequest(proto.Message): ``projects/PROJECT_ID/location/LOCATION_ID/queues/QUEUE_ID`` """ - name = proto.Field(proto.STRING, number=1) + name = proto.Field(proto.STRING, number=1,) class ResumeQueueRequest(proto.Message): @@ -252,7 +243,7 @@ class ResumeQueueRequest(proto.Message): ``projects/PROJECT_ID/location/LOCATION_ID/queues/QUEUE_ID`` """ - name = proto.Field(proto.STRING, number=1) + name = proto.Field(proto.STRING, number=1,) class ListTasksRequest(proto.Message): @@ -303,13 +294,10 @@ class ListTasksRequest(proto.Message): The page token is valid for only 2 hours. """ - parent = proto.Field(proto.STRING, number=1) - + parent = proto.Field(proto.STRING, number=1,) response_view = proto.Field(proto.ENUM, number=2, enum=gct_task.Task.View,) - - 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 ListTasksResponse(proto.Message): @@ -335,8 +323,7 @@ def raw_page(self): return self tasks = proto.RepeatedField(proto.MESSAGE, number=1, message=gct_task.Task,) - - next_page_token = proto.Field(proto.STRING, number=2) + next_page_token = proto.Field(proto.STRING, number=2,) class GetTaskRequest(proto.Message): @@ -365,8 +352,7 @@ class GetTaskRequest(proto.Message): [Task][google.cloud.tasks.v2beta3.Task] resource. """ - name = proto.Field(proto.STRING, number=1) - + name = proto.Field(proto.STRING, number=1,) response_view = proto.Field(proto.ENUM, number=2, enum=gct_task.Task.View,) @@ -439,10 +425,8 @@ class CreateTaskRequest(proto.Message): [Task][google.cloud.tasks.v2beta3.Task] resource. """ - parent = proto.Field(proto.STRING, number=1) - + parent = proto.Field(proto.STRING, number=1,) task = proto.Field(proto.MESSAGE, number=2, message=gct_task.Task,) - response_view = proto.Field(proto.ENUM, number=3, enum=gct_task.Task.View,) @@ -456,7 +440,7 @@ class DeleteTaskRequest(proto.Message): ``projects/PROJECT_ID/locations/LOCATION_ID/queues/QUEUE_ID/tasks/TASK_ID`` """ - name = proto.Field(proto.STRING, number=1) + name = proto.Field(proto.STRING, number=1,) class RunTaskRequest(proto.Message): @@ -485,8 +469,7 @@ class RunTaskRequest(proto.Message): [Task][google.cloud.tasks.v2beta3.Task] resource. """ - name = proto.Field(proto.STRING, number=1) - + name = proto.Field(proto.STRING, number=1,) response_view = proto.Field(proto.ENUM, number=2, enum=gct_task.Task.View,) diff --git a/google/cloud/tasks_v2beta3/types/queue.py b/google/cloud/tasks_v2beta3/types/queue.py index 13e9fc82..feff4435 100644 --- a/google/cloud/tasks_v2beta3/types/queue.py +++ b/google/cloud/tasks_v2beta3/types/queue.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.cloud.tasks_v2beta3.types import target -from google.protobuf import duration_pb2 as duration # type: ignore -from google.protobuf import timestamp_pb2 as timestamp # type: ignore +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore __protobuf__ = proto.module( @@ -120,7 +117,7 @@ class Queue(proto.Message): state (google.cloud.tasks_v2beta3.types.Queue.State): Output only. The state of the queue. - ``state`` can only be changed by called + ``state`` can only be changed by calling [PauseQueue][google.cloud.tasks.v2beta3.CloudTasks.PauseQueue], [ResumeQueue][google.cloud.tasks.v2beta3.CloudTasks.ResumeQueue], or uploading @@ -199,30 +196,20 @@ class Type(proto.Enum): PULL = 1 PUSH = 2 - name = proto.Field(proto.STRING, number=1) - + name = proto.Field(proto.STRING, number=1,) app_engine_http_queue = proto.Field( proto.MESSAGE, number=3, oneof="queue_type", message=target.AppEngineHttpQueue, ) - rate_limits = proto.Field(proto.MESSAGE, number=4, message="RateLimits",) - retry_config = proto.Field(proto.MESSAGE, number=5, message="RetryConfig",) - state = proto.Field(proto.ENUM, number=6, enum=State,) - - purge_time = proto.Field(proto.MESSAGE, number=7, message=timestamp.Timestamp,) - - task_ttl = proto.Field(proto.MESSAGE, number=8, message=duration.Duration,) - - tombstone_ttl = proto.Field(proto.MESSAGE, number=9, message=duration.Duration,) - + purge_time = proto.Field(proto.MESSAGE, number=7, message=timestamp_pb2.Timestamp,) + task_ttl = proto.Field(proto.MESSAGE, number=8, message=duration_pb2.Duration,) + tombstone_ttl = proto.Field(proto.MESSAGE, number=9, message=duration_pb2.Duration,) stackdriver_logging_config = proto.Field( proto.MESSAGE, number=10, message="StackdriverLoggingConfig", ) - type_ = proto.Field(proto.ENUM, number=11, enum=Type,) - stats = proto.Field(proto.MESSAGE, number=12, message="QueueStats",) @@ -306,11 +293,9 @@ class RateLimits(proto.Message): queue.yaml/xml `__. """ - max_dispatches_per_second = proto.Field(proto.DOUBLE, number=1) - - max_burst_size = proto.Field(proto.INT32, number=2) - - max_concurrent_dispatches = proto.Field(proto.INT32, number=3) + max_dispatches_per_second = proto.Field(proto.DOUBLE, number=1,) + max_burst_size = proto.Field(proto.INT32, number=2,) + max_concurrent_dispatches = proto.Field(proto.INT32, number=3,) class RetryConfig(proto.Message): @@ -421,17 +406,13 @@ class RetryConfig(proto.Message): queue.yaml/xml `__. """ - max_attempts = proto.Field(proto.INT32, number=1) - + max_attempts = proto.Field(proto.INT32, number=1,) max_retry_duration = proto.Field( - proto.MESSAGE, number=2, message=duration.Duration, + proto.MESSAGE, number=2, message=duration_pb2.Duration, ) - - min_backoff = proto.Field(proto.MESSAGE, number=3, message=duration.Duration,) - - max_backoff = proto.Field(proto.MESSAGE, number=4, message=duration.Duration,) - - max_doublings = proto.Field(proto.INT32, number=5) + min_backoff = proto.Field(proto.MESSAGE, number=3, message=duration_pb2.Duration,) + max_backoff = proto.Field(proto.MESSAGE, number=4, message=duration_pb2.Duration,) + max_doublings = proto.Field(proto.INT32, number=5,) class StackdriverLoggingConfig(proto.Message): @@ -447,12 +428,11 @@ class StackdriverLoggingConfig(proto.Message): 0.0 is the default and means that no operations are logged. """ - sampling_ratio = proto.Field(proto.DOUBLE, number=1) + sampling_ratio = proto.Field(proto.DOUBLE, number=1,) class QueueStats(proto.Message): r"""Statistics for a queue. - Attributes: tasks_count (int): Output only. An estimation of the number of @@ -483,17 +463,13 @@ class QueueStats(proto.Message): tasks in the queue are targeting. """ - tasks_count = proto.Field(proto.INT64, number=1) - + tasks_count = proto.Field(proto.INT64, number=1,) oldest_estimated_arrival_time = proto.Field( - proto.MESSAGE, number=2, message=timestamp.Timestamp, + proto.MESSAGE, number=2, message=timestamp_pb2.Timestamp, ) - - executed_last_minute_count = proto.Field(proto.INT64, number=3) - - concurrent_dispatches_count = proto.Field(proto.INT64, number=4) - - effective_execution_rate = proto.Field(proto.DOUBLE, number=5) + executed_last_minute_count = proto.Field(proto.INT64, number=3,) + concurrent_dispatches_count = proto.Field(proto.INT64, number=4,) + effective_execution_rate = proto.Field(proto.DOUBLE, number=5,) __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/tasks_v2beta3/types/target.py b/google/cloud/tasks_v2beta3/types/target.py index 938f6413..e75ef387 100644 --- a/google/cloud/tasks_v2beta3/types/target.py +++ b/google/cloud/tasks_v2beta3/types/target.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 @@ -73,9 +71,8 @@ class PullMessage(proto.Message): returned by Cloud Tasks. """ - payload = proto.Field(proto.BYTES, number=1) - - tag = proto.Field(proto.STRING, number=2) + payload = proto.Field(proto.BYTES, number=1,) + tag = proto.Field(proto.STRING, number=2,) class HttpRequest(proto.Message): @@ -191,18 +188,13 @@ class HttpRequest(proto.Message): to validate the token yourself. """ - url = proto.Field(proto.STRING, number=1) - + url = proto.Field(proto.STRING, number=1,) http_method = proto.Field(proto.ENUM, number=2, enum="HttpMethod",) - - headers = proto.MapField(proto.STRING, proto.STRING, number=3) - - body = proto.Field(proto.BYTES, number=4) - + headers = proto.MapField(proto.STRING, proto.STRING, number=3,) + body = proto.Field(proto.BYTES, number=4,) oauth_token = proto.Field( proto.MESSAGE, number=5, oneof="authorization_header", message="OAuthToken", ) - oidc_token = proto.Field( proto.MESSAGE, number=6, oneof="authorization_header", message="OidcToken", ) @@ -397,16 +389,12 @@ class AppEngineHttpRequest(proto.Message): """ http_method = proto.Field(proto.ENUM, number=1, enum="HttpMethod",) - app_engine_routing = proto.Field( proto.MESSAGE, number=2, message="AppEngineRouting", ) - - relative_uri = proto.Field(proto.STRING, number=3) - - headers = proto.MapField(proto.STRING, proto.STRING, number=4) - - body = proto.Field(proto.BYTES, number=5) + relative_uri = proto.Field(proto.STRING, number=3,) + headers = proto.MapField(proto.STRING, proto.STRING, number=4,) + body = proto.Field(proto.BYTES, number=5,) class AppEngineRouting(proto.Message): @@ -505,13 +493,10 @@ class AppEngineRouting(proto.Message): Routed `__. """ - service = proto.Field(proto.STRING, number=1) - - version = proto.Field(proto.STRING, number=2) - - instance = proto.Field(proto.STRING, number=3) - - host = proto.Field(proto.STRING, number=4) + service = proto.Field(proto.STRING, number=1,) + version = proto.Field(proto.STRING, number=2,) + instance = proto.Field(proto.STRING, number=3,) + host = proto.Field(proto.STRING, number=4,) class OAuthToken(proto.Message): @@ -535,9 +520,8 @@ class OAuthToken(proto.Message): will be used. """ - service_account_email = proto.Field(proto.STRING, number=1) - - scope = proto.Field(proto.STRING, number=2) + service_account_email = proto.Field(proto.STRING, number=1,) + scope = proto.Field(proto.STRING, number=2,) class OidcToken(proto.Message): @@ -561,9 +545,8 @@ class OidcToken(proto.Message): target will be used. """ - service_account_email = proto.Field(proto.STRING, number=1) - - audience = proto.Field(proto.STRING, number=2) + service_account_email = proto.Field(proto.STRING, number=1,) + audience = proto.Field(proto.STRING, number=2,) __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/tasks_v2beta3/types/task.py b/google/cloud/tasks_v2beta3/types/task.py index 1ec2700e..4f26082b 100644 --- a/google/cloud/tasks_v2beta3/types/task.py +++ b/google/cloud/tasks_v2beta3/types/task.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,14 +13,12 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import proto # type: ignore - from google.cloud.tasks_v2beta3.types import target -from google.protobuf import duration_pb2 as duration # type: ignore -from google.protobuf import timestamp_pb2 as timestamp # type: ignore -from google.rpc import status_pb2 as status # type: ignore +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from google.rpc import status_pb2 # type: ignore __protobuf__ = proto.module( @@ -31,7 +28,6 @@ class Task(proto.Message): r"""A unit of scheduled work. - Attributes: name (str): Optionally caller-specified in @@ -167,45 +163,35 @@ class View(proto.Enum): BASIC = 1 FULL = 2 - name = proto.Field(proto.STRING, number=1) - + name = proto.Field(proto.STRING, number=1,) app_engine_http_request = proto.Field( proto.MESSAGE, number=3, oneof="payload_type", message=target.AppEngineHttpRequest, ) - http_request = proto.Field( proto.MESSAGE, number=11, oneof="payload_type", message=target.HttpRequest, ) - pull_message = proto.Field( proto.MESSAGE, number=13, oneof="payload_type", message=target.PullMessage, ) - - schedule_time = proto.Field(proto.MESSAGE, number=4, message=timestamp.Timestamp,) - - create_time = proto.Field(proto.MESSAGE, number=5, message=timestamp.Timestamp,) - + schedule_time = proto.Field( + proto.MESSAGE, number=4, message=timestamp_pb2.Timestamp, + ) + create_time = proto.Field(proto.MESSAGE, number=5, message=timestamp_pb2.Timestamp,) dispatch_deadline = proto.Field( - proto.MESSAGE, number=12, message=duration.Duration, + proto.MESSAGE, number=12, message=duration_pb2.Duration, ) - - dispatch_count = proto.Field(proto.INT32, number=6) - - response_count = proto.Field(proto.INT32, number=7) - + dispatch_count = proto.Field(proto.INT32, number=6,) + response_count = proto.Field(proto.INT32, number=7,) first_attempt = proto.Field(proto.MESSAGE, number=8, message="Attempt",) - last_attempt = proto.Field(proto.MESSAGE, number=9, message="Attempt",) - view = proto.Field(proto.ENUM, number=10, enum=View,) class Attempt(proto.Message): r"""The status of a task attempt. - Attributes: schedule_time (google.protobuf.timestamp_pb2.Timestamp): Output only. The time that this attempt was scheduled. @@ -231,13 +217,16 @@ class Attempt(proto.Message): ``response_status`` field is meaningless. """ - schedule_time = proto.Field(proto.MESSAGE, number=1, message=timestamp.Timestamp,) - - dispatch_time = proto.Field(proto.MESSAGE, number=2, message=timestamp.Timestamp,) - - response_time = proto.Field(proto.MESSAGE, number=3, message=timestamp.Timestamp,) - - response_status = proto.Field(proto.MESSAGE, number=4, message=status.Status,) + schedule_time = proto.Field( + proto.MESSAGE, number=1, message=timestamp_pb2.Timestamp, + ) + dispatch_time = proto.Field( + proto.MESSAGE, number=2, message=timestamp_pb2.Timestamp, + ) + response_time = proto.Field( + proto.MESSAGE, number=3, message=timestamp_pb2.Timestamp, + ) + response_status = proto.Field(proto.MESSAGE, number=4, message=status_pb2.Status,) __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/noxfile.py b/noxfile.py index 6e69bfe0..03aa2f58 100644 --- a/noxfile.py +++ b/noxfile.py @@ -18,6 +18,7 @@ from __future__ import absolute_import import os +import pathlib import shutil import nox @@ -30,6 +31,8 @@ SYSTEM_TEST_PYTHON_VERSIONS = ["3.8"] UNIT_TEST_PYTHON_VERSIONS = ["3.6", "3.7", "3.8", "3.9"] +CURRENT_DIRECTORY = pathlib.Path(__file__).parent.absolute() + # 'docfx' is excluded since it only needs to run in 'docs-presubmit' nox.options.sessions = [ "unit", @@ -41,6 +44,9 @@ "docs", ] +# Error if a python version is missing +nox.options.error_on_missing_interpreters = True + @nox.session(python=DEFAULT_PYTHON_VERSION) def lint(session): @@ -56,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, @@ -81,13 +80,15 @@ def lint_setup_py(session): def default(session): # Install all test dependencies, then install this package in-place. - session.install("asyncmock", "pytest-asyncio") - session.install( - "mock", "pytest", "pytest-cov", + constraints_path = str( + CURRENT_DIRECTORY / "testing" / f"constraints-{session.python}.txt" ) + session.install("asyncmock", "pytest-asyncio", "-c", constraints_path) - session.install("-e", ".") + session.install("mock", "pytest", "pytest-cov", "-c", constraints_path) + + session.install("-e", ".", "-c", constraints_path) # Run py.test against the unit tests. session.run( @@ -114,15 +115,18 @@ def unit(session): @nox.session(python=SYSTEM_TEST_PYTHON_VERSIONS) def system(session): """Run the system test suite.""" + constraints_path = str( + CURRENT_DIRECTORY / "testing" / f"constraints-{session.python}.txt" + ) system_test_path = os.path.join("tests", "system.py") system_test_folder_path = os.path.join("tests", "system") # Check the value of `RUN_SYSTEM_TESTS` env var. It defaults to true. if os.environ.get("RUN_SYSTEM_TESTS", "true") == "false": session.skip("RUN_SYSTEM_TESTS is set to false, skipping") - # 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") system_test_exists = os.path.exists(system_test_path) system_test_folder_exists = os.path.exists(system_test_folder_path) @@ -135,10 +139,8 @@ def system(session): # Install all test dependencies, then install this package into the # virtualenv's dist-packages. - session.install( - "mock", "pytest", "google-cloud-testutils", - ) - session.install("-e", ".") + session.install("mock", "pytest", "google-cloud-testutils", "-c", constraints_path) + session.install("-e", ".", "-c", constraints_path) # Run py.test against the system tests. if system_test_exists: @@ -167,7 +169,7 @@ def cover(session): test runs (not system test runs), and then erases coverage data. """ session.install("coverage", "pytest-cov") - session.run("coverage", "report", "--show-missing", "--fail-under=99") + session.run("coverage", "report", "--show-missing", "--fail-under=98") session.run("coverage", "erase") @@ -177,7 +179,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( @@ -199,9 +201,9 @@ def docfx(session): """Build the docfx yaml files for this library.""" session.install("-e", ".") - # sphinx-docfx-yaml supports up to sphinx version 1.5.5. - # https://github.com/docascode/sphinx-docfx-yaml/issues/97 - session.install("sphinx==1.5.5", "alabaster", "recommonmark", "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/synth.py b/owlbot.py similarity index 61% rename from synth.py rename to owlbot.py index 7781cb99..b85eed05 100644 --- a/synth.py +++ b/owlbot.py @@ -21,35 +21,32 @@ logging.basicConfig(level=logging.DEBUG) -gapic = gcp.GAPICBazel() common = gcp.CommonTemplates() -excludes = ["README.rst", "setup.py", "nox*.py", "docs/index.rst"] -# ---------------------------------------------------------------------------- -# Generate tasks GAPIC layer -# ---------------------------------------------------------------------------- -for version in ["v2beta2", "v2beta3", "v2"]: - library = gapic.py_library( - service="tasks", - version=version, - bazel_target=f"//google/cloud/tasks/{version}:tasks-{version}-py", - include_protos=True, +default_version = "v2" + +for library in s.get_staging_dirs(default_version): + # Fix docstring. + s.replace(library / "google/cloud/*/types/target.py", "X-Google-\*", "X-Google-\\*") + s.replace(library / "google/cloud/*/types/target.py", "X-AppEngine-\*", "X-AppEngine-\\*") + + # Comment out broken assertion in unit test + # https://github.com/googleapis/gapic-generator-python/issues/897 + s.replace( + library / "tests/**/test_cloud_tasks.py", + "assert args\[0\]\.lease_duration == duration_pb2\.Duration\(seconds=751\)", + "# assert args[0].lease_duration == duration_pb2.Duration(seconds=751)" + ) + s.replace( + library / "tests/**/test_cloud_tasks.py", + "assert args\[0\].schedule_time == timestamp_pb2\.Timestamp\(seconds=751\)", + "# assert args[0].schedule_time == timestamp_pb2.Timestamp(seconds=751)" ) + excludes = ["README.rst", "setup.py", "nox*.py", "docs/index.rst", "*.tar.gz"] s.copy(library, excludes=excludes) -# Fix docstring. -s.replace("google/cloud/*/types/target.py", "X-Google-\*", "X-Google-\\*") -s.replace("google/cloud/*/types/target.py", "X-AppEngine-\*", "X-AppEngine-\\*") - -# Bug with test_iam_permissions adding permissions twice -# https://github.com/googleapis/gapic-generator-python/issues/778 -s.replace( - "google/cloud/**/client.py", - """\s+if permissions: -\s+request\.permissions\.extend\(permissions\)""", - "", -) +s.remove_staging_dirs() # ---------------------------------------------------------------------------- # Add templated files @@ -57,7 +54,7 @@ templated_files = common.py_library( samples=False, # set to True only if there are samples microgenerator=True, - cov_level=99, + cov_level=98, ) s.move( templated_files, excludes=[".coveragerc"] diff --git a/renovate.json b/renovate.json index 4fa94931..c0489556 100644 --- a/renovate.json +++ b/renovate.json @@ -1,5 +1,9 @@ { "extends": [ "config:base", ":preserveSemverRanges" - ] + ], + "ignorePaths": [".pre-commit-config.yaml"], + "pip_requirements": { + "fileMatch": ["requirements-test.txt", "samples/[\\S/]*constraints.txt", "samples/[\\S/]*constraints-test.txt"] + } } diff --git a/samples/snippets/noxfile.py b/samples/snippets/noxfile.py index 97bf7da8..5ff9e1db 100644 --- a/samples/snippets/noxfile.py +++ b/samples/snippets/noxfile.py @@ -50,7 +50,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': {}, @@ -170,12 +173,21 @@ 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"): - session.install("-r", "requirements.txt") + if os.path.exists("constraints.txt"): + session.install("-r", "requirements.txt", "-c", "constraints.txt") + else: + session.install("-r", "requirements.txt") if os.path.exists("requirements-test.txt"): - session.install("-r", "requirements-test.txt") + if os.path.exists("constraints-test.txt"): + session.install("-r", "requirements-test.txt", "-c", "constraints-test.txt") + else: + session.install("-r", "requirements-test.txt") if INSTALL_LIBRARY_FROM_SOURCE: session.install("-e", _get_repo_root()) diff --git a/samples/snippets/requirements-test.txt b/samples/snippets/requirements-test.txt index 7e460c8c..95ea1e6a 100644 --- a/samples/snippets/requirements-test.txt +++ b/samples/snippets/requirements-test.txt @@ -1 +1 @@ -pytest==6.0.1 +pytest==6.2.4 diff --git a/samples/snippets/requirements.txt b/samples/snippets/requirements.txt index 115eabf9..e543c96a 100644 --- a/samples/snippets/requirements.txt +++ b/samples/snippets/requirements.txt @@ -1 +1 @@ -google-cloud-tasks==2.1.0 +google-cloud-tasks==2.2.0 diff --git a/scripts/fixup_tasks_v2_keywords.py b/scripts/fixup_tasks_v2_keywords.py index 30997b65..fdfc7b38 100644 --- a/scripts/fixup_tasks_v2_keywords.py +++ b/scripts/fixup_tasks_v2_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,23 +39,22 @@ def partition( class tasksCallTransformer(cst.CSTTransformer): CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { - 'create_queue': ('parent', 'queue', ), - 'create_task': ('parent', 'task', 'response_view', ), - 'delete_queue': ('name', ), - 'delete_task': ('name', ), - 'get_iam_policy': ('resource', 'options', ), - 'get_queue': ('name', ), - 'get_task': ('name', 'response_view', ), - 'list_queues': ('parent', 'filter', 'page_size', 'page_token', ), - 'list_tasks': ('parent', 'response_view', 'page_size', 'page_token', ), - 'pause_queue': ('name', ), - 'purge_queue': ('name', ), - 'resume_queue': ('name', ), - 'run_task': ('name', 'response_view', ), - 'set_iam_policy': ('resource', 'policy', ), - 'test_iam_permissions': ('resource', 'permissions', ), - 'update_queue': ('queue', 'update_mask', ), - + 'create_queue': ('parent', 'queue', ), + 'create_task': ('parent', 'task', 'response_view', ), + 'delete_queue': ('name', ), + 'delete_task': ('name', ), + 'get_iam_policy': ('resource', 'options', ), + 'get_queue': ('name', ), + 'get_task': ('name', 'response_view', ), + 'list_queues': ('parent', 'filter', 'page_size', 'page_token', ), + 'list_tasks': ('parent', 'response_view', 'page_size', 'page_token', ), + 'pause_queue': ('name', ), + 'purge_queue': ('name', ), + 'resume_queue': ('name', ), + 'run_task': ('name', 'response_view', ), + 'set_iam_policy': ('resource', 'policy', ), + 'test_iam_permissions': ('resource', 'permissions', ), + 'update_queue': ('queue', 'update_mask', ), } def leave_Call(self, original: cst.Call, updated: cst.Call) -> cst.CSTNode: @@ -88,7 +85,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/scripts/fixup_tasks_v2beta2_keywords.py b/scripts/fixup_tasks_v2beta2_keywords.py index 4f910267..4b2201b4 100644 --- a/scripts/fixup_tasks_v2beta2_keywords.py +++ b/scripts/fixup_tasks_v2beta2_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,27 +39,26 @@ def partition( class tasksCallTransformer(cst.CSTTransformer): CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { - 'acknowledge_task': ('name', 'schedule_time', ), - 'cancel_lease': ('name', 'schedule_time', 'response_view', ), - 'create_queue': ('parent', 'queue', ), - 'create_task': ('parent', 'task', 'response_view', ), - 'delete_queue': ('name', ), - 'delete_task': ('name', ), - 'get_iam_policy': ('resource', 'options', ), - 'get_queue': ('name', 'read_mask', ), - 'get_task': ('name', 'response_view', ), - 'lease_tasks': ('parent', 'lease_duration', 'max_tasks', 'response_view', 'filter', ), - 'list_queues': ('parent', 'filter', 'page_size', 'page_token', 'read_mask', ), - 'list_tasks': ('parent', 'response_view', 'page_size', 'page_token', ), - 'pause_queue': ('name', ), - 'purge_queue': ('name', ), - 'renew_lease': ('name', 'schedule_time', 'lease_duration', 'response_view', ), - 'resume_queue': ('name', ), - 'run_task': ('name', 'response_view', ), - 'set_iam_policy': ('resource', 'policy', ), - 'test_iam_permissions': ('resource', 'permissions', ), - 'update_queue': ('queue', 'update_mask', ), - + 'acknowledge_task': ('name', 'schedule_time', ), + 'cancel_lease': ('name', 'schedule_time', 'response_view', ), + 'create_queue': ('parent', 'queue', ), + 'create_task': ('parent', 'task', 'response_view', ), + 'delete_queue': ('name', ), + 'delete_task': ('name', ), + 'get_iam_policy': ('resource', 'options', ), + 'get_queue': ('name', 'read_mask', ), + 'get_task': ('name', 'response_view', ), + 'lease_tasks': ('parent', 'lease_duration', 'max_tasks', 'response_view', 'filter', ), + 'list_queues': ('parent', 'filter', 'page_size', 'page_token', 'read_mask', ), + 'list_tasks': ('parent', 'response_view', 'page_size', 'page_token', ), + 'pause_queue': ('name', ), + 'purge_queue': ('name', ), + 'renew_lease': ('name', 'schedule_time', 'lease_duration', 'response_view', ), + 'resume_queue': ('name', ), + 'run_task': ('name', 'response_view', ), + 'set_iam_policy': ('resource', 'policy', ), + 'test_iam_permissions': ('resource', 'permissions', ), + 'update_queue': ('queue', 'update_mask', ), } def leave_Call(self, original: cst.Call, updated: cst.Call) -> cst.CSTNode: @@ -92,7 +89,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/scripts/fixup_tasks_v2beta3_keywords.py b/scripts/fixup_tasks_v2beta3_keywords.py index b8e151d0..e9fe202e 100644 --- a/scripts/fixup_tasks_v2beta3_keywords.py +++ b/scripts/fixup_tasks_v2beta3_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,23 +39,22 @@ def partition( class tasksCallTransformer(cst.CSTTransformer): CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { - 'create_queue': ('parent', 'queue', ), - 'create_task': ('parent', 'task', 'response_view', ), - 'delete_queue': ('name', ), - 'delete_task': ('name', ), - 'get_iam_policy': ('resource', 'options', ), - 'get_queue': ('name', 'read_mask', ), - 'get_task': ('name', 'response_view', ), - 'list_queues': ('parent', 'filter', 'page_size', 'page_token', 'read_mask', ), - 'list_tasks': ('parent', 'response_view', 'page_size', 'page_token', ), - 'pause_queue': ('name', ), - 'purge_queue': ('name', ), - 'resume_queue': ('name', ), - 'run_task': ('name', 'response_view', ), - 'set_iam_policy': ('resource', 'policy', ), - 'test_iam_permissions': ('resource', 'permissions', ), - 'update_queue': ('queue', 'update_mask', ), - + 'create_queue': ('parent', 'queue', ), + 'create_task': ('parent', 'task', 'response_view', ), + 'delete_queue': ('name', ), + 'delete_task': ('name', ), + 'get_iam_policy': ('resource', 'options', ), + 'get_queue': ('name', 'read_mask', ), + 'get_task': ('name', 'response_view', ), + 'list_queues': ('parent', 'filter', 'page_size', 'page_token', 'read_mask', ), + 'list_tasks': ('parent', 'response_view', 'page_size', 'page_token', ), + 'pause_queue': ('name', ), + 'purge_queue': ('name', ), + 'resume_queue': ('name', ), + 'run_task': ('name', 'response_view', ), + 'set_iam_policy': ('resource', 'policy', ), + 'test_iam_permissions': ('resource', 'permissions', ), + 'update_queue': ('queue', 'update_mask', ), } def leave_Call(self, original: cst.Call, updated: cst.Call) -> cst.CSTNode: @@ -88,7 +85,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/setup.py b/setup.py index 4f5b2783..af750040 100644 --- a/setup.py +++ b/setup.py @@ -21,15 +21,17 @@ name = "google-cloud-tasks" description = "Cloud Tasks API API client library" -version = "2.2.0" +version = "2.3.0" release_status = "Development Status :: 5 - Production/Stable" dependencies = [ - "google-api-core[grpc] >= 1.22.0, < 2.0.0dev", + "google-api-core[grpc] >= 1.22.2, < 2.0.0dev", "grpc-google-iam-v1 >= 0.12.3, < 0.13dev", "proto-plus >= 0.4.0", - "libcst >= 0.2.5", + "packaging >= 14.3", ] +extras = {"libcst": "libcst >= 0.2.5"} + package_root = os.path.abspath(os.path.dirname(__file__)) readme_filename = os.path.join(package_root, "README.rst") diff --git a/synth.metadata b/synth.metadata deleted file mode 100644 index 57c8e0c2..00000000 --- a/synth.metadata +++ /dev/null @@ -1,62 +0,0 @@ -{ - "sources": [ - { - "git": { - "name": ".", - "remote": "git@github.com:googleapis/python-tasks", - "sha": "7e720ed97e5ea978d6e1a0aaf2ae508cccb6ff90" - } - }, - { - "git": { - "name": "googleapis", - "remote": "https://github.com/googleapis/googleapis.git", - "sha": "eabec5a21219401bad79e1cc7d900c1658aee5fd", - "internalRef": "359130387" - } - }, - { - "git": { - "name": "synthtool", - "remote": "https://github.com/googleapis/synthtool.git", - "sha": "79ab0b44a2cc7d803d07c107f9faf07729fc4012" - } - }, - { - "git": { - "name": "synthtool", - "remote": "https://github.com/googleapis/synthtool.git", - "sha": "79ab0b44a2cc7d803d07c107f9faf07729fc4012" - } - } - ], - "destinations": [ - { - "client": { - "source": "googleapis", - "apiName": "tasks", - "apiVersion": "v2beta2", - "language": "python", - "generator": "bazel" - } - }, - { - "client": { - "source": "googleapis", - "apiName": "tasks", - "apiVersion": "v2beta3", - "language": "python", - "generator": "bazel" - } - }, - { - "client": { - "source": "googleapis", - "apiName": "tasks", - "apiVersion": "v2", - "language": "python", - "generator": "bazel" - } - } - ] -} \ No newline at end of file diff --git a/tasks-v2beta2-py.tar.gz b/testing/constraints-3.10.txt similarity index 100% rename from tasks-v2beta2-py.tar.gz rename to testing/constraints-3.10.txt diff --git a/testing/constraints-3.11.txt b/testing/constraints-3.11.txt new file mode 100644 index 00000000..e69de29b diff --git a/testing/constraints-3.6.txt b/testing/constraints-3.6.txt new file mode 100644 index 00000000..ac3ae21c --- /dev/null +++ b/testing/constraints-3.6.txt @@ -0,0 +1,13 @@ +# This constraints file is used to check that lower bounds +# are correct in setup.py +# List *all* library dependencies and extras in this file. +# Pin the version to the lower bound. +# +# e.g., if setup.py has "foo >= 1.14.0, < 2.0.0dev", +# Then this file should have foo==1.14.0 +google-api-core==1.22.2 +grpc-google-iam-v1==0.12.3 +proto-plus==0.4.0 +libcst==0.2.5 +packaging==14.3 +google-auth==1.24.0 # TODO: remove after google-auth>=1.25.0 is transitively required through google-api-core diff --git a/testing/constraints-3.7.txt b/testing/constraints-3.7.txt new file mode 100644 index 00000000..e69de29b diff --git a/testing/constraints-3.8.txt b/testing/constraints-3.8.txt new file mode 100644 index 00000000..e69de29b diff --git a/testing/constraints-3.9.txt b/testing/constraints-3.9.txt new file mode 100644 index 00000000..e69de29b diff --git a/tests/__init__.py b/tests/__init__.py new file mode 100644 index 00000000..4de65971 --- /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 new file mode 100644 index 00000000..4de65971 --- /dev/null +++ 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 00000000..4de65971 --- /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/tasks_v2/__init__.py b/tests/unit/gapic/tasks_v2/__init__.py index 8b137891..4de65971 100644 --- a/tests/unit/gapic/tasks_v2/__init__.py +++ b/tests/unit/gapic/tasks_v2/__init__.py @@ -1 +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/tasks_v2/test_cloud_tasks.py b/tests/unit/gapic/tasks_v2/test_cloud_tasks.py index 573bfa7b..f2f3cda1 100644 --- a/tests/unit/gapic/tasks_v2/test_cloud_tasks.py +++ b/tests/unit/gapic/tasks_v2/test_cloud_tasks.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,34 +23,62 @@ 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.cloud.tasks_v2.services.cloud_tasks import CloudTasksAsyncClient from google.cloud.tasks_v2.services.cloud_tasks import CloudTasksClient from google.cloud.tasks_v2.services.cloud_tasks import pagers from google.cloud.tasks_v2.services.cloud_tasks import transports +from google.cloud.tasks_v2.services.cloud_tasks.transports.base import _API_CORE_VERSION +from google.cloud.tasks_v2.services.cloud_tasks.transports.base import ( + _GOOGLE_AUTH_VERSION, +) from google.cloud.tasks_v2.types import cloudtasks from google.cloud.tasks_v2.types import queue from google.cloud.tasks_v2.types import queue as gct_queue from google.cloud.tasks_v2.types import target from google.cloud.tasks_v2.types import task from google.cloud.tasks_v2.types import task as gct_task -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 any_pb2 as gp_any # 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.rpc import status_pb2 as status # type: ignore -from google.type import expr_pb2 as expr # type: ignore +from google.protobuf import any_pb2 # type: ignore +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from google.rpc import status_pb2 # type: ignore +from google.type import expr_pb2 # type: ignore +import google.auth + + +# TODO(busunkim): Once google-api-core >= 1.26.0 is required: +# - Delete all the api-core and auth "less than" test cases +# - Delete these pytest markers (Make the "greater than or equal to" tests the default). +requires_google_auth_lt_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), + reason="This test requires google-auth < 1.25.0", +) +requires_google_auth_gte_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) < packaging.version.parse("1.25.0"), + reason="This test requires google-auth >= 1.25.0", +) + +requires_api_core_lt_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) >= packaging.version.parse("1.26.0"), + reason="This test requires google-api-core < 1.26.0", +) + +requires_api_core_gte_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) < packaging.version.parse("1.26.0"), + reason="This test requires google-api-core >= 1.26.0", +) def client_cert_source_callback(): @@ -95,31 +122,35 @@ def test__get_default_mtls_endpoint(): assert CloudTasksClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi -def test_cloud_tasks_client_from_service_account_info(): - creds = credentials.AnonymousCredentials() +@pytest.mark.parametrize("client_class", [CloudTasksClient, CloudTasksAsyncClient,]) +def test_cloud_tasks_client_from_service_account_info(client_class): + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_info" ) as factory: factory.return_value = creds info = {"valid": True} - client = CloudTasksClient.from_service_account_info(info) + client = client_class.from_service_account_info(info) assert client.transport._credentials == creds + assert isinstance(client, client_class) assert client.transport._host == "cloudtasks.googleapis.com:443" @pytest.mark.parametrize("client_class", [CloudTasksClient, CloudTasksAsyncClient,]) def test_cloud_tasks_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: 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 == "cloudtasks.googleapis.com:443" @@ -159,7 +190,7 @@ def test_cloud_tasks_client_client_options( ): # Check that if channel is provided we won't create a new one. with mock.patch.object(CloudTasksClient, "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() @@ -443,7 +474,7 @@ def test_list_queues( transport: str = "grpc", request_type=cloudtasks.ListQueuesRequest ): client = CloudTasksClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -456,19 +487,15 @@ def test_list_queues( call.return_value = cloudtasks.ListQueuesResponse( next_page_token="next_page_token_value", ) - response = client.list_queues(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == cloudtasks.ListQueuesRequest() # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListQueuesPager) - assert response.next_page_token == "next_page_token_value" @@ -476,12 +503,27 @@ def test_list_queues_from_dict(): test_list_queues(request_type=dict) +def test_list_queues_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 = CloudTasksClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_queues), "__call__") as call: + client.list_queues() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == cloudtasks.ListQueuesRequest() + + @pytest.mark.asyncio async def test_list_queues_async( transport: str = "grpc_asyncio", request_type=cloudtasks.ListQueuesRequest ): client = CloudTasksAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -494,18 +536,15 @@ async def test_list_queues_async( call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( cloudtasks.ListQueuesResponse(next_page_token="next_page_token_value",) ) - response = await client.list_queues(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == cloudtasks.ListQueuesRequest() # Establish that the response is the type that we expect. assert isinstance(response, pagers.ListQueuesAsyncPager) - assert response.next_page_token == "next_page_token_value" @@ -515,17 +554,17 @@ async def test_list_queues_async_from_dict(): def test_list_queues_field_headers(): - client = CloudTasksClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = cloudtasks.ListQueuesRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_queues), "__call__") as call: call.return_value = cloudtasks.ListQueuesResponse() - client.list_queues(request) # Establish that the underlying gRPC stub method was called. @@ -540,11 +579,12 @@ def test_list_queues_field_headers(): @pytest.mark.asyncio async def test_list_queues_field_headers_async(): - client = CloudTasksAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = cloudtasks.ListQueuesRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -552,7 +592,6 @@ async def test_list_queues_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( cloudtasks.ListQueuesResponse() ) - await client.list_queues(request) # Establish that the underlying gRPC stub method was called. @@ -566,13 +605,12 @@ async def test_list_queues_field_headers_async(): def test_list_queues_flattened(): - client = CloudTasksClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_queues), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = cloudtasks.ListQueuesResponse() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.list_queues(parent="parent_value",) @@ -581,12 +619,11 @@ def test_list_queues_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" def test_list_queues_flattened_error(): - client = CloudTasksClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -598,7 +635,7 @@ def test_list_queues_flattened_error(): @pytest.mark.asyncio async def test_list_queues_flattened_async(): - client = CloudTasksAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_queues), "__call__") as call: @@ -616,13 +653,12 @@ async def test_list_queues_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_queues_flattened_error_async(): - client = CloudTasksAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -633,7 +669,7 @@ async def test_list_queues_flattened_error_async(): def test_list_queues_pager(): - client = CloudTasksClient(credentials=credentials.AnonymousCredentials,) + client = CloudTasksClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_queues), "__call__") as call: @@ -665,7 +701,7 @@ def test_list_queues_pager(): def test_list_queues_pages(): - client = CloudTasksClient(credentials=credentials.AnonymousCredentials,) + client = CloudTasksClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_queues), "__call__") as call: @@ -689,7 +725,7 @@ def test_list_queues_pages(): @pytest.mark.asyncio async def test_list_queues_async_pager(): - client = CloudTasksAsyncClient(credentials=credentials.AnonymousCredentials,) + client = CloudTasksAsyncClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -720,7 +756,7 @@ async def test_list_queues_async_pager(): @pytest.mark.asyncio async def test_list_queues_async_pages(): - client = CloudTasksAsyncClient(credentials=credentials.AnonymousCredentials,) + client = CloudTasksAsyncClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -748,7 +784,7 @@ async def test_list_queues_async_pages(): def test_get_queue(transport: str = "grpc", request_type=cloudtasks.GetQueueRequest): client = CloudTasksClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -761,21 +797,16 @@ def test_get_queue(transport: str = "grpc", request_type=cloudtasks.GetQueueRequ call.return_value = queue.Queue( name="name_value", state=queue.Queue.State.RUNNING, ) - response = client.get_queue(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == cloudtasks.GetQueueRequest() # Establish that the response is the type that we expect. - assert isinstance(response, queue.Queue) - assert response.name == "name_value" - assert response.state == queue.Queue.State.RUNNING @@ -783,12 +814,27 @@ def test_get_queue_from_dict(): test_get_queue(request_type=dict) +def test_get_queue_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 = CloudTasksClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_queue), "__call__") as call: + client.get_queue() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == cloudtasks.GetQueueRequest() + + @pytest.mark.asyncio async def test_get_queue_async( transport: str = "grpc_asyncio", request_type=cloudtasks.GetQueueRequest ): client = CloudTasksAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -801,20 +847,16 @@ async def test_get_queue_async( call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( queue.Queue(name="name_value", state=queue.Queue.State.RUNNING,) ) - response = await client.get_queue(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == cloudtasks.GetQueueRequest() # Establish that the response is the type that we expect. assert isinstance(response, queue.Queue) - assert response.name == "name_value" - assert response.state == queue.Queue.State.RUNNING @@ -824,17 +866,17 @@ async def test_get_queue_async_from_dict(): def test_get_queue_field_headers(): - client = CloudTasksClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = cloudtasks.GetQueueRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_queue), "__call__") as call: call.return_value = queue.Queue() - client.get_queue(request) # Establish that the underlying gRPC stub method was called. @@ -849,17 +891,17 @@ def test_get_queue_field_headers(): @pytest.mark.asyncio async def test_get_queue_field_headers_async(): - client = CloudTasksAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = cloudtasks.GetQueueRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_queue), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(queue.Queue()) - await client.get_queue(request) # Establish that the underlying gRPC stub method was called. @@ -873,13 +915,12 @@ async def test_get_queue_field_headers_async(): def test_get_queue_flattened(): - client = CloudTasksClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_queue), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = queue.Queue() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.get_queue(name="name_value",) @@ -888,12 +929,11 @@ def test_get_queue_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" def test_get_queue_flattened_error(): - client = CloudTasksClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -905,7 +945,7 @@ def test_get_queue_flattened_error(): @pytest.mark.asyncio async def test_get_queue_flattened_async(): - client = CloudTasksAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_queue), "__call__") as call: @@ -921,13 +961,12 @@ async def test_get_queue_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_queue_flattened_error_async(): - client = CloudTasksAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -941,7 +980,7 @@ def test_create_queue( transport: str = "grpc", request_type=cloudtasks.CreateQueueRequest ): client = CloudTasksClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -954,21 +993,16 @@ def test_create_queue( call.return_value = gct_queue.Queue( name="name_value", state=gct_queue.Queue.State.RUNNING, ) - response = client.create_queue(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == cloudtasks.CreateQueueRequest() # Establish that the response is the type that we expect. - assert isinstance(response, gct_queue.Queue) - assert response.name == "name_value" - assert response.state == gct_queue.Queue.State.RUNNING @@ -976,12 +1010,27 @@ def test_create_queue_from_dict(): test_create_queue(request_type=dict) +def test_create_queue_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 = CloudTasksClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.create_queue), "__call__") as call: + client.create_queue() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == cloudtasks.CreateQueueRequest() + + @pytest.mark.asyncio async def test_create_queue_async( transport: str = "grpc_asyncio", request_type=cloudtasks.CreateQueueRequest ): client = CloudTasksAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -994,20 +1043,16 @@ async def test_create_queue_async( call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( gct_queue.Queue(name="name_value", state=gct_queue.Queue.State.RUNNING,) ) - response = await client.create_queue(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == cloudtasks.CreateQueueRequest() # Establish that the response is the type that we expect. assert isinstance(response, gct_queue.Queue) - assert response.name == "name_value" - assert response.state == gct_queue.Queue.State.RUNNING @@ -1017,17 +1062,17 @@ async def test_create_queue_async_from_dict(): def test_create_queue_field_headers(): - client = CloudTasksClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = cloudtasks.CreateQueueRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.create_queue), "__call__") as call: call.return_value = gct_queue.Queue() - client.create_queue(request) # Establish that the underlying gRPC stub method was called. @@ -1042,17 +1087,17 @@ def test_create_queue_field_headers(): @pytest.mark.asyncio async def test_create_queue_field_headers_async(): - client = CloudTasksAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = cloudtasks.CreateQueueRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.create_queue), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gct_queue.Queue()) - await client.create_queue(request) # Establish that the underlying gRPC stub method was called. @@ -1066,13 +1111,12 @@ async def test_create_queue_field_headers_async(): def test_create_queue_flattened(): - client = CloudTasksClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.create_queue), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = gct_queue.Queue() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.create_queue( @@ -1083,14 +1127,12 @@ def test_create_queue_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" - assert args[0].queue == gct_queue.Queue(name="name_value") def test_create_queue_flattened_error(): - client = CloudTasksClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1104,7 +1146,7 @@ def test_create_queue_flattened_error(): @pytest.mark.asyncio async def test_create_queue_flattened_async(): - client = CloudTasksAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.create_queue), "__call__") as call: @@ -1122,15 +1164,13 @@ async def test_create_queue_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" - assert args[0].queue == gct_queue.Queue(name="name_value") @pytest.mark.asyncio async def test_create_queue_flattened_error_async(): - client = CloudTasksAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1146,7 +1186,7 @@ def test_update_queue( transport: str = "grpc", request_type=cloudtasks.UpdateQueueRequest ): client = CloudTasksClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1159,21 +1199,16 @@ def test_update_queue( call.return_value = gct_queue.Queue( name="name_value", state=gct_queue.Queue.State.RUNNING, ) - response = client.update_queue(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == cloudtasks.UpdateQueueRequest() # Establish that the response is the type that we expect. - assert isinstance(response, gct_queue.Queue) - assert response.name == "name_value" - assert response.state == gct_queue.Queue.State.RUNNING @@ -1181,12 +1216,27 @@ def test_update_queue_from_dict(): test_update_queue(request_type=dict) +def test_update_queue_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 = CloudTasksClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.update_queue), "__call__") as call: + client.update_queue() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == cloudtasks.UpdateQueueRequest() + + @pytest.mark.asyncio async def test_update_queue_async( transport: str = "grpc_asyncio", request_type=cloudtasks.UpdateQueueRequest ): client = CloudTasksAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1199,20 +1249,16 @@ async def test_update_queue_async( call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( gct_queue.Queue(name="name_value", state=gct_queue.Queue.State.RUNNING,) ) - response = await client.update_queue(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == cloudtasks.UpdateQueueRequest() # Establish that the response is the type that we expect. assert isinstance(response, gct_queue.Queue) - assert response.name == "name_value" - assert response.state == gct_queue.Queue.State.RUNNING @@ -1222,17 +1268,17 @@ async def test_update_queue_async_from_dict(): def test_update_queue_field_headers(): - client = CloudTasksClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = cloudtasks.UpdateQueueRequest() + request.queue.name = "queue.name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.update_queue), "__call__") as call: call.return_value = gct_queue.Queue() - client.update_queue(request) # Establish that the underlying gRPC stub method was called. @@ -1247,17 +1293,17 @@ def test_update_queue_field_headers(): @pytest.mark.asyncio async def test_update_queue_field_headers_async(): - client = CloudTasksAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = cloudtasks.UpdateQueueRequest() + request.queue.name = "queue.name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.update_queue), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gct_queue.Queue()) - await client.update_queue(request) # Establish that the underlying gRPC stub method was called. @@ -1271,32 +1317,29 @@ async def test_update_queue_field_headers_async(): def test_update_queue_flattened(): - client = CloudTasksClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.update_queue), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = gct_queue.Queue() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.update_queue( queue=gct_queue.Queue(name="name_value"), - update_mask=field_mask.FieldMask(paths=["paths_value"]), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].queue == gct_queue.Queue(name="name_value") - - assert args[0].update_mask == field_mask.FieldMask(paths=["paths_value"]) + assert args[0].update_mask == field_mask_pb2.FieldMask(paths=["paths_value"]) def test_update_queue_flattened_error(): - client = CloudTasksClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1304,13 +1347,13 @@ def test_update_queue_flattened_error(): client.update_queue( cloudtasks.UpdateQueueRequest(), queue=gct_queue.Queue(name="name_value"), - update_mask=field_mask.FieldMask(paths=["paths_value"]), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) @pytest.mark.asyncio async def test_update_queue_flattened_async(): - client = CloudTasksAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.update_queue), "__call__") as call: @@ -1322,22 +1365,20 @@ async def test_update_queue_flattened_async(): # using the keyword arguments to the method. response = await client.update_queue( queue=gct_queue.Queue(name="name_value"), - update_mask=field_mask.FieldMask(paths=["paths_value"]), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].queue == gct_queue.Queue(name="name_value") - - assert args[0].update_mask == field_mask.FieldMask(paths=["paths_value"]) + assert args[0].update_mask == field_mask_pb2.FieldMask(paths=["paths_value"]) @pytest.mark.asyncio async def test_update_queue_flattened_error_async(): - client = CloudTasksAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1345,7 +1386,7 @@ async def test_update_queue_flattened_error_async(): await client.update_queue( cloudtasks.UpdateQueueRequest(), queue=gct_queue.Queue(name="name_value"), - update_mask=field_mask.FieldMask(paths=["paths_value"]), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) @@ -1353,7 +1394,7 @@ def test_delete_queue( transport: str = "grpc", request_type=cloudtasks.DeleteQueueRequest ): client = CloudTasksClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1364,13 +1405,11 @@ def test_delete_queue( with mock.patch.object(type(client.transport.delete_queue), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = None - response = client.delete_queue(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == cloudtasks.DeleteQueueRequest() # Establish that the response is the type that we expect. @@ -1381,12 +1420,27 @@ def test_delete_queue_from_dict(): test_delete_queue(request_type=dict) +def test_delete_queue_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 = CloudTasksClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_queue), "__call__") as call: + client.delete_queue() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == cloudtasks.DeleteQueueRequest() + + @pytest.mark.asyncio async def test_delete_queue_async( transport: str = "grpc_asyncio", request_type=cloudtasks.DeleteQueueRequest ): client = CloudTasksAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1397,13 +1451,11 @@ async def test_delete_queue_async( with mock.patch.object(type(client.transport.delete_queue), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_queue(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == cloudtasks.DeleteQueueRequest() # Establish that the response is the type that we expect. @@ -1416,17 +1468,17 @@ async def test_delete_queue_async_from_dict(): def test_delete_queue_field_headers(): - client = CloudTasksClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = cloudtasks.DeleteQueueRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.delete_queue), "__call__") as call: call.return_value = None - client.delete_queue(request) # Establish that the underlying gRPC stub method was called. @@ -1441,17 +1493,17 @@ def test_delete_queue_field_headers(): @pytest.mark.asyncio async def test_delete_queue_field_headers_async(): - client = CloudTasksAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = cloudtasks.DeleteQueueRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.delete_queue), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_queue(request) # Establish that the underlying gRPC stub method was called. @@ -1465,13 +1517,12 @@ async def test_delete_queue_field_headers_async(): def test_delete_queue_flattened(): - client = CloudTasksClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.delete_queue), "__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_queue(name="name_value",) @@ -1480,12 +1531,11 @@ def test_delete_queue_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" def test_delete_queue_flattened_error(): - client = CloudTasksClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1497,7 +1547,7 @@ def test_delete_queue_flattened_error(): @pytest.mark.asyncio async def test_delete_queue_flattened_async(): - client = CloudTasksAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.delete_queue), "__call__") as call: @@ -1513,13 +1563,12 @@ async def test_delete_queue_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_queue_flattened_error_async(): - client = CloudTasksAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1533,7 +1582,7 @@ def test_purge_queue( transport: str = "grpc", request_type=cloudtasks.PurgeQueueRequest ): client = CloudTasksClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1546,21 +1595,16 @@ def test_purge_queue( call.return_value = queue.Queue( name="name_value", state=queue.Queue.State.RUNNING, ) - response = client.purge_queue(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == cloudtasks.PurgeQueueRequest() # Establish that the response is the type that we expect. - assert isinstance(response, queue.Queue) - assert response.name == "name_value" - assert response.state == queue.Queue.State.RUNNING @@ -1568,12 +1612,27 @@ def test_purge_queue_from_dict(): test_purge_queue(request_type=dict) +def test_purge_queue_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 = CloudTasksClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.purge_queue), "__call__") as call: + client.purge_queue() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == cloudtasks.PurgeQueueRequest() + + @pytest.mark.asyncio async def test_purge_queue_async( transport: str = "grpc_asyncio", request_type=cloudtasks.PurgeQueueRequest ): client = CloudTasksAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1586,20 +1645,16 @@ async def test_purge_queue_async( call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( queue.Queue(name="name_value", state=queue.Queue.State.RUNNING,) ) - response = await client.purge_queue(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == cloudtasks.PurgeQueueRequest() # Establish that the response is the type that we expect. assert isinstance(response, queue.Queue) - assert response.name == "name_value" - assert response.state == queue.Queue.State.RUNNING @@ -1609,17 +1664,17 @@ async def test_purge_queue_async_from_dict(): def test_purge_queue_field_headers(): - client = CloudTasksClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = cloudtasks.PurgeQueueRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.purge_queue), "__call__") as call: call.return_value = queue.Queue() - client.purge_queue(request) # Establish that the underlying gRPC stub method was called. @@ -1634,17 +1689,17 @@ def test_purge_queue_field_headers(): @pytest.mark.asyncio async def test_purge_queue_field_headers_async(): - client = CloudTasksAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = cloudtasks.PurgeQueueRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.purge_queue), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(queue.Queue()) - await client.purge_queue(request) # Establish that the underlying gRPC stub method was called. @@ -1658,13 +1713,12 @@ async def test_purge_queue_field_headers_async(): def test_purge_queue_flattened(): - client = CloudTasksClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.purge_queue), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = queue.Queue() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.purge_queue(name="name_value",) @@ -1673,12 +1727,11 @@ def test_purge_queue_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" def test_purge_queue_flattened_error(): - client = CloudTasksClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1690,7 +1743,7 @@ def test_purge_queue_flattened_error(): @pytest.mark.asyncio async def test_purge_queue_flattened_async(): - client = CloudTasksAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.purge_queue), "__call__") as call: @@ -1706,13 +1759,12 @@ async def test_purge_queue_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_purge_queue_flattened_error_async(): - client = CloudTasksAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1726,7 +1778,7 @@ def test_pause_queue( transport: str = "grpc", request_type=cloudtasks.PauseQueueRequest ): client = CloudTasksClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1739,21 +1791,16 @@ def test_pause_queue( call.return_value = queue.Queue( name="name_value", state=queue.Queue.State.RUNNING, ) - response = client.pause_queue(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == cloudtasks.PauseQueueRequest() # Establish that the response is the type that we expect. - assert isinstance(response, queue.Queue) - assert response.name == "name_value" - assert response.state == queue.Queue.State.RUNNING @@ -1761,12 +1808,27 @@ def test_pause_queue_from_dict(): test_pause_queue(request_type=dict) +def test_pause_queue_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 = CloudTasksClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.pause_queue), "__call__") as call: + client.pause_queue() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == cloudtasks.PauseQueueRequest() + + @pytest.mark.asyncio async def test_pause_queue_async( transport: str = "grpc_asyncio", request_type=cloudtasks.PauseQueueRequest ): client = CloudTasksAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1779,20 +1841,16 @@ async def test_pause_queue_async( call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( queue.Queue(name="name_value", state=queue.Queue.State.RUNNING,) ) - response = await client.pause_queue(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == cloudtasks.PauseQueueRequest() # Establish that the response is the type that we expect. assert isinstance(response, queue.Queue) - assert response.name == "name_value" - assert response.state == queue.Queue.State.RUNNING @@ -1802,17 +1860,17 @@ async def test_pause_queue_async_from_dict(): def test_pause_queue_field_headers(): - client = CloudTasksClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = cloudtasks.PauseQueueRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.pause_queue), "__call__") as call: call.return_value = queue.Queue() - client.pause_queue(request) # Establish that the underlying gRPC stub method was called. @@ -1827,17 +1885,17 @@ def test_pause_queue_field_headers(): @pytest.mark.asyncio async def test_pause_queue_field_headers_async(): - client = CloudTasksAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = cloudtasks.PauseQueueRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.pause_queue), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(queue.Queue()) - await client.pause_queue(request) # Establish that the underlying gRPC stub method was called. @@ -1851,13 +1909,12 @@ async def test_pause_queue_field_headers_async(): def test_pause_queue_flattened(): - client = CloudTasksClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.pause_queue), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = queue.Queue() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.pause_queue(name="name_value",) @@ -1866,12 +1923,11 @@ def test_pause_queue_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" def test_pause_queue_flattened_error(): - client = CloudTasksClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1883,7 +1939,7 @@ def test_pause_queue_flattened_error(): @pytest.mark.asyncio async def test_pause_queue_flattened_async(): - client = CloudTasksAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.pause_queue), "__call__") as call: @@ -1899,13 +1955,12 @@ async def test_pause_queue_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_pause_queue_flattened_error_async(): - client = CloudTasksAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1919,7 +1974,7 @@ def test_resume_queue( transport: str = "grpc", request_type=cloudtasks.ResumeQueueRequest ): client = CloudTasksClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1932,21 +1987,16 @@ def test_resume_queue( call.return_value = queue.Queue( name="name_value", state=queue.Queue.State.RUNNING, ) - response = client.resume_queue(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == cloudtasks.ResumeQueueRequest() # Establish that the response is the type that we expect. - assert isinstance(response, queue.Queue) - assert response.name == "name_value" - assert response.state == queue.Queue.State.RUNNING @@ -1954,12 +2004,27 @@ def test_resume_queue_from_dict(): test_resume_queue(request_type=dict) +def test_resume_queue_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 = CloudTasksClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.resume_queue), "__call__") as call: + client.resume_queue() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == cloudtasks.ResumeQueueRequest() + + @pytest.mark.asyncio async def test_resume_queue_async( transport: str = "grpc_asyncio", request_type=cloudtasks.ResumeQueueRequest ): client = CloudTasksAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1972,20 +2037,16 @@ async def test_resume_queue_async( call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( queue.Queue(name="name_value", state=queue.Queue.State.RUNNING,) ) - response = await client.resume_queue(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == cloudtasks.ResumeQueueRequest() # Establish that the response is the type that we expect. assert isinstance(response, queue.Queue) - assert response.name == "name_value" - assert response.state == queue.Queue.State.RUNNING @@ -1995,17 +2056,17 @@ async def test_resume_queue_async_from_dict(): def test_resume_queue_field_headers(): - client = CloudTasksClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = cloudtasks.ResumeQueueRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.resume_queue), "__call__") as call: call.return_value = queue.Queue() - client.resume_queue(request) # Establish that the underlying gRPC stub method was called. @@ -2020,17 +2081,17 @@ def test_resume_queue_field_headers(): @pytest.mark.asyncio async def test_resume_queue_field_headers_async(): - client = CloudTasksAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = cloudtasks.ResumeQueueRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.resume_queue), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(queue.Queue()) - await client.resume_queue(request) # Establish that the underlying gRPC stub method was called. @@ -2044,13 +2105,12 @@ async def test_resume_queue_field_headers_async(): def test_resume_queue_flattened(): - client = CloudTasksClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.resume_queue), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = queue.Queue() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.resume_queue(name="name_value",) @@ -2059,12 +2119,11 @@ def test_resume_queue_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" def test_resume_queue_flattened_error(): - client = CloudTasksClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -2076,7 +2135,7 @@ def test_resume_queue_flattened_error(): @pytest.mark.asyncio async def test_resume_queue_flattened_async(): - client = CloudTasksAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.resume_queue), "__call__") as call: @@ -2092,13 +2151,12 @@ async def test_resume_queue_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_resume_queue_flattened_error_async(): - client = CloudTasksAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -2109,10 +2167,10 @@ async def test_resume_queue_flattened_error_async(): def test_get_iam_policy( - transport: str = "grpc", request_type=iam_policy.GetIamPolicyRequest + transport: str = "grpc", request_type=iam_policy_pb2.GetIamPolicyRequest ): client = CloudTasksClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -2122,22 +2180,17 @@ def test_get_iam_policy( # 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) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - - assert args[0] == iam_policy.GetIamPolicyRequest() + assert args[0] == iam_policy_pb2.GetIamPolicyRequest() # 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 - assert response.etag == b"etag_blob" @@ -2145,12 +2198,27 @@ def test_get_iam_policy_from_dict(): test_get_iam_policy(request_type=dict) +def test_get_iam_policy_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 = CloudTasksClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: + client.get_iam_policy() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.GetIamPolicyRequest() + + @pytest.mark.asyncio async def test_get_iam_policy_async( - transport: str = "grpc_asyncio", request_type=iam_policy.GetIamPolicyRequest + transport: str = "grpc_asyncio", request_type=iam_policy_pb2.GetIamPolicyRequest ): client = CloudTasksAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -2161,22 +2229,18 @@ async def test_get_iam_policy_async( 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) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - - assert args[0] == iam_policy.GetIamPolicyRequest() + assert args[0] == iam_policy_pb2.GetIamPolicyRequest() # 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 - assert response.etag == b"etag_blob" @@ -2186,17 +2250,17 @@ async def test_get_iam_policy_async_from_dict(): def test_get_iam_policy_field_headers(): - client = CloudTasksClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value 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) # Establish that the underlying gRPC stub method was called. @@ -2211,17 +2275,17 @@ def test_get_iam_policy_field_headers(): @pytest.mark.asyncio async def test_get_iam_policy_field_headers_async(): - client = CloudTasksAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value 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) # Establish that the underlying gRPC stub method was called. @@ -2235,29 +2299,27 @@ async def test_get_iam_policy_field_headers_async(): def test_get_iam_policy_from_dict_foreign(): - client = CloudTasksClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksClient(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() def test_get_iam_policy_flattened(): - client = CloudTasksClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksClient(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() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.get_iam_policy(resource="resource_value",) @@ -2266,31 +2328,30 @@ def test_get_iam_policy_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].resource == "resource_value" def test_get_iam_policy_flattened_error(): - client = CloudTasksClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): client.get_iam_policy( - iam_policy.GetIamPolicyRequest(), resource="resource_value", + iam_policy_pb2.GetIamPolicyRequest(), resource="resource_value", ) @pytest.mark.asyncio async def test_get_iam_policy_flattened_async(): - client = CloudTasksAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksAsyncClient(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() - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy.Policy()) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. response = await client.get_iam_policy(resource="resource_value",) @@ -2299,27 +2360,26 @@ async def test_get_iam_policy_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].resource == "resource_value" @pytest.mark.asyncio async def test_get_iam_policy_flattened_error_async(): - client = CloudTasksAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): await client.get_iam_policy( - iam_policy.GetIamPolicyRequest(), resource="resource_value", + iam_policy_pb2.GetIamPolicyRequest(), resource="resource_value", ) def test_set_iam_policy( - transport: str = "grpc", request_type=iam_policy.SetIamPolicyRequest + transport: str = "grpc", request_type=iam_policy_pb2.SetIamPolicyRequest ): client = CloudTasksClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -2329,22 +2389,17 @@ def test_set_iam_policy( # 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) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - - assert args[0] == iam_policy.SetIamPolicyRequest() + assert args[0] == iam_policy_pb2.SetIamPolicyRequest() # 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 - assert response.etag == b"etag_blob" @@ -2352,12 +2407,27 @@ def test_set_iam_policy_from_dict(): test_set_iam_policy(request_type=dict) +def test_set_iam_policy_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 = CloudTasksClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + client.set_iam_policy() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.SetIamPolicyRequest() + + @pytest.mark.asyncio async def test_set_iam_policy_async( - transport: str = "grpc_asyncio", request_type=iam_policy.SetIamPolicyRequest + transport: str = "grpc_asyncio", request_type=iam_policy_pb2.SetIamPolicyRequest ): client = CloudTasksAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -2368,22 +2438,18 @@ async def test_set_iam_policy_async( 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) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - - assert args[0] == iam_policy.SetIamPolicyRequest() + assert args[0] == iam_policy_pb2.SetIamPolicyRequest() # 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 - assert response.etag == b"etag_blob" @@ -2393,17 +2459,17 @@ async def test_set_iam_policy_async_from_dict(): def test_set_iam_policy_field_headers(): - client = CloudTasksClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value 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) # Establish that the underlying gRPC stub method was called. @@ -2418,17 +2484,17 @@ def test_set_iam_policy_field_headers(): @pytest.mark.asyncio async def test_set_iam_policy_field_headers_async(): - client = CloudTasksAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value 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) # Establish that the underlying gRPC stub method was called. @@ -2442,29 +2508,27 @@ async def test_set_iam_policy_field_headers_async(): def test_set_iam_policy_from_dict_foreign(): - client = CloudTasksClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksClient(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() def test_set_iam_policy_flattened(): - client = CloudTasksClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksClient(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() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.set_iam_policy(resource="resource_value",) @@ -2473,31 +2537,30 @@ def test_set_iam_policy_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].resource == "resource_value" def test_set_iam_policy_flattened_error(): - client = CloudTasksClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): client.set_iam_policy( - iam_policy.SetIamPolicyRequest(), resource="resource_value", + iam_policy_pb2.SetIamPolicyRequest(), resource="resource_value", ) @pytest.mark.asyncio async def test_set_iam_policy_flattened_async(): - client = CloudTasksAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksAsyncClient(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() - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy.Policy()) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. response = await client.set_iam_policy(resource="resource_value",) @@ -2506,27 +2569,26 @@ async def test_set_iam_policy_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].resource == "resource_value" @pytest.mark.asyncio async def test_set_iam_policy_flattened_error_async(): - client = CloudTasksAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): await client.set_iam_policy( - iam_policy.SetIamPolicyRequest(), resource="resource_value", + iam_policy_pb2.SetIamPolicyRequest(), resource="resource_value", ) def test_test_iam_permissions( - transport: str = "grpc", request_type=iam_policy.TestIamPermissionsRequest + transport: str = "grpc", request_type=iam_policy_pb2.TestIamPermissionsRequest ): client = CloudTasksClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -2538,22 +2600,18 @@ def test_test_iam_permissions( 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"], ) - 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] == iam_policy.TestIamPermissionsRequest() + assert args[0] == iam_policy_pb2.TestIamPermissionsRequest() # 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"] @@ -2561,12 +2619,30 @@ def test_test_iam_permissions_from_dict(): test_test_iam_permissions(request_type=dict) +def test_test_iam_permissions_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 = CloudTasksClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + client.test_iam_permissions() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.TestIamPermissionsRequest() + + @pytest.mark.asyncio async def test_test_iam_permissions_async( - transport: str = "grpc_asyncio", request_type=iam_policy.TestIamPermissionsRequest + transport: str = "grpc_asyncio", + request_type=iam_policy_pb2.TestIamPermissionsRequest, ): client = CloudTasksAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -2579,20 +2655,19 @@ async def test_test_iam_permissions_async( ) 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) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - - assert args[0] == iam_policy.TestIamPermissionsRequest() + assert args[0] == iam_policy_pb2.TestIamPermissionsRequest() # 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"] @@ -2602,19 +2677,19 @@ async def test_test_iam_permissions_async_from_dict(): def test_test_iam_permissions_field_headers(): - client = CloudTasksClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value 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) # Establish that the underlying gRPC stub method was called. @@ -2629,11 +2704,12 @@ def test_test_iam_permissions_field_headers(): @pytest.mark.asyncio async def test_test_iam_permissions_field_headers_async(): - client = CloudTasksAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value 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. @@ -2641,9 +2717,8 @@ 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) # Establish that the underlying gRPC stub method was called. @@ -2657,14 +2732,13 @@ async def test_test_iam_permissions_field_headers_async(): def test_test_iam_permissions_from_dict_foreign(): - client = CloudTasksClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksClient(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={ "resource": "resource_value", @@ -2675,15 +2749,14 @@ def test_test_iam_permissions_from_dict_foreign(): def test_test_iam_permissions_flattened(): - client = CloudTasksClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksClient(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() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.test_iam_permissions( @@ -2694,20 +2767,18 @@ def test_test_iam_permissions_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].resource == "resource_value" - assert args[0].permissions == ["permissions_value"] def test_test_iam_permissions_flattened_error(): - client = CloudTasksClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): client.test_iam_permissions( - iam_policy.TestIamPermissionsRequest(), + iam_policy_pb2.TestIamPermissionsRequest(), resource="resource_value", permissions=["permissions_value"], ) @@ -2715,17 +2786,17 @@ def test_test_iam_permissions_flattened_error(): @pytest.mark.asyncio async def test_test_iam_permissions_flattened_async(): - client = CloudTasksAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksAsyncClient(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() call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - iam_policy.TestIamPermissionsResponse() + iam_policy_pb2.TestIamPermissionsResponse() ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. @@ -2737,21 +2808,19 @@ async def test_test_iam_permissions_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].resource == "resource_value" - assert args[0].permissions == ["permissions_value"] @pytest.mark.asyncio async def test_test_iam_permissions_flattened_error_async(): - client = CloudTasksAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): await client.test_iam_permissions( - iam_policy.TestIamPermissionsRequest(), + iam_policy_pb2.TestIamPermissionsRequest(), resource="resource_value", permissions=["permissions_value"], ) @@ -2759,7 +2828,7 @@ async def test_test_iam_permissions_flattened_error_async(): def test_list_tasks(transport: str = "grpc", request_type=cloudtasks.ListTasksRequest): client = CloudTasksClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -2772,19 +2841,15 @@ def test_list_tasks(transport: str = "grpc", request_type=cloudtasks.ListTasksRe call.return_value = cloudtasks.ListTasksResponse( next_page_token="next_page_token_value", ) - response = client.list_tasks(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == cloudtasks.ListTasksRequest() # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListTasksPager) - assert response.next_page_token == "next_page_token_value" @@ -2792,12 +2857,27 @@ def test_list_tasks_from_dict(): test_list_tasks(request_type=dict) +def test_list_tasks_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 = CloudTasksClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_tasks), "__call__") as call: + client.list_tasks() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == cloudtasks.ListTasksRequest() + + @pytest.mark.asyncio async def test_list_tasks_async( transport: str = "grpc_asyncio", request_type=cloudtasks.ListTasksRequest ): client = CloudTasksAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -2810,18 +2890,15 @@ async def test_list_tasks_async( call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( cloudtasks.ListTasksResponse(next_page_token="next_page_token_value",) ) - response = await client.list_tasks(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == cloudtasks.ListTasksRequest() # Establish that the response is the type that we expect. assert isinstance(response, pagers.ListTasksAsyncPager) - assert response.next_page_token == "next_page_token_value" @@ -2831,17 +2908,17 @@ async def test_list_tasks_async_from_dict(): def test_list_tasks_field_headers(): - client = CloudTasksClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = cloudtasks.ListTasksRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_tasks), "__call__") as call: call.return_value = cloudtasks.ListTasksResponse() - client.list_tasks(request) # Establish that the underlying gRPC stub method was called. @@ -2856,11 +2933,12 @@ def test_list_tasks_field_headers(): @pytest.mark.asyncio async def test_list_tasks_field_headers_async(): - client = CloudTasksAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = cloudtasks.ListTasksRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -2868,7 +2946,6 @@ async def test_list_tasks_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( cloudtasks.ListTasksResponse() ) - await client.list_tasks(request) # Establish that the underlying gRPC stub method was called. @@ -2882,13 +2959,12 @@ async def test_list_tasks_field_headers_async(): def test_list_tasks_flattened(): - client = CloudTasksClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_tasks), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = cloudtasks.ListTasksResponse() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.list_tasks(parent="parent_value",) @@ -2897,12 +2973,11 @@ def test_list_tasks_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" def test_list_tasks_flattened_error(): - client = CloudTasksClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -2914,7 +2989,7 @@ def test_list_tasks_flattened_error(): @pytest.mark.asyncio async def test_list_tasks_flattened_async(): - client = CloudTasksAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_tasks), "__call__") as call: @@ -2932,13 +3007,12 @@ async def test_list_tasks_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_tasks_flattened_error_async(): - client = CloudTasksAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -2949,7 +3023,7 @@ async def test_list_tasks_flattened_error_async(): def test_list_tasks_pager(): - client = CloudTasksClient(credentials=credentials.AnonymousCredentials,) + client = CloudTasksClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_tasks), "__call__") as call: @@ -2978,7 +3052,7 @@ def test_list_tasks_pager(): def test_list_tasks_pages(): - client = CloudTasksClient(credentials=credentials.AnonymousCredentials,) + client = CloudTasksClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_tasks), "__call__") as call: @@ -2999,7 +3073,7 @@ def test_list_tasks_pages(): @pytest.mark.asyncio async def test_list_tasks_async_pager(): - client = CloudTasksAsyncClient(credentials=credentials.AnonymousCredentials,) + client = CloudTasksAsyncClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -3027,7 +3101,7 @@ async def test_list_tasks_async_pager(): @pytest.mark.asyncio async def test_list_tasks_async_pages(): - client = CloudTasksAsyncClient(credentials=credentials.AnonymousCredentials,) + client = CloudTasksAsyncClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -3052,7 +3126,7 @@ async def test_list_tasks_async_pages(): def test_get_task(transport: str = "grpc", request_type=cloudtasks.GetTaskRequest): client = CloudTasksClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -3071,25 +3145,18 @@ def test_get_task(transport: str = "grpc", request_type=cloudtasks.GetTaskReques http_method=target.HttpMethod.POST ), ) - response = client.get_task(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == cloudtasks.GetTaskRequest() # Establish that the response is the type that we expect. - assert isinstance(response, task.Task) - assert response.name == "name_value" - assert response.dispatch_count == 1496 - assert response.response_count == 1527 - assert response.view == task.Task.View.BASIC @@ -3097,12 +3164,27 @@ def test_get_task_from_dict(): test_get_task(request_type=dict) +def test_get_task_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 = CloudTasksClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_task), "__call__") as call: + client.get_task() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == cloudtasks.GetTaskRequest() + + @pytest.mark.asyncio async def test_get_task_async( transport: str = "grpc_asyncio", request_type=cloudtasks.GetTaskRequest ): client = CloudTasksAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -3120,24 +3202,18 @@ async def test_get_task_async( view=task.Task.View.BASIC, ) ) - response = await client.get_task(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == cloudtasks.GetTaskRequest() # Establish that the response is the type that we expect. assert isinstance(response, task.Task) - assert response.name == "name_value" - assert response.dispatch_count == 1496 - assert response.response_count == 1527 - assert response.view == task.Task.View.BASIC @@ -3147,17 +3223,17 @@ async def test_get_task_async_from_dict(): def test_get_task_field_headers(): - client = CloudTasksClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = cloudtasks.GetTaskRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_task), "__call__") as call: call.return_value = task.Task() - client.get_task(request) # Establish that the underlying gRPC stub method was called. @@ -3172,17 +3248,17 @@ def test_get_task_field_headers(): @pytest.mark.asyncio async def test_get_task_field_headers_async(): - client = CloudTasksAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = cloudtasks.GetTaskRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_task), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(task.Task()) - await client.get_task(request) # Establish that the underlying gRPC stub method was called. @@ -3196,13 +3272,12 @@ async def test_get_task_field_headers_async(): def test_get_task_flattened(): - client = CloudTasksClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_task), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = task.Task() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.get_task(name="name_value",) @@ -3211,12 +3286,11 @@ def test_get_task_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" def test_get_task_flattened_error(): - client = CloudTasksClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -3228,7 +3302,7 @@ def test_get_task_flattened_error(): @pytest.mark.asyncio async def test_get_task_flattened_async(): - client = CloudTasksAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_task), "__call__") as call: @@ -3244,13 +3318,12 @@ async def test_get_task_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_task_flattened_error_async(): - client = CloudTasksAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -3264,7 +3337,7 @@ def test_create_task( transport: str = "grpc", request_type=cloudtasks.CreateTaskRequest ): client = CloudTasksClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -3283,25 +3356,18 @@ def test_create_task( http_method=target.HttpMethod.POST ), ) - response = client.create_task(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == cloudtasks.CreateTaskRequest() # Establish that the response is the type that we expect. - assert isinstance(response, gct_task.Task) - assert response.name == "name_value" - assert response.dispatch_count == 1496 - assert response.response_count == 1527 - assert response.view == gct_task.Task.View.BASIC @@ -3309,12 +3375,27 @@ def test_create_task_from_dict(): test_create_task(request_type=dict) +def test_create_task_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 = CloudTasksClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.create_task), "__call__") as call: + client.create_task() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == cloudtasks.CreateTaskRequest() + + @pytest.mark.asyncio async def test_create_task_async( transport: str = "grpc_asyncio", request_type=cloudtasks.CreateTaskRequest ): client = CloudTasksAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -3332,24 +3413,18 @@ async def test_create_task_async( view=gct_task.Task.View.BASIC, ) ) - response = await client.create_task(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == cloudtasks.CreateTaskRequest() # Establish that the response is the type that we expect. assert isinstance(response, gct_task.Task) - assert response.name == "name_value" - assert response.dispatch_count == 1496 - assert response.response_count == 1527 - assert response.view == gct_task.Task.View.BASIC @@ -3359,17 +3434,17 @@ async def test_create_task_async_from_dict(): def test_create_task_field_headers(): - client = CloudTasksClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = cloudtasks.CreateTaskRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.create_task), "__call__") as call: call.return_value = gct_task.Task() - client.create_task(request) # Establish that the underlying gRPC stub method was called. @@ -3384,17 +3459,17 @@ def test_create_task_field_headers(): @pytest.mark.asyncio async def test_create_task_field_headers_async(): - client = CloudTasksAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = cloudtasks.CreateTaskRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.create_task), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gct_task.Task()) - await client.create_task(request) # Establish that the underlying gRPC stub method was called. @@ -3408,13 +3483,12 @@ async def test_create_task_field_headers_async(): def test_create_task_flattened(): - client = CloudTasksClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.create_task), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = gct_task.Task() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.create_task( @@ -3425,14 +3499,12 @@ def test_create_task_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" - assert args[0].task == gct_task.Task(name="name_value") def test_create_task_flattened_error(): - client = CloudTasksClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -3446,7 +3518,7 @@ def test_create_task_flattened_error(): @pytest.mark.asyncio async def test_create_task_flattened_async(): - client = CloudTasksAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.create_task), "__call__") as call: @@ -3464,15 +3536,13 @@ async def test_create_task_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" - assert args[0].task == gct_task.Task(name="name_value") @pytest.mark.asyncio async def test_create_task_flattened_error_async(): - client = CloudTasksAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -3488,7 +3558,7 @@ def test_delete_task( transport: str = "grpc", request_type=cloudtasks.DeleteTaskRequest ): client = CloudTasksClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -3499,13 +3569,11 @@ def test_delete_task( with mock.patch.object(type(client.transport.delete_task), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = None - response = client.delete_task(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == cloudtasks.DeleteTaskRequest() # Establish that the response is the type that we expect. @@ -3516,12 +3584,27 @@ def test_delete_task_from_dict(): test_delete_task(request_type=dict) +def test_delete_task_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 = CloudTasksClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_task), "__call__") as call: + client.delete_task() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == cloudtasks.DeleteTaskRequest() + + @pytest.mark.asyncio async def test_delete_task_async( transport: str = "grpc_asyncio", request_type=cloudtasks.DeleteTaskRequest ): client = CloudTasksAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -3532,13 +3615,11 @@ async def test_delete_task_async( with mock.patch.object(type(client.transport.delete_task), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_task(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == cloudtasks.DeleteTaskRequest() # Establish that the response is the type that we expect. @@ -3551,17 +3632,17 @@ async def test_delete_task_async_from_dict(): def test_delete_task_field_headers(): - client = CloudTasksClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = cloudtasks.DeleteTaskRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.delete_task), "__call__") as call: call.return_value = None - client.delete_task(request) # Establish that the underlying gRPC stub method was called. @@ -3576,17 +3657,17 @@ def test_delete_task_field_headers(): @pytest.mark.asyncio async def test_delete_task_field_headers_async(): - client = CloudTasksAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = cloudtasks.DeleteTaskRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.delete_task), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_task(request) # Establish that the underlying gRPC stub method was called. @@ -3600,13 +3681,12 @@ async def test_delete_task_field_headers_async(): def test_delete_task_flattened(): - client = CloudTasksClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.delete_task), "__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_task(name="name_value",) @@ -3615,12 +3695,11 @@ def test_delete_task_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" def test_delete_task_flattened_error(): - client = CloudTasksClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -3632,7 +3711,7 @@ def test_delete_task_flattened_error(): @pytest.mark.asyncio async def test_delete_task_flattened_async(): - client = CloudTasksAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.delete_task), "__call__") as call: @@ -3648,13 +3727,12 @@ async def test_delete_task_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_task_flattened_error_async(): - client = CloudTasksAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -3666,7 +3744,7 @@ async def test_delete_task_flattened_error_async(): def test_run_task(transport: str = "grpc", request_type=cloudtasks.RunTaskRequest): client = CloudTasksClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -3685,25 +3763,18 @@ def test_run_task(transport: str = "grpc", request_type=cloudtasks.RunTaskReques http_method=target.HttpMethod.POST ), ) - response = client.run_task(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == cloudtasks.RunTaskRequest() # Establish that the response is the type that we expect. - assert isinstance(response, task.Task) - assert response.name == "name_value" - assert response.dispatch_count == 1496 - assert response.response_count == 1527 - assert response.view == task.Task.View.BASIC @@ -3711,12 +3782,27 @@ def test_run_task_from_dict(): test_run_task(request_type=dict) +def test_run_task_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 = CloudTasksClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.run_task), "__call__") as call: + client.run_task() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == cloudtasks.RunTaskRequest() + + @pytest.mark.asyncio async def test_run_task_async( transport: str = "grpc_asyncio", request_type=cloudtasks.RunTaskRequest ): client = CloudTasksAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -3734,24 +3820,18 @@ async def test_run_task_async( view=task.Task.View.BASIC, ) ) - response = await client.run_task(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == cloudtasks.RunTaskRequest() # Establish that the response is the type that we expect. assert isinstance(response, task.Task) - assert response.name == "name_value" - assert response.dispatch_count == 1496 - assert response.response_count == 1527 - assert response.view == task.Task.View.BASIC @@ -3761,17 +3841,17 @@ async def test_run_task_async_from_dict(): def test_run_task_field_headers(): - client = CloudTasksClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = cloudtasks.RunTaskRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.run_task), "__call__") as call: call.return_value = task.Task() - client.run_task(request) # Establish that the underlying gRPC stub method was called. @@ -3786,17 +3866,17 @@ def test_run_task_field_headers(): @pytest.mark.asyncio async def test_run_task_field_headers_async(): - client = CloudTasksAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = cloudtasks.RunTaskRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.run_task), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(task.Task()) - await client.run_task(request) # Establish that the underlying gRPC stub method was called. @@ -3810,13 +3890,12 @@ async def test_run_task_field_headers_async(): def test_run_task_flattened(): - client = CloudTasksClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.run_task), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = task.Task() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.run_task(name="name_value",) @@ -3825,12 +3904,11 @@ def test_run_task_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" def test_run_task_flattened_error(): - client = CloudTasksClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -3842,7 +3920,7 @@ def test_run_task_flattened_error(): @pytest.mark.asyncio async def test_run_task_flattened_async(): - client = CloudTasksAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.run_task), "__call__") as call: @@ -3858,13 +3936,12 @@ async def test_run_task_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_run_task_flattened_error_async(): - client = CloudTasksAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -3877,16 +3954,16 @@ async def test_run_task_flattened_error_async(): def test_credentials_transport_error(): # It is an error to provide credentials and a transport instance. transport = transports.CloudTasksGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = CloudTasksClient( - 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.CloudTasksGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = CloudTasksClient( @@ -3896,7 +3973,7 @@ def test_credentials_transport_error(): # It is an error to provide scopes and a transport instance. transport = transports.CloudTasksGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = CloudTasksClient( @@ -3907,7 +3984,7 @@ def test_credentials_transport_error(): def test_transport_instance(): # A client may be instantiated with a custom transport instance. transport = transports.CloudTasksGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) client = CloudTasksClient(transport=transport) assert client.transport is transport @@ -3916,13 +3993,13 @@ def test_transport_instance(): def test_transport_get_channel(): # A client may be instantiated with a custom transport instance. transport = transports.CloudTasksGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) channel = transport.grpc_channel assert channel transport = transports.CloudTasksGrpcAsyncIOTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) channel = transport.grpc_channel assert channel @@ -3934,23 +4011,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 = CloudTasksClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksClient(credentials=ga_credentials.AnonymousCredentials(),) assert isinstance(client.transport, transports.CloudTasksGrpcTransport,) def test_cloud_tasks_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.CloudTasksTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), credentials_file="credentials.json", ) @@ -3962,7 +4039,7 @@ def test_cloud_tasks_base_transport(): ) as Transport: Transport.return_value = None transport = transports.CloudTasksTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Every method on the transport should just blindly @@ -3990,15 +4067,37 @@ def test_cloud_tasks_base_transport(): getattr(transport, method)(request=object()) +@requires_google_auth_gte_1_25_0 def test_cloud_tasks_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.cloud.tasks_v2.services.cloud_tasks.transports.CloudTasksTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.CloudTasksTransport( + 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",), + quota_project_id="octopus", + ) + + +@requires_google_auth_lt_1_25_0 +def test_cloud_tasks_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.cloud.tasks_v2.services.cloud_tasks.transports.CloudTasksTransport._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.CloudTasksTransport( credentials_file="credentials.json", quota_project_id="octopus", ) @@ -4011,19 +4110,33 @@ def test_cloud_tasks_base_transport_with_credentials_file(): def test_cloud_tasks_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.cloud.tasks_v2.services.cloud_tasks.transports.CloudTasksTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - adc.return_value = (credentials.AnonymousCredentials(), None) + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.CloudTasksTransport() adc.assert_called_once() +@requires_google_auth_gte_1_25_0 def test_cloud_tasks_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) + CloudTasksClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=("https://www.googleapis.com/auth/cloud-platform",), + quota_project_id=None, + ) + + +@requires_google_auth_lt_1_25_0 +def test_cloud_tasks_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) CloudTasksClient() adc.assert_called_once_with( scopes=("https://www.googleapis.com/auth/cloud-platform",), @@ -4031,26 +4144,156 @@ def test_cloud_tasks_auth_adc(): ) -def test_cloud_tasks_transport_auth_adc(): +@pytest.mark.parametrize( + "transport_class", + [transports.CloudTasksGrpcTransport, transports.CloudTasksGrpcAsyncIOTransport,], +) +@requires_google_auth_gte_1_25_0 +def test_cloud_tasks_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.CloudTasksGrpcTransport( - 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",), + quota_project_id="octopus", ) + + +@pytest.mark.parametrize( + "transport_class", + [transports.CloudTasksGrpcTransport, transports.CloudTasksGrpcAsyncIOTransport,], +) +@requires_google_auth_lt_1_25_0 +def test_cloud_tasks_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",), quota_project_id="octopus", ) +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.CloudTasksGrpcTransport, grpc_helpers), + (transports.CloudTasksGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_gte_1_26_0 +def test_cloud_tasks_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( + "cloudtasks.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + default_scopes=("https://www.googleapis.com/auth/cloud-platform",), + scopes=["1", "2"], + default_host="cloudtasks.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.CloudTasksGrpcTransport, grpc_helpers), + (transports.CloudTasksGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_cloud_tasks_transport_create_channel_old_api_core( + transport_class, grpc_helpers +): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class(quota_project_id="octopus") + + create_channel.assert_called_with( + "cloudtasks.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + scopes=("https://www.googleapis.com/auth/cloud-platform",), + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.CloudTasksGrpcTransport, grpc_helpers), + (transports.CloudTasksGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_cloud_tasks_transport_create_channel_user_scopes( + transport_class, grpc_helpers +): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + + create_channel.assert_called_with( + "cloudtasks.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + scopes=["1", "2"], + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + @pytest.mark.parametrize( "transport_class", [transports.CloudTasksGrpcTransport, transports.CloudTasksGrpcAsyncIOTransport], ) def test_cloud_tasks_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: @@ -4089,7 +4332,7 @@ def test_cloud_tasks_grpc_transport_client_cert_source_for_mtls(transport_class) def test_cloud_tasks_host_no_port(): client = CloudTasksClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="cloudtasks.googleapis.com" ), @@ -4099,7 +4342,7 @@ def test_cloud_tasks_host_no_port(): def test_cloud_tasks_host_with_port(): client = CloudTasksClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="cloudtasks.googleapis.com:8000" ), @@ -4150,9 +4393,9 @@ def test_cloud_tasks_transport_channel_mtls_with_client_cert_source(transport_cl 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", @@ -4227,7 +4470,6 @@ def test_queue_path(): project = "squid" location = "clam" queue = "whelk" - expected = "projects/{project}/locations/{location}/queues/{queue}".format( project=project, location=location, queue=queue, ) @@ -4253,7 +4495,6 @@ def test_task_path(): location = "mussel" queue = "winkle" task = "nautilus" - expected = "projects/{project}/locations/{location}/queues/{queue}/tasks/{task}".format( project=project, location=location, queue=queue, task=task, ) @@ -4277,7 +4518,6 @@ def test_parse_task_path(): def test_common_billing_account_path(): billing_account = "whelk" - expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -4298,7 +4538,6 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): folder = "oyster" - expected = "folders/{folder}".format(folder=folder,) actual = CloudTasksClient.common_folder_path(folder) assert expected == actual @@ -4317,7 +4556,6 @@ def test_parse_common_folder_path(): def test_common_organization_path(): organization = "cuttlefish" - expected = "organizations/{organization}".format(organization=organization,) actual = CloudTasksClient.common_organization_path(organization) assert expected == actual @@ -4336,7 +4574,6 @@ def test_parse_common_organization_path(): def test_common_project_path(): project = "winkle" - expected = "projects/{project}".format(project=project,) actual = CloudTasksClient.common_project_path(project) assert expected == actual @@ -4356,7 +4593,6 @@ def test_parse_common_project_path(): def test_common_location_path(): project = "scallop" location = "abalone" - expected = "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -4383,7 +4619,7 @@ def test_client_withDEFAULT_CLIENT_INFO(): transports.CloudTasksTransport, "_prep_wrapped_messages" ) as prep: client = CloudTasksClient( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) @@ -4392,6 +4628,6 @@ def test_client_withDEFAULT_CLIENT_INFO(): ) as prep: transport_class = CloudTasksClient.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) diff --git a/tests/unit/gapic/tasks_v2beta2/__init__.py b/tests/unit/gapic/tasks_v2beta2/__init__.py index 8b137891..4de65971 100644 --- a/tests/unit/gapic/tasks_v2beta2/__init__.py +++ b/tests/unit/gapic/tasks_v2beta2/__init__.py @@ -1 +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/tasks_v2beta2/test_cloud_tasks.py b/tests/unit/gapic/tasks_v2beta2/test_cloud_tasks.py index 555e14aa..8a11b7fb 100644 --- a/tests/unit/gapic/tasks_v2beta2/test_cloud_tasks.py +++ b/tests/unit/gapic/tasks_v2beta2/test_cloud_tasks.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,34 +23,64 @@ 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.cloud.tasks_v2beta2.services.cloud_tasks import CloudTasksAsyncClient from google.cloud.tasks_v2beta2.services.cloud_tasks import CloudTasksClient from google.cloud.tasks_v2beta2.services.cloud_tasks import pagers from google.cloud.tasks_v2beta2.services.cloud_tasks import transports +from google.cloud.tasks_v2beta2.services.cloud_tasks.transports.base import ( + _API_CORE_VERSION, +) +from google.cloud.tasks_v2beta2.services.cloud_tasks.transports.base import ( + _GOOGLE_AUTH_VERSION, +) from google.cloud.tasks_v2beta2.types import cloudtasks from google.cloud.tasks_v2beta2.types import queue from google.cloud.tasks_v2beta2.types import queue as gct_queue from google.cloud.tasks_v2beta2.types import target from google.cloud.tasks_v2beta2.types import task from google.cloud.tasks_v2beta2.types import task as gct_task -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 any_pb2 as gp_any # 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.rpc import status_pb2 as status # type: ignore -from google.type import expr_pb2 as expr # type: ignore +from google.protobuf import any_pb2 # type: ignore +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from google.rpc import status_pb2 # type: ignore +from google.type import expr_pb2 # type: ignore +import google.auth + + +# TODO(busunkim): Once google-api-core >= 1.26.0 is required: +# - Delete all the api-core and auth "less than" test cases +# - Delete these pytest markers (Make the "greater than or equal to" tests the default). +requires_google_auth_lt_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), + reason="This test requires google-auth < 1.25.0", +) +requires_google_auth_gte_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) < packaging.version.parse("1.25.0"), + reason="This test requires google-auth >= 1.25.0", +) + +requires_api_core_lt_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) >= packaging.version.parse("1.26.0"), + reason="This test requires google-api-core < 1.26.0", +) + +requires_api_core_gte_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) < packaging.version.parse("1.26.0"), + reason="This test requires google-api-core >= 1.26.0", +) def client_cert_source_callback(): @@ -95,31 +124,35 @@ def test__get_default_mtls_endpoint(): assert CloudTasksClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi -def test_cloud_tasks_client_from_service_account_info(): - creds = credentials.AnonymousCredentials() +@pytest.mark.parametrize("client_class", [CloudTasksClient, CloudTasksAsyncClient,]) +def test_cloud_tasks_client_from_service_account_info(client_class): + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_info" ) as factory: factory.return_value = creds info = {"valid": True} - client = CloudTasksClient.from_service_account_info(info) + client = client_class.from_service_account_info(info) assert client.transport._credentials == creds + assert isinstance(client, client_class) assert client.transport._host == "cloudtasks.googleapis.com:443" @pytest.mark.parametrize("client_class", [CloudTasksClient, CloudTasksAsyncClient,]) def test_cloud_tasks_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: 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 == "cloudtasks.googleapis.com:443" @@ -159,7 +192,7 @@ def test_cloud_tasks_client_client_options( ): # Check that if channel is provided we won't create a new one. with mock.patch.object(CloudTasksClient, "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() @@ -443,7 +476,7 @@ def test_list_queues( transport: str = "grpc", request_type=cloudtasks.ListQueuesRequest ): client = CloudTasksClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -456,19 +489,15 @@ def test_list_queues( call.return_value = cloudtasks.ListQueuesResponse( next_page_token="next_page_token_value", ) - response = client.list_queues(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == cloudtasks.ListQueuesRequest() # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListQueuesPager) - assert response.next_page_token == "next_page_token_value" @@ -476,12 +505,27 @@ def test_list_queues_from_dict(): test_list_queues(request_type=dict) +def test_list_queues_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 = CloudTasksClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_queues), "__call__") as call: + client.list_queues() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == cloudtasks.ListQueuesRequest() + + @pytest.mark.asyncio async def test_list_queues_async( transport: str = "grpc_asyncio", request_type=cloudtasks.ListQueuesRequest ): client = CloudTasksAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -494,18 +538,15 @@ async def test_list_queues_async( call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( cloudtasks.ListQueuesResponse(next_page_token="next_page_token_value",) ) - response = await client.list_queues(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == cloudtasks.ListQueuesRequest() # Establish that the response is the type that we expect. assert isinstance(response, pagers.ListQueuesAsyncPager) - assert response.next_page_token == "next_page_token_value" @@ -515,17 +556,17 @@ async def test_list_queues_async_from_dict(): def test_list_queues_field_headers(): - client = CloudTasksClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = cloudtasks.ListQueuesRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_queues), "__call__") as call: call.return_value = cloudtasks.ListQueuesResponse() - client.list_queues(request) # Establish that the underlying gRPC stub method was called. @@ -540,11 +581,12 @@ def test_list_queues_field_headers(): @pytest.mark.asyncio async def test_list_queues_field_headers_async(): - client = CloudTasksAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = cloudtasks.ListQueuesRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -552,7 +594,6 @@ async def test_list_queues_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( cloudtasks.ListQueuesResponse() ) - await client.list_queues(request) # Establish that the underlying gRPC stub method was called. @@ -566,13 +607,12 @@ async def test_list_queues_field_headers_async(): def test_list_queues_flattened(): - client = CloudTasksClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_queues), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = cloudtasks.ListQueuesResponse() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.list_queues(parent="parent_value",) @@ -581,12 +621,11 @@ def test_list_queues_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" def test_list_queues_flattened_error(): - client = CloudTasksClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -598,7 +637,7 @@ def test_list_queues_flattened_error(): @pytest.mark.asyncio async def test_list_queues_flattened_async(): - client = CloudTasksAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_queues), "__call__") as call: @@ -616,13 +655,12 @@ async def test_list_queues_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_queues_flattened_error_async(): - client = CloudTasksAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -633,7 +671,7 @@ async def test_list_queues_flattened_error_async(): def test_list_queues_pager(): - client = CloudTasksClient(credentials=credentials.AnonymousCredentials,) + client = CloudTasksClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_queues), "__call__") as call: @@ -665,7 +703,7 @@ def test_list_queues_pager(): def test_list_queues_pages(): - client = CloudTasksClient(credentials=credentials.AnonymousCredentials,) + client = CloudTasksClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_queues), "__call__") as call: @@ -689,7 +727,7 @@ def test_list_queues_pages(): @pytest.mark.asyncio async def test_list_queues_async_pager(): - client = CloudTasksAsyncClient(credentials=credentials.AnonymousCredentials,) + client = CloudTasksAsyncClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -720,7 +758,7 @@ async def test_list_queues_async_pager(): @pytest.mark.asyncio async def test_list_queues_async_pages(): - client = CloudTasksAsyncClient(credentials=credentials.AnonymousCredentials,) + client = CloudTasksAsyncClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -748,7 +786,7 @@ async def test_list_queues_async_pages(): def test_get_queue(transport: str = "grpc", request_type=cloudtasks.GetQueueRequest): client = CloudTasksClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -767,21 +805,16 @@ def test_get_queue(transport: str = "grpc", request_type=cloudtasks.GetQueueRequ ) ), ) - response = client.get_queue(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == cloudtasks.GetQueueRequest() # Establish that the response is the type that we expect. - assert isinstance(response, queue.Queue) - assert response.name == "name_value" - assert response.state == queue.Queue.State.RUNNING @@ -789,12 +822,27 @@ def test_get_queue_from_dict(): test_get_queue(request_type=dict) +def test_get_queue_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 = CloudTasksClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_queue), "__call__") as call: + client.get_queue() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == cloudtasks.GetQueueRequest() + + @pytest.mark.asyncio async def test_get_queue_async( transport: str = "grpc_asyncio", request_type=cloudtasks.GetQueueRequest ): client = CloudTasksAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -807,20 +855,16 @@ async def test_get_queue_async( call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( queue.Queue(name="name_value", state=queue.Queue.State.RUNNING,) ) - response = await client.get_queue(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == cloudtasks.GetQueueRequest() # Establish that the response is the type that we expect. assert isinstance(response, queue.Queue) - assert response.name == "name_value" - assert response.state == queue.Queue.State.RUNNING @@ -830,17 +874,17 @@ async def test_get_queue_async_from_dict(): def test_get_queue_field_headers(): - client = CloudTasksClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = cloudtasks.GetQueueRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_queue), "__call__") as call: call.return_value = queue.Queue() - client.get_queue(request) # Establish that the underlying gRPC stub method was called. @@ -855,17 +899,17 @@ def test_get_queue_field_headers(): @pytest.mark.asyncio async def test_get_queue_field_headers_async(): - client = CloudTasksAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = cloudtasks.GetQueueRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_queue), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(queue.Queue()) - await client.get_queue(request) # Establish that the underlying gRPC stub method was called. @@ -879,13 +923,12 @@ async def test_get_queue_field_headers_async(): def test_get_queue_flattened(): - client = CloudTasksClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_queue), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = queue.Queue() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.get_queue(name="name_value",) @@ -894,12 +937,11 @@ def test_get_queue_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" def test_get_queue_flattened_error(): - client = CloudTasksClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -911,7 +953,7 @@ def test_get_queue_flattened_error(): @pytest.mark.asyncio async def test_get_queue_flattened_async(): - client = CloudTasksAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_queue), "__call__") as call: @@ -927,13 +969,12 @@ async def test_get_queue_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_queue_flattened_error_async(): - client = CloudTasksAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -947,7 +988,7 @@ def test_create_queue( transport: str = "grpc", request_type=cloudtasks.CreateQueueRequest ): client = CloudTasksClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -966,21 +1007,16 @@ def test_create_queue( ) ), ) - response = client.create_queue(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == cloudtasks.CreateQueueRequest() # Establish that the response is the type that we expect. - assert isinstance(response, gct_queue.Queue) - assert response.name == "name_value" - assert response.state == gct_queue.Queue.State.RUNNING @@ -988,12 +1024,27 @@ def test_create_queue_from_dict(): test_create_queue(request_type=dict) +def test_create_queue_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 = CloudTasksClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.create_queue), "__call__") as call: + client.create_queue() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == cloudtasks.CreateQueueRequest() + + @pytest.mark.asyncio async def test_create_queue_async( transport: str = "grpc_asyncio", request_type=cloudtasks.CreateQueueRequest ): client = CloudTasksAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1006,20 +1057,16 @@ async def test_create_queue_async( call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( gct_queue.Queue(name="name_value", state=gct_queue.Queue.State.RUNNING,) ) - response = await client.create_queue(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == cloudtasks.CreateQueueRequest() # Establish that the response is the type that we expect. assert isinstance(response, gct_queue.Queue) - assert response.name == "name_value" - assert response.state == gct_queue.Queue.State.RUNNING @@ -1029,17 +1076,17 @@ async def test_create_queue_async_from_dict(): def test_create_queue_field_headers(): - client = CloudTasksClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = cloudtasks.CreateQueueRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.create_queue), "__call__") as call: call.return_value = gct_queue.Queue() - client.create_queue(request) # Establish that the underlying gRPC stub method was called. @@ -1054,17 +1101,17 @@ def test_create_queue_field_headers(): @pytest.mark.asyncio async def test_create_queue_field_headers_async(): - client = CloudTasksAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = cloudtasks.CreateQueueRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.create_queue), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gct_queue.Queue()) - await client.create_queue(request) # Establish that the underlying gRPC stub method was called. @@ -1078,13 +1125,12 @@ async def test_create_queue_field_headers_async(): def test_create_queue_flattened(): - client = CloudTasksClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.create_queue), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = gct_queue.Queue() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.create_queue( @@ -1095,14 +1141,12 @@ def test_create_queue_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" - assert args[0].queue == gct_queue.Queue(name="name_value") def test_create_queue_flattened_error(): - client = CloudTasksClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1116,7 +1160,7 @@ def test_create_queue_flattened_error(): @pytest.mark.asyncio async def test_create_queue_flattened_async(): - client = CloudTasksAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.create_queue), "__call__") as call: @@ -1134,15 +1178,13 @@ async def test_create_queue_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" - assert args[0].queue == gct_queue.Queue(name="name_value") @pytest.mark.asyncio async def test_create_queue_flattened_error_async(): - client = CloudTasksAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1158,7 +1200,7 @@ def test_update_queue( transport: str = "grpc", request_type=cloudtasks.UpdateQueueRequest ): client = CloudTasksClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1177,21 +1219,16 @@ def test_update_queue( ) ), ) - response = client.update_queue(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == cloudtasks.UpdateQueueRequest() # Establish that the response is the type that we expect. - assert isinstance(response, gct_queue.Queue) - assert response.name == "name_value" - assert response.state == gct_queue.Queue.State.RUNNING @@ -1199,12 +1236,27 @@ def test_update_queue_from_dict(): test_update_queue(request_type=dict) +def test_update_queue_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 = CloudTasksClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.update_queue), "__call__") as call: + client.update_queue() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == cloudtasks.UpdateQueueRequest() + + @pytest.mark.asyncio async def test_update_queue_async( transport: str = "grpc_asyncio", request_type=cloudtasks.UpdateQueueRequest ): client = CloudTasksAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1217,20 +1269,16 @@ async def test_update_queue_async( call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( gct_queue.Queue(name="name_value", state=gct_queue.Queue.State.RUNNING,) ) - response = await client.update_queue(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == cloudtasks.UpdateQueueRequest() # Establish that the response is the type that we expect. assert isinstance(response, gct_queue.Queue) - assert response.name == "name_value" - assert response.state == gct_queue.Queue.State.RUNNING @@ -1240,17 +1288,17 @@ async def test_update_queue_async_from_dict(): def test_update_queue_field_headers(): - client = CloudTasksClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = cloudtasks.UpdateQueueRequest() + request.queue.name = "queue.name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.update_queue), "__call__") as call: call.return_value = gct_queue.Queue() - client.update_queue(request) # Establish that the underlying gRPC stub method was called. @@ -1265,17 +1313,17 @@ def test_update_queue_field_headers(): @pytest.mark.asyncio async def test_update_queue_field_headers_async(): - client = CloudTasksAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = cloudtasks.UpdateQueueRequest() + request.queue.name = "queue.name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.update_queue), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gct_queue.Queue()) - await client.update_queue(request) # Establish that the underlying gRPC stub method was called. @@ -1289,32 +1337,29 @@ async def test_update_queue_field_headers_async(): def test_update_queue_flattened(): - client = CloudTasksClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.update_queue), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = gct_queue.Queue() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.update_queue( queue=gct_queue.Queue(name="name_value"), - update_mask=field_mask.FieldMask(paths=["paths_value"]), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].queue == gct_queue.Queue(name="name_value") - - assert args[0].update_mask == field_mask.FieldMask(paths=["paths_value"]) + assert args[0].update_mask == field_mask_pb2.FieldMask(paths=["paths_value"]) def test_update_queue_flattened_error(): - client = CloudTasksClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1322,13 +1367,13 @@ def test_update_queue_flattened_error(): client.update_queue( cloudtasks.UpdateQueueRequest(), queue=gct_queue.Queue(name="name_value"), - update_mask=field_mask.FieldMask(paths=["paths_value"]), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) @pytest.mark.asyncio async def test_update_queue_flattened_async(): - client = CloudTasksAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.update_queue), "__call__") as call: @@ -1340,22 +1385,20 @@ async def test_update_queue_flattened_async(): # using the keyword arguments to the method. response = await client.update_queue( queue=gct_queue.Queue(name="name_value"), - update_mask=field_mask.FieldMask(paths=["paths_value"]), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].queue == gct_queue.Queue(name="name_value") - - assert args[0].update_mask == field_mask.FieldMask(paths=["paths_value"]) + assert args[0].update_mask == field_mask_pb2.FieldMask(paths=["paths_value"]) @pytest.mark.asyncio async def test_update_queue_flattened_error_async(): - client = CloudTasksAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1363,7 +1406,7 @@ async def test_update_queue_flattened_error_async(): await client.update_queue( cloudtasks.UpdateQueueRequest(), queue=gct_queue.Queue(name="name_value"), - update_mask=field_mask.FieldMask(paths=["paths_value"]), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) @@ -1371,7 +1414,7 @@ def test_delete_queue( transport: str = "grpc", request_type=cloudtasks.DeleteQueueRequest ): client = CloudTasksClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1382,13 +1425,11 @@ def test_delete_queue( with mock.patch.object(type(client.transport.delete_queue), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = None - response = client.delete_queue(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == cloudtasks.DeleteQueueRequest() # Establish that the response is the type that we expect. @@ -1399,12 +1440,27 @@ def test_delete_queue_from_dict(): test_delete_queue(request_type=dict) +def test_delete_queue_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 = CloudTasksClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_queue), "__call__") as call: + client.delete_queue() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == cloudtasks.DeleteQueueRequest() + + @pytest.mark.asyncio async def test_delete_queue_async( transport: str = "grpc_asyncio", request_type=cloudtasks.DeleteQueueRequest ): client = CloudTasksAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1415,13 +1471,11 @@ async def test_delete_queue_async( with mock.patch.object(type(client.transport.delete_queue), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_queue(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == cloudtasks.DeleteQueueRequest() # Establish that the response is the type that we expect. @@ -1434,17 +1488,17 @@ async def test_delete_queue_async_from_dict(): def test_delete_queue_field_headers(): - client = CloudTasksClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = cloudtasks.DeleteQueueRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.delete_queue), "__call__") as call: call.return_value = None - client.delete_queue(request) # Establish that the underlying gRPC stub method was called. @@ -1459,17 +1513,17 @@ def test_delete_queue_field_headers(): @pytest.mark.asyncio async def test_delete_queue_field_headers_async(): - client = CloudTasksAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = cloudtasks.DeleteQueueRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.delete_queue), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_queue(request) # Establish that the underlying gRPC stub method was called. @@ -1483,13 +1537,12 @@ async def test_delete_queue_field_headers_async(): def test_delete_queue_flattened(): - client = CloudTasksClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.delete_queue), "__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_queue(name="name_value",) @@ -1498,12 +1551,11 @@ def test_delete_queue_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" def test_delete_queue_flattened_error(): - client = CloudTasksClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1515,7 +1567,7 @@ def test_delete_queue_flattened_error(): @pytest.mark.asyncio async def test_delete_queue_flattened_async(): - client = CloudTasksAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.delete_queue), "__call__") as call: @@ -1531,13 +1583,12 @@ async def test_delete_queue_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_queue_flattened_error_async(): - client = CloudTasksAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1551,7 +1602,7 @@ def test_purge_queue( transport: str = "grpc", request_type=cloudtasks.PurgeQueueRequest ): client = CloudTasksClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1570,21 +1621,16 @@ def test_purge_queue( ) ), ) - response = client.purge_queue(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == cloudtasks.PurgeQueueRequest() # Establish that the response is the type that we expect. - assert isinstance(response, queue.Queue) - assert response.name == "name_value" - assert response.state == queue.Queue.State.RUNNING @@ -1592,12 +1638,27 @@ def test_purge_queue_from_dict(): test_purge_queue(request_type=dict) +def test_purge_queue_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 = CloudTasksClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.purge_queue), "__call__") as call: + client.purge_queue() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == cloudtasks.PurgeQueueRequest() + + @pytest.mark.asyncio async def test_purge_queue_async( transport: str = "grpc_asyncio", request_type=cloudtasks.PurgeQueueRequest ): client = CloudTasksAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1610,20 +1671,16 @@ async def test_purge_queue_async( call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( queue.Queue(name="name_value", state=queue.Queue.State.RUNNING,) ) - response = await client.purge_queue(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == cloudtasks.PurgeQueueRequest() # Establish that the response is the type that we expect. assert isinstance(response, queue.Queue) - assert response.name == "name_value" - assert response.state == queue.Queue.State.RUNNING @@ -1633,17 +1690,17 @@ async def test_purge_queue_async_from_dict(): def test_purge_queue_field_headers(): - client = CloudTasksClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = cloudtasks.PurgeQueueRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.purge_queue), "__call__") as call: call.return_value = queue.Queue() - client.purge_queue(request) # Establish that the underlying gRPC stub method was called. @@ -1658,17 +1715,17 @@ def test_purge_queue_field_headers(): @pytest.mark.asyncio async def test_purge_queue_field_headers_async(): - client = CloudTasksAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = cloudtasks.PurgeQueueRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.purge_queue), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(queue.Queue()) - await client.purge_queue(request) # Establish that the underlying gRPC stub method was called. @@ -1682,13 +1739,12 @@ async def test_purge_queue_field_headers_async(): def test_purge_queue_flattened(): - client = CloudTasksClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.purge_queue), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = queue.Queue() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.purge_queue(name="name_value",) @@ -1697,12 +1753,11 @@ def test_purge_queue_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" def test_purge_queue_flattened_error(): - client = CloudTasksClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1714,7 +1769,7 @@ def test_purge_queue_flattened_error(): @pytest.mark.asyncio async def test_purge_queue_flattened_async(): - client = CloudTasksAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.purge_queue), "__call__") as call: @@ -1730,13 +1785,12 @@ async def test_purge_queue_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_purge_queue_flattened_error_async(): - client = CloudTasksAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1750,7 +1804,7 @@ def test_pause_queue( transport: str = "grpc", request_type=cloudtasks.PauseQueueRequest ): client = CloudTasksClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1769,21 +1823,16 @@ def test_pause_queue( ) ), ) - response = client.pause_queue(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == cloudtasks.PauseQueueRequest() # Establish that the response is the type that we expect. - assert isinstance(response, queue.Queue) - assert response.name == "name_value" - assert response.state == queue.Queue.State.RUNNING @@ -1791,12 +1840,27 @@ def test_pause_queue_from_dict(): test_pause_queue(request_type=dict) +def test_pause_queue_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 = CloudTasksClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.pause_queue), "__call__") as call: + client.pause_queue() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == cloudtasks.PauseQueueRequest() + + @pytest.mark.asyncio async def test_pause_queue_async( transport: str = "grpc_asyncio", request_type=cloudtasks.PauseQueueRequest ): client = CloudTasksAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1809,20 +1873,16 @@ async def test_pause_queue_async( call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( queue.Queue(name="name_value", state=queue.Queue.State.RUNNING,) ) - response = await client.pause_queue(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == cloudtasks.PauseQueueRequest() # Establish that the response is the type that we expect. assert isinstance(response, queue.Queue) - assert response.name == "name_value" - assert response.state == queue.Queue.State.RUNNING @@ -1832,17 +1892,17 @@ async def test_pause_queue_async_from_dict(): def test_pause_queue_field_headers(): - client = CloudTasksClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = cloudtasks.PauseQueueRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.pause_queue), "__call__") as call: call.return_value = queue.Queue() - client.pause_queue(request) # Establish that the underlying gRPC stub method was called. @@ -1857,17 +1917,17 @@ def test_pause_queue_field_headers(): @pytest.mark.asyncio async def test_pause_queue_field_headers_async(): - client = CloudTasksAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = cloudtasks.PauseQueueRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.pause_queue), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(queue.Queue()) - await client.pause_queue(request) # Establish that the underlying gRPC stub method was called. @@ -1881,13 +1941,12 @@ async def test_pause_queue_field_headers_async(): def test_pause_queue_flattened(): - client = CloudTasksClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.pause_queue), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = queue.Queue() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.pause_queue(name="name_value",) @@ -1896,12 +1955,11 @@ def test_pause_queue_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" def test_pause_queue_flattened_error(): - client = CloudTasksClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1913,7 +1971,7 @@ def test_pause_queue_flattened_error(): @pytest.mark.asyncio async def test_pause_queue_flattened_async(): - client = CloudTasksAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.pause_queue), "__call__") as call: @@ -1929,13 +1987,12 @@ async def test_pause_queue_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_pause_queue_flattened_error_async(): - client = CloudTasksAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1949,7 +2006,7 @@ def test_resume_queue( transport: str = "grpc", request_type=cloudtasks.ResumeQueueRequest ): client = CloudTasksClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1968,21 +2025,16 @@ def test_resume_queue( ) ), ) - response = client.resume_queue(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == cloudtasks.ResumeQueueRequest() # Establish that the response is the type that we expect. - assert isinstance(response, queue.Queue) - assert response.name == "name_value" - assert response.state == queue.Queue.State.RUNNING @@ -1990,12 +2042,27 @@ def test_resume_queue_from_dict(): test_resume_queue(request_type=dict) +def test_resume_queue_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 = CloudTasksClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.resume_queue), "__call__") as call: + client.resume_queue() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == cloudtasks.ResumeQueueRequest() + + @pytest.mark.asyncio async def test_resume_queue_async( transport: str = "grpc_asyncio", request_type=cloudtasks.ResumeQueueRequest ): client = CloudTasksAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -2008,20 +2075,16 @@ async def test_resume_queue_async( call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( queue.Queue(name="name_value", state=queue.Queue.State.RUNNING,) ) - response = await client.resume_queue(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == cloudtasks.ResumeQueueRequest() # Establish that the response is the type that we expect. assert isinstance(response, queue.Queue) - assert response.name == "name_value" - assert response.state == queue.Queue.State.RUNNING @@ -2031,17 +2094,17 @@ async def test_resume_queue_async_from_dict(): def test_resume_queue_field_headers(): - client = CloudTasksClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = cloudtasks.ResumeQueueRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.resume_queue), "__call__") as call: call.return_value = queue.Queue() - client.resume_queue(request) # Establish that the underlying gRPC stub method was called. @@ -2056,17 +2119,17 @@ def test_resume_queue_field_headers(): @pytest.mark.asyncio async def test_resume_queue_field_headers_async(): - client = CloudTasksAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = cloudtasks.ResumeQueueRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.resume_queue), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(queue.Queue()) - await client.resume_queue(request) # Establish that the underlying gRPC stub method was called. @@ -2080,13 +2143,12 @@ async def test_resume_queue_field_headers_async(): def test_resume_queue_flattened(): - client = CloudTasksClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.resume_queue), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = queue.Queue() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.resume_queue(name="name_value",) @@ -2095,12 +2157,11 @@ def test_resume_queue_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" def test_resume_queue_flattened_error(): - client = CloudTasksClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -2112,7 +2173,7 @@ def test_resume_queue_flattened_error(): @pytest.mark.asyncio async def test_resume_queue_flattened_async(): - client = CloudTasksAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.resume_queue), "__call__") as call: @@ -2128,13 +2189,12 @@ async def test_resume_queue_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_resume_queue_flattened_error_async(): - client = CloudTasksAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -2145,10 +2205,10 @@ async def test_resume_queue_flattened_error_async(): def test_get_iam_policy( - transport: str = "grpc", request_type=iam_policy.GetIamPolicyRequest + transport: str = "grpc", request_type=iam_policy_pb2.GetIamPolicyRequest ): client = CloudTasksClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -2158,22 +2218,17 @@ def test_get_iam_policy( # 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) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - - assert args[0] == iam_policy.GetIamPolicyRequest() + assert args[0] == iam_policy_pb2.GetIamPolicyRequest() # 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 - assert response.etag == b"etag_blob" @@ -2181,12 +2236,27 @@ def test_get_iam_policy_from_dict(): test_get_iam_policy(request_type=dict) +def test_get_iam_policy_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 = CloudTasksClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: + client.get_iam_policy() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.GetIamPolicyRequest() + + @pytest.mark.asyncio async def test_get_iam_policy_async( - transport: str = "grpc_asyncio", request_type=iam_policy.GetIamPolicyRequest + transport: str = "grpc_asyncio", request_type=iam_policy_pb2.GetIamPolicyRequest ): client = CloudTasksAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -2197,22 +2267,18 @@ async def test_get_iam_policy_async( 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) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - - assert args[0] == iam_policy.GetIamPolicyRequest() + assert args[0] == iam_policy_pb2.GetIamPolicyRequest() # 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 - assert response.etag == b"etag_blob" @@ -2222,17 +2288,17 @@ async def test_get_iam_policy_async_from_dict(): def test_get_iam_policy_field_headers(): - client = CloudTasksClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value 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) # Establish that the underlying gRPC stub method was called. @@ -2247,17 +2313,17 @@ def test_get_iam_policy_field_headers(): @pytest.mark.asyncio async def test_get_iam_policy_field_headers_async(): - client = CloudTasksAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value 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) # Establish that the underlying gRPC stub method was called. @@ -2271,29 +2337,27 @@ async def test_get_iam_policy_field_headers_async(): def test_get_iam_policy_from_dict_foreign(): - client = CloudTasksClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksClient(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() def test_get_iam_policy_flattened(): - client = CloudTasksClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksClient(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() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.get_iam_policy(resource="resource_value",) @@ -2302,31 +2366,30 @@ def test_get_iam_policy_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].resource == "resource_value" def test_get_iam_policy_flattened_error(): - client = CloudTasksClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): client.get_iam_policy( - iam_policy.GetIamPolicyRequest(), resource="resource_value", + iam_policy_pb2.GetIamPolicyRequest(), resource="resource_value", ) @pytest.mark.asyncio async def test_get_iam_policy_flattened_async(): - client = CloudTasksAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksAsyncClient(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() - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy.Policy()) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. response = await client.get_iam_policy(resource="resource_value",) @@ -2335,27 +2398,26 @@ async def test_get_iam_policy_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].resource == "resource_value" @pytest.mark.asyncio async def test_get_iam_policy_flattened_error_async(): - client = CloudTasksAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): await client.get_iam_policy( - iam_policy.GetIamPolicyRequest(), resource="resource_value", + iam_policy_pb2.GetIamPolicyRequest(), resource="resource_value", ) def test_set_iam_policy( - transport: str = "grpc", request_type=iam_policy.SetIamPolicyRequest + transport: str = "grpc", request_type=iam_policy_pb2.SetIamPolicyRequest ): client = CloudTasksClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -2365,22 +2427,17 @@ def test_set_iam_policy( # 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) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - - assert args[0] == iam_policy.SetIamPolicyRequest() + assert args[0] == iam_policy_pb2.SetIamPolicyRequest() # 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 - assert response.etag == b"etag_blob" @@ -2388,38 +2445,49 @@ def test_set_iam_policy_from_dict(): test_set_iam_policy(request_type=dict) -@pytest.mark.asyncio -async def test_set_iam_policy_async( - transport: str = "grpc_asyncio", request_type=iam_policy.SetIamPolicyRequest -): - client = CloudTasksAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, +def test_set_iam_policy_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 = CloudTasksClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() + # 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: + client.set_iam_policy() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.SetIamPolicyRequest() + + +@pytest.mark.asyncio +async def test_set_iam_policy_async( + transport: str = "grpc_asyncio", request_type=iam_policy_pb2.SetIamPolicyRequest +): + client = CloudTasksAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() # 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) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - - assert args[0] == iam_policy.SetIamPolicyRequest() + assert args[0] == iam_policy_pb2.SetIamPolicyRequest() # 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 - assert response.etag == b"etag_blob" @@ -2429,17 +2497,17 @@ async def test_set_iam_policy_async_from_dict(): def test_set_iam_policy_field_headers(): - client = CloudTasksClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value 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) # Establish that the underlying gRPC stub method was called. @@ -2454,17 +2522,17 @@ def test_set_iam_policy_field_headers(): @pytest.mark.asyncio async def test_set_iam_policy_field_headers_async(): - client = CloudTasksAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value 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) # Establish that the underlying gRPC stub method was called. @@ -2478,29 +2546,27 @@ async def test_set_iam_policy_field_headers_async(): def test_set_iam_policy_from_dict_foreign(): - client = CloudTasksClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksClient(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() def test_set_iam_policy_flattened(): - client = CloudTasksClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksClient(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() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.set_iam_policy(resource="resource_value",) @@ -2509,31 +2575,30 @@ def test_set_iam_policy_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].resource == "resource_value" def test_set_iam_policy_flattened_error(): - client = CloudTasksClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): client.set_iam_policy( - iam_policy.SetIamPolicyRequest(), resource="resource_value", + iam_policy_pb2.SetIamPolicyRequest(), resource="resource_value", ) @pytest.mark.asyncio async def test_set_iam_policy_flattened_async(): - client = CloudTasksAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksAsyncClient(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() - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy.Policy()) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. response = await client.set_iam_policy(resource="resource_value",) @@ -2542,27 +2607,26 @@ async def test_set_iam_policy_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].resource == "resource_value" @pytest.mark.asyncio async def test_set_iam_policy_flattened_error_async(): - client = CloudTasksAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): await client.set_iam_policy( - iam_policy.SetIamPolicyRequest(), resource="resource_value", + iam_policy_pb2.SetIamPolicyRequest(), resource="resource_value", ) def test_test_iam_permissions( - transport: str = "grpc", request_type=iam_policy.TestIamPermissionsRequest + transport: str = "grpc", request_type=iam_policy_pb2.TestIamPermissionsRequest ): client = CloudTasksClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -2574,22 +2638,18 @@ def test_test_iam_permissions( 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"], ) - 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] == iam_policy.TestIamPermissionsRequest() + assert args[0] == iam_policy_pb2.TestIamPermissionsRequest() # 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"] @@ -2597,12 +2657,30 @@ def test_test_iam_permissions_from_dict(): test_test_iam_permissions(request_type=dict) +def test_test_iam_permissions_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 = CloudTasksClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + client.test_iam_permissions() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.TestIamPermissionsRequest() + + @pytest.mark.asyncio async def test_test_iam_permissions_async( - transport: str = "grpc_asyncio", request_type=iam_policy.TestIamPermissionsRequest + transport: str = "grpc_asyncio", + request_type=iam_policy_pb2.TestIamPermissionsRequest, ): client = CloudTasksAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -2615,20 +2693,19 @@ async def test_test_iam_permissions_async( ) 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) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - - assert args[0] == iam_policy.TestIamPermissionsRequest() + assert args[0] == iam_policy_pb2.TestIamPermissionsRequest() # 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"] @@ -2638,19 +2715,19 @@ async def test_test_iam_permissions_async_from_dict(): def test_test_iam_permissions_field_headers(): - client = CloudTasksClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value 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) # Establish that the underlying gRPC stub method was called. @@ -2665,11 +2742,12 @@ def test_test_iam_permissions_field_headers(): @pytest.mark.asyncio async def test_test_iam_permissions_field_headers_async(): - client = CloudTasksAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value 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. @@ -2677,9 +2755,8 @@ 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) # Establish that the underlying gRPC stub method was called. @@ -2693,14 +2770,13 @@ async def test_test_iam_permissions_field_headers_async(): def test_test_iam_permissions_from_dict_foreign(): - client = CloudTasksClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksClient(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={ "resource": "resource_value", @@ -2711,15 +2787,14 @@ def test_test_iam_permissions_from_dict_foreign(): def test_test_iam_permissions_flattened(): - client = CloudTasksClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksClient(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() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.test_iam_permissions( @@ -2730,20 +2805,18 @@ def test_test_iam_permissions_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].resource == "resource_value" - assert args[0].permissions == ["permissions_value"] def test_test_iam_permissions_flattened_error(): - client = CloudTasksClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): client.test_iam_permissions( - iam_policy.TestIamPermissionsRequest(), + iam_policy_pb2.TestIamPermissionsRequest(), resource="resource_value", permissions=["permissions_value"], ) @@ -2751,17 +2824,17 @@ def test_test_iam_permissions_flattened_error(): @pytest.mark.asyncio async def test_test_iam_permissions_flattened_async(): - client = CloudTasksAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksAsyncClient(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() call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - iam_policy.TestIamPermissionsResponse() + iam_policy_pb2.TestIamPermissionsResponse() ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. @@ -2773,21 +2846,19 @@ async def test_test_iam_permissions_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].resource == "resource_value" - assert args[0].permissions == ["permissions_value"] @pytest.mark.asyncio async def test_test_iam_permissions_flattened_error_async(): - client = CloudTasksAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): await client.test_iam_permissions( - iam_policy.TestIamPermissionsRequest(), + iam_policy_pb2.TestIamPermissionsRequest(), resource="resource_value", permissions=["permissions_value"], ) @@ -2795,7 +2866,7 @@ async def test_test_iam_permissions_flattened_error_async(): def test_list_tasks(transport: str = "grpc", request_type=cloudtasks.ListTasksRequest): client = CloudTasksClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -2808,19 +2879,15 @@ def test_list_tasks(transport: str = "grpc", request_type=cloudtasks.ListTasksRe call.return_value = cloudtasks.ListTasksResponse( next_page_token="next_page_token_value", ) - response = client.list_tasks(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == cloudtasks.ListTasksRequest() # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListTasksPager) - assert response.next_page_token == "next_page_token_value" @@ -2828,12 +2895,27 @@ def test_list_tasks_from_dict(): test_list_tasks(request_type=dict) +def test_list_tasks_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 = CloudTasksClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_tasks), "__call__") as call: + client.list_tasks() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == cloudtasks.ListTasksRequest() + + @pytest.mark.asyncio async def test_list_tasks_async( transport: str = "grpc_asyncio", request_type=cloudtasks.ListTasksRequest ): client = CloudTasksAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -2846,18 +2928,15 @@ async def test_list_tasks_async( call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( cloudtasks.ListTasksResponse(next_page_token="next_page_token_value",) ) - response = await client.list_tasks(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == cloudtasks.ListTasksRequest() # Establish that the response is the type that we expect. assert isinstance(response, pagers.ListTasksAsyncPager) - assert response.next_page_token == "next_page_token_value" @@ -2867,17 +2946,17 @@ async def test_list_tasks_async_from_dict(): def test_list_tasks_field_headers(): - client = CloudTasksClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = cloudtasks.ListTasksRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_tasks), "__call__") as call: call.return_value = cloudtasks.ListTasksResponse() - client.list_tasks(request) # Establish that the underlying gRPC stub method was called. @@ -2892,11 +2971,12 @@ def test_list_tasks_field_headers(): @pytest.mark.asyncio async def test_list_tasks_field_headers_async(): - client = CloudTasksAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = cloudtasks.ListTasksRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -2904,7 +2984,6 @@ async def test_list_tasks_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( cloudtasks.ListTasksResponse() ) - await client.list_tasks(request) # Establish that the underlying gRPC stub method was called. @@ -2918,13 +2997,12 @@ async def test_list_tasks_field_headers_async(): def test_list_tasks_flattened(): - client = CloudTasksClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_tasks), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = cloudtasks.ListTasksResponse() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.list_tasks(parent="parent_value",) @@ -2933,12 +3011,11 @@ def test_list_tasks_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" def test_list_tasks_flattened_error(): - client = CloudTasksClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -2950,7 +3027,7 @@ def test_list_tasks_flattened_error(): @pytest.mark.asyncio async def test_list_tasks_flattened_async(): - client = CloudTasksAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_tasks), "__call__") as call: @@ -2968,13 +3045,12 @@ async def test_list_tasks_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_tasks_flattened_error_async(): - client = CloudTasksAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -2985,7 +3061,7 @@ async def test_list_tasks_flattened_error_async(): def test_list_tasks_pager(): - client = CloudTasksClient(credentials=credentials.AnonymousCredentials,) + client = CloudTasksClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_tasks), "__call__") as call: @@ -3014,7 +3090,7 @@ def test_list_tasks_pager(): def test_list_tasks_pages(): - client = CloudTasksClient(credentials=credentials.AnonymousCredentials,) + client = CloudTasksClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_tasks), "__call__") as call: @@ -3035,7 +3111,7 @@ def test_list_tasks_pages(): @pytest.mark.asyncio async def test_list_tasks_async_pager(): - client = CloudTasksAsyncClient(credentials=credentials.AnonymousCredentials,) + client = CloudTasksAsyncClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -3063,7 +3139,7 @@ async def test_list_tasks_async_pager(): @pytest.mark.asyncio async def test_list_tasks_async_pages(): - client = CloudTasksAsyncClient(credentials=credentials.AnonymousCredentials,) + client = CloudTasksAsyncClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -3088,7 +3164,7 @@ async def test_list_tasks_async_pages(): def test_get_task(transport: str = "grpc", request_type=cloudtasks.GetTaskRequest): client = CloudTasksClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -3105,21 +3181,16 @@ def test_get_task(transport: str = "grpc", request_type=cloudtasks.GetTaskReques http_method=target.HttpMethod.POST ), ) - response = client.get_task(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == cloudtasks.GetTaskRequest() # Establish that the response is the type that we expect. - assert isinstance(response, task.Task) - assert response.name == "name_value" - assert response.view == task.Task.View.BASIC @@ -3127,12 +3198,27 @@ def test_get_task_from_dict(): test_get_task(request_type=dict) +def test_get_task_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 = CloudTasksClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_task), "__call__") as call: + client.get_task() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == cloudtasks.GetTaskRequest() + + @pytest.mark.asyncio async def test_get_task_async( transport: str = "grpc_asyncio", request_type=cloudtasks.GetTaskRequest ): client = CloudTasksAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -3145,20 +3231,16 @@ async def test_get_task_async( call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( task.Task(name="name_value", view=task.Task.View.BASIC,) ) - response = await client.get_task(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == cloudtasks.GetTaskRequest() # Establish that the response is the type that we expect. assert isinstance(response, task.Task) - assert response.name == "name_value" - assert response.view == task.Task.View.BASIC @@ -3168,17 +3250,17 @@ async def test_get_task_async_from_dict(): def test_get_task_field_headers(): - client = CloudTasksClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = cloudtasks.GetTaskRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_task), "__call__") as call: call.return_value = task.Task() - client.get_task(request) # Establish that the underlying gRPC stub method was called. @@ -3193,17 +3275,17 @@ def test_get_task_field_headers(): @pytest.mark.asyncio async def test_get_task_field_headers_async(): - client = CloudTasksAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = cloudtasks.GetTaskRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_task), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(task.Task()) - await client.get_task(request) # Establish that the underlying gRPC stub method was called. @@ -3217,13 +3299,12 @@ async def test_get_task_field_headers_async(): def test_get_task_flattened(): - client = CloudTasksClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_task), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = task.Task() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.get_task(name="name_value",) @@ -3232,12 +3313,11 @@ def test_get_task_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" def test_get_task_flattened_error(): - client = CloudTasksClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -3249,7 +3329,7 @@ def test_get_task_flattened_error(): @pytest.mark.asyncio async def test_get_task_flattened_async(): - client = CloudTasksAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_task), "__call__") as call: @@ -3265,13 +3345,12 @@ async def test_get_task_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_task_flattened_error_async(): - client = CloudTasksAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -3285,7 +3364,7 @@ def test_create_task( transport: str = "grpc", request_type=cloudtasks.CreateTaskRequest ): client = CloudTasksClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -3302,21 +3381,16 @@ def test_create_task( http_method=target.HttpMethod.POST ), ) - response = client.create_task(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == cloudtasks.CreateTaskRequest() # Establish that the response is the type that we expect. - assert isinstance(response, gct_task.Task) - assert response.name == "name_value" - assert response.view == gct_task.Task.View.BASIC @@ -3324,12 +3398,27 @@ def test_create_task_from_dict(): test_create_task(request_type=dict) +def test_create_task_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 = CloudTasksClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.create_task), "__call__") as call: + client.create_task() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == cloudtasks.CreateTaskRequest() + + @pytest.mark.asyncio async def test_create_task_async( transport: str = "grpc_asyncio", request_type=cloudtasks.CreateTaskRequest ): client = CloudTasksAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -3342,20 +3431,16 @@ async def test_create_task_async( call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( gct_task.Task(name="name_value", view=gct_task.Task.View.BASIC,) ) - response = await client.create_task(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == cloudtasks.CreateTaskRequest() # Establish that the response is the type that we expect. assert isinstance(response, gct_task.Task) - assert response.name == "name_value" - assert response.view == gct_task.Task.View.BASIC @@ -3365,17 +3450,17 @@ async def test_create_task_async_from_dict(): def test_create_task_field_headers(): - client = CloudTasksClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = cloudtasks.CreateTaskRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.create_task), "__call__") as call: call.return_value = gct_task.Task() - client.create_task(request) # Establish that the underlying gRPC stub method was called. @@ -3390,17 +3475,17 @@ def test_create_task_field_headers(): @pytest.mark.asyncio async def test_create_task_field_headers_async(): - client = CloudTasksAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = cloudtasks.CreateTaskRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.create_task), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gct_task.Task()) - await client.create_task(request) # Establish that the underlying gRPC stub method was called. @@ -3414,13 +3499,12 @@ async def test_create_task_field_headers_async(): def test_create_task_flattened(): - client = CloudTasksClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.create_task), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = gct_task.Task() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.create_task( @@ -3431,14 +3515,12 @@ def test_create_task_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" - assert args[0].task == gct_task.Task(name="name_value") def test_create_task_flattened_error(): - client = CloudTasksClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -3452,7 +3534,7 @@ def test_create_task_flattened_error(): @pytest.mark.asyncio async def test_create_task_flattened_async(): - client = CloudTasksAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.create_task), "__call__") as call: @@ -3470,15 +3552,13 @@ async def test_create_task_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" - assert args[0].task == gct_task.Task(name="name_value") @pytest.mark.asyncio async def test_create_task_flattened_error_async(): - client = CloudTasksAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -3494,7 +3574,7 @@ def test_delete_task( transport: str = "grpc", request_type=cloudtasks.DeleteTaskRequest ): client = CloudTasksClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -3505,13 +3585,11 @@ def test_delete_task( with mock.patch.object(type(client.transport.delete_task), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = None - response = client.delete_task(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == cloudtasks.DeleteTaskRequest() # Establish that the response is the type that we expect. @@ -3522,12 +3600,27 @@ def test_delete_task_from_dict(): test_delete_task(request_type=dict) +def test_delete_task_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 = CloudTasksClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_task), "__call__") as call: + client.delete_task() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == cloudtasks.DeleteTaskRequest() + + @pytest.mark.asyncio async def test_delete_task_async( transport: str = "grpc_asyncio", request_type=cloudtasks.DeleteTaskRequest ): client = CloudTasksAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -3538,13 +3631,11 @@ async def test_delete_task_async( with mock.patch.object(type(client.transport.delete_task), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_task(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == cloudtasks.DeleteTaskRequest() # Establish that the response is the type that we expect. @@ -3557,17 +3648,17 @@ async def test_delete_task_async_from_dict(): def test_delete_task_field_headers(): - client = CloudTasksClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = cloudtasks.DeleteTaskRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.delete_task), "__call__") as call: call.return_value = None - client.delete_task(request) # Establish that the underlying gRPC stub method was called. @@ -3582,17 +3673,17 @@ def test_delete_task_field_headers(): @pytest.mark.asyncio async def test_delete_task_field_headers_async(): - client = CloudTasksAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = cloudtasks.DeleteTaskRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.delete_task), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_task(request) # Establish that the underlying gRPC stub method was called. @@ -3606,13 +3697,12 @@ async def test_delete_task_field_headers_async(): def test_delete_task_flattened(): - client = CloudTasksClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.delete_task), "__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_task(name="name_value",) @@ -3621,12 +3711,11 @@ def test_delete_task_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" def test_delete_task_flattened_error(): - client = CloudTasksClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -3638,7 +3727,7 @@ def test_delete_task_flattened_error(): @pytest.mark.asyncio async def test_delete_task_flattened_async(): - client = CloudTasksAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.delete_task), "__call__") as call: @@ -3654,13 +3743,12 @@ async def test_delete_task_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_task_flattened_error_async(): - client = CloudTasksAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -3674,7 +3762,7 @@ def test_lease_tasks( transport: str = "grpc", request_type=cloudtasks.LeaseTasksRequest ): client = CloudTasksClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -3685,17 +3773,14 @@ def test_lease_tasks( with mock.patch.object(type(client.transport.lease_tasks), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = cloudtasks.LeaseTasksResponse() - response = client.lease_tasks(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == cloudtasks.LeaseTasksRequest() # Establish that the response is the type that we expect. - assert isinstance(response, cloudtasks.LeaseTasksResponse) @@ -3703,12 +3788,27 @@ def test_lease_tasks_from_dict(): test_lease_tasks(request_type=dict) +def test_lease_tasks_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 = CloudTasksClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.lease_tasks), "__call__") as call: + client.lease_tasks() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == cloudtasks.LeaseTasksRequest() + + @pytest.mark.asyncio async def test_lease_tasks_async( transport: str = "grpc_asyncio", request_type=cloudtasks.LeaseTasksRequest ): client = CloudTasksAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -3721,13 +3821,11 @@ async def test_lease_tasks_async( call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( cloudtasks.LeaseTasksResponse() ) - response = await client.lease_tasks(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == cloudtasks.LeaseTasksRequest() # Establish that the response is the type that we expect. @@ -3740,17 +3838,17 @@ async def test_lease_tasks_async_from_dict(): def test_lease_tasks_field_headers(): - client = CloudTasksClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = cloudtasks.LeaseTasksRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.lease_tasks), "__call__") as call: call.return_value = cloudtasks.LeaseTasksResponse() - client.lease_tasks(request) # Establish that the underlying gRPC stub method was called. @@ -3765,11 +3863,12 @@ def test_lease_tasks_field_headers(): @pytest.mark.asyncio async def test_lease_tasks_field_headers_async(): - client = CloudTasksAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = cloudtasks.LeaseTasksRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -3777,7 +3876,6 @@ async def test_lease_tasks_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( cloudtasks.LeaseTasksResponse() ) - await client.lease_tasks(request) # Establish that the underlying gRPC stub method was called. @@ -3791,33 +3889,28 @@ async def test_lease_tasks_field_headers_async(): def test_lease_tasks_flattened(): - client = CloudTasksClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.lease_tasks), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = cloudtasks.LeaseTasksResponse() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.lease_tasks( - parent="parent_value", lease_duration=duration.Duration(seconds=751), + parent="parent_value", lease_duration=duration_pb2.Duration(seconds=751), ) # 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 DurationRule().to_proto(args[0].lease_duration) == duration.Duration( - seconds=751 - ) + # assert args[0].lease_duration == duration_pb2.Duration(seconds=751) def test_lease_tasks_flattened_error(): - client = CloudTasksClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -3825,13 +3918,13 @@ def test_lease_tasks_flattened_error(): client.lease_tasks( cloudtasks.LeaseTasksRequest(), parent="parent_value", - lease_duration=duration.Duration(seconds=751), + lease_duration=duration_pb2.Duration(seconds=751), ) @pytest.mark.asyncio async def test_lease_tasks_flattened_async(): - client = CloudTasksAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.lease_tasks), "__call__") as call: @@ -3844,24 +3937,20 @@ async def test_lease_tasks_flattened_async(): # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. response = await client.lease_tasks( - parent="parent_value", lease_duration=duration.Duration(seconds=751), + parent="parent_value", lease_duration=duration_pb2.Duration(seconds=751), ) # 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 DurationRule().to_proto(args[0].lease_duration) == duration.Duration( - seconds=751 - ) + # assert args[0].lease_duration == duration_pb2.Duration(seconds=751) @pytest.mark.asyncio async def test_lease_tasks_flattened_error_async(): - client = CloudTasksAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -3869,7 +3958,7 @@ async def test_lease_tasks_flattened_error_async(): await client.lease_tasks( cloudtasks.LeaseTasksRequest(), parent="parent_value", - lease_duration=duration.Duration(seconds=751), + lease_duration=duration_pb2.Duration(seconds=751), ) @@ -3877,7 +3966,7 @@ def test_acknowledge_task( transport: str = "grpc", request_type=cloudtasks.AcknowledgeTaskRequest ): client = CloudTasksClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -3888,13 +3977,11 @@ def test_acknowledge_task( with mock.patch.object(type(client.transport.acknowledge_task), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = None - response = client.acknowledge_task(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == cloudtasks.AcknowledgeTaskRequest() # Establish that the response is the type that we expect. @@ -3905,12 +3992,27 @@ def test_acknowledge_task_from_dict(): test_acknowledge_task(request_type=dict) +def test_acknowledge_task_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 = CloudTasksClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.acknowledge_task), "__call__") as call: + client.acknowledge_task() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == cloudtasks.AcknowledgeTaskRequest() + + @pytest.mark.asyncio async def test_acknowledge_task_async( transport: str = "grpc_asyncio", request_type=cloudtasks.AcknowledgeTaskRequest ): client = CloudTasksAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -3921,13 +4023,11 @@ async def test_acknowledge_task_async( with mock.patch.object(type(client.transport.acknowledge_task), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.acknowledge_task(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == cloudtasks.AcknowledgeTaskRequest() # Establish that the response is the type that we expect. @@ -3940,17 +4040,17 @@ async def test_acknowledge_task_async_from_dict(): def test_acknowledge_task_field_headers(): - client = CloudTasksClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = cloudtasks.AcknowledgeTaskRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.acknowledge_task), "__call__") as call: call.return_value = None - client.acknowledge_task(request) # Establish that the underlying gRPC stub method was called. @@ -3965,17 +4065,17 @@ def test_acknowledge_task_field_headers(): @pytest.mark.asyncio async def test_acknowledge_task_field_headers_async(): - client = CloudTasksAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = cloudtasks.AcknowledgeTaskRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.acknowledge_task), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.acknowledge_task(request) # Establish that the underlying gRPC stub method was called. @@ -3989,33 +4089,28 @@ async def test_acknowledge_task_field_headers_async(): def test_acknowledge_task_flattened(): - client = CloudTasksClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.acknowledge_task), "__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_task( - name="name_value", schedule_time=timestamp.Timestamp(seconds=751), + name="name_value", schedule_time=timestamp_pb2.Timestamp(seconds=751), ) # 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 TimestampRule().to_proto(args[0].schedule_time) == timestamp.Timestamp( - seconds=751 - ) + # assert args[0].schedule_time == timestamp_pb2.Timestamp(seconds=751) def test_acknowledge_task_flattened_error(): - client = CloudTasksClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -4023,13 +4118,13 @@ def test_acknowledge_task_flattened_error(): client.acknowledge_task( cloudtasks.AcknowledgeTaskRequest(), name="name_value", - schedule_time=timestamp.Timestamp(seconds=751), + schedule_time=timestamp_pb2.Timestamp(seconds=751), ) @pytest.mark.asyncio async def test_acknowledge_task_flattened_async(): - client = CloudTasksAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.acknowledge_task), "__call__") as call: @@ -4040,24 +4135,20 @@ async def test_acknowledge_task_flattened_async(): # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. response = await client.acknowledge_task( - name="name_value", schedule_time=timestamp.Timestamp(seconds=751), + name="name_value", schedule_time=timestamp_pb2.Timestamp(seconds=751), ) # 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 TimestampRule().to_proto(args[0].schedule_time) == timestamp.Timestamp( - seconds=751 - ) + # assert args[0].schedule_time == timestamp_pb2.Timestamp(seconds=751) @pytest.mark.asyncio async def test_acknowledge_task_flattened_error_async(): - client = CloudTasksAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -4065,7 +4156,7 @@ async def test_acknowledge_task_flattened_error_async(): await client.acknowledge_task( cloudtasks.AcknowledgeTaskRequest(), name="name_value", - schedule_time=timestamp.Timestamp(seconds=751), + schedule_time=timestamp_pb2.Timestamp(seconds=751), ) @@ -4073,7 +4164,7 @@ def test_renew_lease( transport: str = "grpc", request_type=cloudtasks.RenewLeaseRequest ): client = CloudTasksClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -4090,21 +4181,16 @@ def test_renew_lease( http_method=target.HttpMethod.POST ), ) - response = client.renew_lease(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == cloudtasks.RenewLeaseRequest() # Establish that the response is the type that we expect. - assert isinstance(response, task.Task) - assert response.name == "name_value" - assert response.view == task.Task.View.BASIC @@ -4112,12 +4198,27 @@ def test_renew_lease_from_dict(): test_renew_lease(request_type=dict) +def test_renew_lease_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 = CloudTasksClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.renew_lease), "__call__") as call: + client.renew_lease() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == cloudtasks.RenewLeaseRequest() + + @pytest.mark.asyncio async def test_renew_lease_async( transport: str = "grpc_asyncio", request_type=cloudtasks.RenewLeaseRequest ): client = CloudTasksAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -4130,20 +4231,16 @@ async def test_renew_lease_async( call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( task.Task(name="name_value", view=task.Task.View.BASIC,) ) - response = await client.renew_lease(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == cloudtasks.RenewLeaseRequest() # Establish that the response is the type that we expect. assert isinstance(response, task.Task) - assert response.name == "name_value" - assert response.view == task.Task.View.BASIC @@ -4153,17 +4250,17 @@ async def test_renew_lease_async_from_dict(): def test_renew_lease_field_headers(): - client = CloudTasksClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = cloudtasks.RenewLeaseRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.renew_lease), "__call__") as call: call.return_value = task.Task() - client.renew_lease(request) # Establish that the underlying gRPC stub method was called. @@ -4178,17 +4275,17 @@ def test_renew_lease_field_headers(): @pytest.mark.asyncio async def test_renew_lease_field_headers_async(): - client = CloudTasksAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = cloudtasks.RenewLeaseRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.renew_lease), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(task.Task()) - await client.renew_lease(request) # Establish that the underlying gRPC stub method was called. @@ -4202,39 +4299,31 @@ async def test_renew_lease_field_headers_async(): def test_renew_lease_flattened(): - client = CloudTasksClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.renew_lease), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = task.Task() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.renew_lease( name="name_value", - schedule_time=timestamp.Timestamp(seconds=751), - lease_duration=duration.Duration(seconds=751), + schedule_time=timestamp_pb2.Timestamp(seconds=751), + lease_duration=duration_pb2.Duration(seconds=751), ) # 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 TimestampRule().to_proto(args[0].schedule_time) == timestamp.Timestamp( - seconds=751 - ) - - assert DurationRule().to_proto(args[0].lease_duration) == duration.Duration( - seconds=751 - ) + # assert args[0].schedule_time == timestamp_pb2.Timestamp(seconds=751) + # assert args[0].lease_duration == duration_pb2.Duration(seconds=751) def test_renew_lease_flattened_error(): - client = CloudTasksClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -4242,14 +4331,14 @@ def test_renew_lease_flattened_error(): client.renew_lease( cloudtasks.RenewLeaseRequest(), name="name_value", - schedule_time=timestamp.Timestamp(seconds=751), - lease_duration=duration.Duration(seconds=751), + schedule_time=timestamp_pb2.Timestamp(seconds=751), + lease_duration=duration_pb2.Duration(seconds=751), ) @pytest.mark.asyncio async def test_renew_lease_flattened_async(): - client = CloudTasksAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.renew_lease), "__call__") as call: @@ -4261,29 +4350,22 @@ async def test_renew_lease_flattened_async(): # using the keyword arguments to the method. response = await client.renew_lease( name="name_value", - schedule_time=timestamp.Timestamp(seconds=751), - lease_duration=duration.Duration(seconds=751), + schedule_time=timestamp_pb2.Timestamp(seconds=751), + lease_duration=duration_pb2.Duration(seconds=751), ) # 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 TimestampRule().to_proto(args[0].schedule_time) == timestamp.Timestamp( - seconds=751 - ) - - assert DurationRule().to_proto(args[0].lease_duration) == duration.Duration( - seconds=751 - ) + # assert args[0].schedule_time == timestamp_pb2.Timestamp(seconds=751) + # assert args[0].lease_duration == duration_pb2.Duration(seconds=751) @pytest.mark.asyncio async def test_renew_lease_flattened_error_async(): - client = CloudTasksAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -4291,8 +4373,8 @@ async def test_renew_lease_flattened_error_async(): await client.renew_lease( cloudtasks.RenewLeaseRequest(), name="name_value", - schedule_time=timestamp.Timestamp(seconds=751), - lease_duration=duration.Duration(seconds=751), + schedule_time=timestamp_pb2.Timestamp(seconds=751), + lease_duration=duration_pb2.Duration(seconds=751), ) @@ -4300,7 +4382,7 @@ def test_cancel_lease( transport: str = "grpc", request_type=cloudtasks.CancelLeaseRequest ): client = CloudTasksClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -4317,21 +4399,16 @@ def test_cancel_lease( http_method=target.HttpMethod.POST ), ) - response = client.cancel_lease(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == cloudtasks.CancelLeaseRequest() # Establish that the response is the type that we expect. - assert isinstance(response, task.Task) - assert response.name == "name_value" - assert response.view == task.Task.View.BASIC @@ -4339,12 +4416,27 @@ def test_cancel_lease_from_dict(): test_cancel_lease(request_type=dict) +def test_cancel_lease_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 = CloudTasksClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_lease), "__call__") as call: + client.cancel_lease() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == cloudtasks.CancelLeaseRequest() + + @pytest.mark.asyncio async def test_cancel_lease_async( transport: str = "grpc_asyncio", request_type=cloudtasks.CancelLeaseRequest ): client = CloudTasksAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -4357,20 +4449,16 @@ async def test_cancel_lease_async( call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( task.Task(name="name_value", view=task.Task.View.BASIC,) ) - response = await client.cancel_lease(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == cloudtasks.CancelLeaseRequest() # Establish that the response is the type that we expect. assert isinstance(response, task.Task) - assert response.name == "name_value" - assert response.view == task.Task.View.BASIC @@ -4380,17 +4468,17 @@ async def test_cancel_lease_async_from_dict(): def test_cancel_lease_field_headers(): - client = CloudTasksClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = cloudtasks.CancelLeaseRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.cancel_lease), "__call__") as call: call.return_value = task.Task() - client.cancel_lease(request) # Establish that the underlying gRPC stub method was called. @@ -4405,17 +4493,17 @@ def test_cancel_lease_field_headers(): @pytest.mark.asyncio async def test_cancel_lease_field_headers_async(): - client = CloudTasksAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = cloudtasks.CancelLeaseRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.cancel_lease), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(task.Task()) - await client.cancel_lease(request) # Establish that the underlying gRPC stub method was called. @@ -4429,33 +4517,28 @@ async def test_cancel_lease_field_headers_async(): def test_cancel_lease_flattened(): - client = CloudTasksClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.cancel_lease), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = task.Task() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.cancel_lease( - name="name_value", schedule_time=timestamp.Timestamp(seconds=751), + name="name_value", schedule_time=timestamp_pb2.Timestamp(seconds=751), ) # 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 TimestampRule().to_proto(args[0].schedule_time) == timestamp.Timestamp( - seconds=751 - ) + # assert args[0].schedule_time == timestamp_pb2.Timestamp(seconds=751) def test_cancel_lease_flattened_error(): - client = CloudTasksClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -4463,13 +4546,13 @@ def test_cancel_lease_flattened_error(): client.cancel_lease( cloudtasks.CancelLeaseRequest(), name="name_value", - schedule_time=timestamp.Timestamp(seconds=751), + schedule_time=timestamp_pb2.Timestamp(seconds=751), ) @pytest.mark.asyncio async def test_cancel_lease_flattened_async(): - client = CloudTasksAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.cancel_lease), "__call__") as call: @@ -4480,24 +4563,20 @@ async def test_cancel_lease_flattened_async(): # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. response = await client.cancel_lease( - name="name_value", schedule_time=timestamp.Timestamp(seconds=751), + name="name_value", schedule_time=timestamp_pb2.Timestamp(seconds=751), ) # 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 TimestampRule().to_proto(args[0].schedule_time) == timestamp.Timestamp( - seconds=751 - ) + # assert args[0].schedule_time == timestamp_pb2.Timestamp(seconds=751) @pytest.mark.asyncio async def test_cancel_lease_flattened_error_async(): - client = CloudTasksAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -4505,13 +4584,13 @@ async def test_cancel_lease_flattened_error_async(): await client.cancel_lease( cloudtasks.CancelLeaseRequest(), name="name_value", - schedule_time=timestamp.Timestamp(seconds=751), + schedule_time=timestamp_pb2.Timestamp(seconds=751), ) def test_run_task(transport: str = "grpc", request_type=cloudtasks.RunTaskRequest): client = CloudTasksClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -4528,21 +4607,16 @@ def test_run_task(transport: str = "grpc", request_type=cloudtasks.RunTaskReques http_method=target.HttpMethod.POST ), ) - response = client.run_task(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == cloudtasks.RunTaskRequest() # Establish that the response is the type that we expect. - assert isinstance(response, task.Task) - assert response.name == "name_value" - assert response.view == task.Task.View.BASIC @@ -4550,12 +4624,27 @@ def test_run_task_from_dict(): test_run_task(request_type=dict) +def test_run_task_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 = CloudTasksClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.run_task), "__call__") as call: + client.run_task() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == cloudtasks.RunTaskRequest() + + @pytest.mark.asyncio async def test_run_task_async( transport: str = "grpc_asyncio", request_type=cloudtasks.RunTaskRequest ): client = CloudTasksAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -4568,20 +4657,16 @@ async def test_run_task_async( call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( task.Task(name="name_value", view=task.Task.View.BASIC,) ) - response = await client.run_task(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == cloudtasks.RunTaskRequest() # Establish that the response is the type that we expect. assert isinstance(response, task.Task) - assert response.name == "name_value" - assert response.view == task.Task.View.BASIC @@ -4591,17 +4676,17 @@ async def test_run_task_async_from_dict(): def test_run_task_field_headers(): - client = CloudTasksClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = cloudtasks.RunTaskRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.run_task), "__call__") as call: call.return_value = task.Task() - client.run_task(request) # Establish that the underlying gRPC stub method was called. @@ -4616,17 +4701,17 @@ def test_run_task_field_headers(): @pytest.mark.asyncio async def test_run_task_field_headers_async(): - client = CloudTasksAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = cloudtasks.RunTaskRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.run_task), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(task.Task()) - await client.run_task(request) # Establish that the underlying gRPC stub method was called. @@ -4640,13 +4725,12 @@ async def test_run_task_field_headers_async(): def test_run_task_flattened(): - client = CloudTasksClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.run_task), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = task.Task() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.run_task(name="name_value",) @@ -4655,12 +4739,11 @@ def test_run_task_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" def test_run_task_flattened_error(): - client = CloudTasksClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -4672,7 +4755,7 @@ def test_run_task_flattened_error(): @pytest.mark.asyncio async def test_run_task_flattened_async(): - client = CloudTasksAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.run_task), "__call__") as call: @@ -4688,13 +4771,12 @@ async def test_run_task_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_run_task_flattened_error_async(): - client = CloudTasksAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -4707,16 +4789,16 @@ async def test_run_task_flattened_error_async(): def test_credentials_transport_error(): # It is an error to provide credentials and a transport instance. transport = transports.CloudTasksGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = CloudTasksClient( - 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.CloudTasksGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = CloudTasksClient( @@ -4726,7 +4808,7 @@ def test_credentials_transport_error(): # It is an error to provide scopes and a transport instance. transport = transports.CloudTasksGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = CloudTasksClient( @@ -4737,7 +4819,7 @@ def test_credentials_transport_error(): def test_transport_instance(): # A client may be instantiated with a custom transport instance. transport = transports.CloudTasksGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) client = CloudTasksClient(transport=transport) assert client.transport is transport @@ -4746,13 +4828,13 @@ def test_transport_instance(): def test_transport_get_channel(): # A client may be instantiated with a custom transport instance. transport = transports.CloudTasksGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) channel = transport.grpc_channel assert channel transport = transports.CloudTasksGrpcAsyncIOTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) channel = transport.grpc_channel assert channel @@ -4764,23 +4846,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 = CloudTasksClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksClient(credentials=ga_credentials.AnonymousCredentials(),) assert isinstance(client.transport, transports.CloudTasksGrpcTransport,) def test_cloud_tasks_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.CloudTasksTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), credentials_file="credentials.json", ) @@ -4792,7 +4874,7 @@ def test_cloud_tasks_base_transport(): ) as Transport: Transport.return_value = None transport = transports.CloudTasksTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Every method on the transport should just blindly @@ -4824,15 +4906,37 @@ def test_cloud_tasks_base_transport(): getattr(transport, method)(request=object()) +@requires_google_auth_gte_1_25_0 def test_cloud_tasks_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.cloud.tasks_v2beta2.services.cloud_tasks.transports.CloudTasksTransport._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.CloudTasksTransport( + 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",), + quota_project_id="octopus", + ) + + +@requires_google_auth_lt_1_25_0 +def test_cloud_tasks_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.cloud.tasks_v2beta2.services.cloud_tasks.transports.CloudTasksTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.CloudTasksTransport( credentials_file="credentials.json", quota_project_id="octopus", ) @@ -4845,19 +4949,33 @@ def test_cloud_tasks_base_transport_with_credentials_file(): def test_cloud_tasks_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.cloud.tasks_v2beta2.services.cloud_tasks.transports.CloudTasksTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - adc.return_value = (credentials.AnonymousCredentials(), None) + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.CloudTasksTransport() adc.assert_called_once() +@requires_google_auth_gte_1_25_0 def test_cloud_tasks_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) + CloudTasksClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=("https://www.googleapis.com/auth/cloud-platform",), + quota_project_id=None, + ) + + +@requires_google_auth_lt_1_25_0 +def test_cloud_tasks_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) CloudTasksClient() adc.assert_called_once_with( scopes=("https://www.googleapis.com/auth/cloud-platform",), @@ -4865,26 +4983,156 @@ def test_cloud_tasks_auth_adc(): ) -def test_cloud_tasks_transport_auth_adc(): +@pytest.mark.parametrize( + "transport_class", + [transports.CloudTasksGrpcTransport, transports.CloudTasksGrpcAsyncIOTransport,], +) +@requires_google_auth_gte_1_25_0 +def test_cloud_tasks_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.CloudTasksGrpcTransport( - 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",), + quota_project_id="octopus", ) + + +@pytest.mark.parametrize( + "transport_class", + [transports.CloudTasksGrpcTransport, transports.CloudTasksGrpcAsyncIOTransport,], +) +@requires_google_auth_lt_1_25_0 +def test_cloud_tasks_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",), quota_project_id="octopus", ) +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.CloudTasksGrpcTransport, grpc_helpers), + (transports.CloudTasksGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_gte_1_26_0 +def test_cloud_tasks_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( + "cloudtasks.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + default_scopes=("https://www.googleapis.com/auth/cloud-platform",), + scopes=["1", "2"], + default_host="cloudtasks.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.CloudTasksGrpcTransport, grpc_helpers), + (transports.CloudTasksGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_cloud_tasks_transport_create_channel_old_api_core( + transport_class, grpc_helpers +): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class(quota_project_id="octopus") + + create_channel.assert_called_with( + "cloudtasks.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + scopes=("https://www.googleapis.com/auth/cloud-platform",), + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.CloudTasksGrpcTransport, grpc_helpers), + (transports.CloudTasksGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_cloud_tasks_transport_create_channel_user_scopes( + transport_class, grpc_helpers +): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + + create_channel.assert_called_with( + "cloudtasks.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + scopes=["1", "2"], + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + @pytest.mark.parametrize( "transport_class", [transports.CloudTasksGrpcTransport, transports.CloudTasksGrpcAsyncIOTransport], ) def test_cloud_tasks_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: @@ -4923,7 +5171,7 @@ def test_cloud_tasks_grpc_transport_client_cert_source_for_mtls(transport_class) def test_cloud_tasks_host_no_port(): client = CloudTasksClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="cloudtasks.googleapis.com" ), @@ -4933,7 +5181,7 @@ def test_cloud_tasks_host_no_port(): def test_cloud_tasks_host_with_port(): client = CloudTasksClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="cloudtasks.googleapis.com:8000" ), @@ -4984,9 +5232,9 @@ def test_cloud_tasks_transport_channel_mtls_with_client_cert_source(transport_cl 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", @@ -5061,7 +5309,6 @@ def test_queue_path(): project = "squid" location = "clam" queue = "whelk" - expected = "projects/{project}/locations/{location}/queues/{queue}".format( project=project, location=location, queue=queue, ) @@ -5087,7 +5334,6 @@ def test_task_path(): location = "mussel" queue = "winkle" task = "nautilus" - expected = "projects/{project}/locations/{location}/queues/{queue}/tasks/{task}".format( project=project, location=location, queue=queue, task=task, ) @@ -5111,7 +5357,6 @@ def test_parse_task_path(): def test_common_billing_account_path(): billing_account = "whelk" - expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -5132,7 +5377,6 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): folder = "oyster" - expected = "folders/{folder}".format(folder=folder,) actual = CloudTasksClient.common_folder_path(folder) assert expected == actual @@ -5151,7 +5395,6 @@ def test_parse_common_folder_path(): def test_common_organization_path(): organization = "cuttlefish" - expected = "organizations/{organization}".format(organization=organization,) actual = CloudTasksClient.common_organization_path(organization) assert expected == actual @@ -5170,7 +5413,6 @@ def test_parse_common_organization_path(): def test_common_project_path(): project = "winkle" - expected = "projects/{project}".format(project=project,) actual = CloudTasksClient.common_project_path(project) assert expected == actual @@ -5190,7 +5432,6 @@ def test_parse_common_project_path(): def test_common_location_path(): project = "scallop" location = "abalone" - expected = "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -5217,7 +5458,7 @@ def test_client_withDEFAULT_CLIENT_INFO(): transports.CloudTasksTransport, "_prep_wrapped_messages" ) as prep: client = CloudTasksClient( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) @@ -5226,6 +5467,6 @@ def test_client_withDEFAULT_CLIENT_INFO(): ) as prep: transport_class = CloudTasksClient.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) diff --git a/tests/unit/gapic/tasks_v2beta3/__init__.py b/tests/unit/gapic/tasks_v2beta3/__init__.py index 8b137891..4de65971 100644 --- a/tests/unit/gapic/tasks_v2beta3/__init__.py +++ b/tests/unit/gapic/tasks_v2beta3/__init__.py @@ -1 +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/tasks_v2beta3/test_cloud_tasks.py b/tests/unit/gapic/tasks_v2beta3/test_cloud_tasks.py index 99157ca3..185aa41c 100644 --- a/tests/unit/gapic/tasks_v2beta3/test_cloud_tasks.py +++ b/tests/unit/gapic/tasks_v2beta3/test_cloud_tasks.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,34 +23,64 @@ 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.cloud.tasks_v2beta3.services.cloud_tasks import CloudTasksAsyncClient from google.cloud.tasks_v2beta3.services.cloud_tasks import CloudTasksClient from google.cloud.tasks_v2beta3.services.cloud_tasks import pagers from google.cloud.tasks_v2beta3.services.cloud_tasks import transports +from google.cloud.tasks_v2beta3.services.cloud_tasks.transports.base import ( + _API_CORE_VERSION, +) +from google.cloud.tasks_v2beta3.services.cloud_tasks.transports.base import ( + _GOOGLE_AUTH_VERSION, +) from google.cloud.tasks_v2beta3.types import cloudtasks from google.cloud.tasks_v2beta3.types import queue from google.cloud.tasks_v2beta3.types import queue as gct_queue from google.cloud.tasks_v2beta3.types import target from google.cloud.tasks_v2beta3.types import task from google.cloud.tasks_v2beta3.types import task as gct_task -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 any_pb2 as gp_any # 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.rpc import status_pb2 as status # type: ignore -from google.type import expr_pb2 as expr # type: ignore +from google.protobuf import any_pb2 # type: ignore +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from google.rpc import status_pb2 # type: ignore +from google.type import expr_pb2 # type: ignore +import google.auth + + +# TODO(busunkim): Once google-api-core >= 1.26.0 is required: +# - Delete all the api-core and auth "less than" test cases +# - Delete these pytest markers (Make the "greater than or equal to" tests the default). +requires_google_auth_lt_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), + reason="This test requires google-auth < 1.25.0", +) +requires_google_auth_gte_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) < packaging.version.parse("1.25.0"), + reason="This test requires google-auth >= 1.25.0", +) + +requires_api_core_lt_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) >= packaging.version.parse("1.26.0"), + reason="This test requires google-api-core < 1.26.0", +) + +requires_api_core_gte_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) < packaging.version.parse("1.26.0"), + reason="This test requires google-api-core >= 1.26.0", +) def client_cert_source_callback(): @@ -95,31 +124,35 @@ def test__get_default_mtls_endpoint(): assert CloudTasksClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi -def test_cloud_tasks_client_from_service_account_info(): - creds = credentials.AnonymousCredentials() +@pytest.mark.parametrize("client_class", [CloudTasksClient, CloudTasksAsyncClient,]) +def test_cloud_tasks_client_from_service_account_info(client_class): + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_info" ) as factory: factory.return_value = creds info = {"valid": True} - client = CloudTasksClient.from_service_account_info(info) + client = client_class.from_service_account_info(info) assert client.transport._credentials == creds + assert isinstance(client, client_class) assert client.transport._host == "cloudtasks.googleapis.com:443" @pytest.mark.parametrize("client_class", [CloudTasksClient, CloudTasksAsyncClient,]) def test_cloud_tasks_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: 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 == "cloudtasks.googleapis.com:443" @@ -159,7 +192,7 @@ def test_cloud_tasks_client_client_options( ): # Check that if channel is provided we won't create a new one. with mock.patch.object(CloudTasksClient, "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() @@ -443,7 +476,7 @@ def test_list_queues( transport: str = "grpc", request_type=cloudtasks.ListQueuesRequest ): client = CloudTasksClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -456,19 +489,15 @@ def test_list_queues( call.return_value = cloudtasks.ListQueuesResponse( next_page_token="next_page_token_value", ) - response = client.list_queues(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == cloudtasks.ListQueuesRequest() # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListQueuesPager) - assert response.next_page_token == "next_page_token_value" @@ -476,12 +505,27 @@ def test_list_queues_from_dict(): test_list_queues(request_type=dict) +def test_list_queues_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 = CloudTasksClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_queues), "__call__") as call: + client.list_queues() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == cloudtasks.ListQueuesRequest() + + @pytest.mark.asyncio async def test_list_queues_async( transport: str = "grpc_asyncio", request_type=cloudtasks.ListQueuesRequest ): client = CloudTasksAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -494,18 +538,15 @@ async def test_list_queues_async( call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( cloudtasks.ListQueuesResponse(next_page_token="next_page_token_value",) ) - response = await client.list_queues(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == cloudtasks.ListQueuesRequest() # Establish that the response is the type that we expect. assert isinstance(response, pagers.ListQueuesAsyncPager) - assert response.next_page_token == "next_page_token_value" @@ -515,17 +556,17 @@ async def test_list_queues_async_from_dict(): def test_list_queues_field_headers(): - client = CloudTasksClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = cloudtasks.ListQueuesRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_queues), "__call__") as call: call.return_value = cloudtasks.ListQueuesResponse() - client.list_queues(request) # Establish that the underlying gRPC stub method was called. @@ -540,11 +581,12 @@ def test_list_queues_field_headers(): @pytest.mark.asyncio async def test_list_queues_field_headers_async(): - client = CloudTasksAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = cloudtasks.ListQueuesRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -552,7 +594,6 @@ async def test_list_queues_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( cloudtasks.ListQueuesResponse() ) - await client.list_queues(request) # Establish that the underlying gRPC stub method was called. @@ -566,13 +607,12 @@ async def test_list_queues_field_headers_async(): def test_list_queues_flattened(): - client = CloudTasksClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_queues), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = cloudtasks.ListQueuesResponse() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.list_queues(parent="parent_value",) @@ -581,12 +621,11 @@ def test_list_queues_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" def test_list_queues_flattened_error(): - client = CloudTasksClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -598,7 +637,7 @@ def test_list_queues_flattened_error(): @pytest.mark.asyncio async def test_list_queues_flattened_async(): - client = CloudTasksAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_queues), "__call__") as call: @@ -616,13 +655,12 @@ async def test_list_queues_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_queues_flattened_error_async(): - client = CloudTasksAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -633,7 +671,7 @@ async def test_list_queues_flattened_error_async(): def test_list_queues_pager(): - client = CloudTasksClient(credentials=credentials.AnonymousCredentials,) + client = CloudTasksClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_queues), "__call__") as call: @@ -665,7 +703,7 @@ def test_list_queues_pager(): def test_list_queues_pages(): - client = CloudTasksClient(credentials=credentials.AnonymousCredentials,) + client = CloudTasksClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_queues), "__call__") as call: @@ -689,7 +727,7 @@ def test_list_queues_pages(): @pytest.mark.asyncio async def test_list_queues_async_pager(): - client = CloudTasksAsyncClient(credentials=credentials.AnonymousCredentials,) + client = CloudTasksAsyncClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -720,7 +758,7 @@ async def test_list_queues_async_pager(): @pytest.mark.asyncio async def test_list_queues_async_pages(): - client = CloudTasksAsyncClient(credentials=credentials.AnonymousCredentials,) + client = CloudTasksAsyncClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -748,7 +786,7 @@ async def test_list_queues_async_pages(): def test_get_queue(transport: str = "grpc", request_type=cloudtasks.GetQueueRequest): client = CloudTasksClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -768,23 +806,17 @@ def test_get_queue(transport: str = "grpc", request_type=cloudtasks.GetQueueRequ ) ), ) - response = client.get_queue(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == cloudtasks.GetQueueRequest() # Establish that the response is the type that we expect. - assert isinstance(response, queue.Queue) - assert response.name == "name_value" - assert response.state == queue.Queue.State.RUNNING - assert response.type_ == queue.Queue.Type.PULL @@ -792,12 +824,27 @@ def test_get_queue_from_dict(): test_get_queue(request_type=dict) +def test_get_queue_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 = CloudTasksClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_queue), "__call__") as call: + client.get_queue() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == cloudtasks.GetQueueRequest() + + @pytest.mark.asyncio async def test_get_queue_async( transport: str = "grpc_asyncio", request_type=cloudtasks.GetQueueRequest ): client = CloudTasksAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -814,22 +861,17 @@ async def test_get_queue_async( type_=queue.Queue.Type.PULL, ) ) - response = await client.get_queue(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == cloudtasks.GetQueueRequest() # Establish that the response is the type that we expect. assert isinstance(response, queue.Queue) - assert response.name == "name_value" - assert response.state == queue.Queue.State.RUNNING - assert response.type_ == queue.Queue.Type.PULL @@ -839,17 +881,17 @@ async def test_get_queue_async_from_dict(): def test_get_queue_field_headers(): - client = CloudTasksClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = cloudtasks.GetQueueRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_queue), "__call__") as call: call.return_value = queue.Queue() - client.get_queue(request) # Establish that the underlying gRPC stub method was called. @@ -864,17 +906,17 @@ def test_get_queue_field_headers(): @pytest.mark.asyncio async def test_get_queue_field_headers_async(): - client = CloudTasksAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = cloudtasks.GetQueueRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_queue), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(queue.Queue()) - await client.get_queue(request) # Establish that the underlying gRPC stub method was called. @@ -888,13 +930,12 @@ async def test_get_queue_field_headers_async(): def test_get_queue_flattened(): - client = CloudTasksClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_queue), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = queue.Queue() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.get_queue(name="name_value",) @@ -903,12 +944,11 @@ def test_get_queue_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" def test_get_queue_flattened_error(): - client = CloudTasksClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -920,7 +960,7 @@ def test_get_queue_flattened_error(): @pytest.mark.asyncio async def test_get_queue_flattened_async(): - client = CloudTasksAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_queue), "__call__") as call: @@ -936,13 +976,12 @@ async def test_get_queue_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_queue_flattened_error_async(): - client = CloudTasksAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -956,7 +995,7 @@ def test_create_queue( transport: str = "grpc", request_type=cloudtasks.CreateQueueRequest ): client = CloudTasksClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -976,23 +1015,17 @@ def test_create_queue( ) ), ) - response = client.create_queue(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == cloudtasks.CreateQueueRequest() # Establish that the response is the type that we expect. - assert isinstance(response, gct_queue.Queue) - assert response.name == "name_value" - assert response.state == gct_queue.Queue.State.RUNNING - assert response.type_ == gct_queue.Queue.Type.PULL @@ -1000,12 +1033,27 @@ def test_create_queue_from_dict(): test_create_queue(request_type=dict) +def test_create_queue_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 = CloudTasksClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.create_queue), "__call__") as call: + client.create_queue() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == cloudtasks.CreateQueueRequest() + + @pytest.mark.asyncio async def test_create_queue_async( transport: str = "grpc_asyncio", request_type=cloudtasks.CreateQueueRequest ): client = CloudTasksAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1022,22 +1070,17 @@ async def test_create_queue_async( type_=gct_queue.Queue.Type.PULL, ) ) - response = await client.create_queue(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == cloudtasks.CreateQueueRequest() # Establish that the response is the type that we expect. assert isinstance(response, gct_queue.Queue) - assert response.name == "name_value" - assert response.state == gct_queue.Queue.State.RUNNING - assert response.type_ == gct_queue.Queue.Type.PULL @@ -1047,17 +1090,17 @@ async def test_create_queue_async_from_dict(): def test_create_queue_field_headers(): - client = CloudTasksClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = cloudtasks.CreateQueueRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.create_queue), "__call__") as call: call.return_value = gct_queue.Queue() - client.create_queue(request) # Establish that the underlying gRPC stub method was called. @@ -1072,17 +1115,17 @@ def test_create_queue_field_headers(): @pytest.mark.asyncio async def test_create_queue_field_headers_async(): - client = CloudTasksAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = cloudtasks.CreateQueueRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.create_queue), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gct_queue.Queue()) - await client.create_queue(request) # Establish that the underlying gRPC stub method was called. @@ -1096,13 +1139,12 @@ async def test_create_queue_field_headers_async(): def test_create_queue_flattened(): - client = CloudTasksClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.create_queue), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = gct_queue.Queue() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.create_queue( @@ -1113,14 +1155,12 @@ def test_create_queue_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" - assert args[0].queue == gct_queue.Queue(name="name_value") def test_create_queue_flattened_error(): - client = CloudTasksClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1134,7 +1174,7 @@ def test_create_queue_flattened_error(): @pytest.mark.asyncio async def test_create_queue_flattened_async(): - client = CloudTasksAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.create_queue), "__call__") as call: @@ -1152,15 +1192,13 @@ async def test_create_queue_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" - assert args[0].queue == gct_queue.Queue(name="name_value") @pytest.mark.asyncio async def test_create_queue_flattened_error_async(): - client = CloudTasksAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1176,7 +1214,7 @@ def test_update_queue( transport: str = "grpc", request_type=cloudtasks.UpdateQueueRequest ): client = CloudTasksClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1196,23 +1234,17 @@ def test_update_queue( ) ), ) - response = client.update_queue(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == cloudtasks.UpdateQueueRequest() # Establish that the response is the type that we expect. - assert isinstance(response, gct_queue.Queue) - assert response.name == "name_value" - assert response.state == gct_queue.Queue.State.RUNNING - assert response.type_ == gct_queue.Queue.Type.PULL @@ -1220,12 +1252,27 @@ def test_update_queue_from_dict(): test_update_queue(request_type=dict) +def test_update_queue_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 = CloudTasksClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.update_queue), "__call__") as call: + client.update_queue() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == cloudtasks.UpdateQueueRequest() + + @pytest.mark.asyncio async def test_update_queue_async( transport: str = "grpc_asyncio", request_type=cloudtasks.UpdateQueueRequest ): client = CloudTasksAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1242,22 +1289,17 @@ async def test_update_queue_async( type_=gct_queue.Queue.Type.PULL, ) ) - response = await client.update_queue(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == cloudtasks.UpdateQueueRequest() # Establish that the response is the type that we expect. assert isinstance(response, gct_queue.Queue) - assert response.name == "name_value" - assert response.state == gct_queue.Queue.State.RUNNING - assert response.type_ == gct_queue.Queue.Type.PULL @@ -1267,17 +1309,17 @@ async def test_update_queue_async_from_dict(): def test_update_queue_field_headers(): - client = CloudTasksClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = cloudtasks.UpdateQueueRequest() + request.queue.name = "queue.name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.update_queue), "__call__") as call: call.return_value = gct_queue.Queue() - client.update_queue(request) # Establish that the underlying gRPC stub method was called. @@ -1292,17 +1334,17 @@ def test_update_queue_field_headers(): @pytest.mark.asyncio async def test_update_queue_field_headers_async(): - client = CloudTasksAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = cloudtasks.UpdateQueueRequest() + request.queue.name = "queue.name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.update_queue), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gct_queue.Queue()) - await client.update_queue(request) # Establish that the underlying gRPC stub method was called. @@ -1316,32 +1358,29 @@ async def test_update_queue_field_headers_async(): def test_update_queue_flattened(): - client = CloudTasksClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.update_queue), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = gct_queue.Queue() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.update_queue( queue=gct_queue.Queue(name="name_value"), - update_mask=field_mask.FieldMask(paths=["paths_value"]), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].queue == gct_queue.Queue(name="name_value") - - assert args[0].update_mask == field_mask.FieldMask(paths=["paths_value"]) + assert args[0].update_mask == field_mask_pb2.FieldMask(paths=["paths_value"]) def test_update_queue_flattened_error(): - client = CloudTasksClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1349,13 +1388,13 @@ def test_update_queue_flattened_error(): client.update_queue( cloudtasks.UpdateQueueRequest(), queue=gct_queue.Queue(name="name_value"), - update_mask=field_mask.FieldMask(paths=["paths_value"]), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) @pytest.mark.asyncio async def test_update_queue_flattened_async(): - client = CloudTasksAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.update_queue), "__call__") as call: @@ -1367,22 +1406,20 @@ async def test_update_queue_flattened_async(): # using the keyword arguments to the method. response = await client.update_queue( queue=gct_queue.Queue(name="name_value"), - update_mask=field_mask.FieldMask(paths=["paths_value"]), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].queue == gct_queue.Queue(name="name_value") - - assert args[0].update_mask == field_mask.FieldMask(paths=["paths_value"]) + assert args[0].update_mask == field_mask_pb2.FieldMask(paths=["paths_value"]) @pytest.mark.asyncio async def test_update_queue_flattened_error_async(): - client = CloudTasksAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1390,7 +1427,7 @@ async def test_update_queue_flattened_error_async(): await client.update_queue( cloudtasks.UpdateQueueRequest(), queue=gct_queue.Queue(name="name_value"), - update_mask=field_mask.FieldMask(paths=["paths_value"]), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) @@ -1398,7 +1435,7 @@ def test_delete_queue( transport: str = "grpc", request_type=cloudtasks.DeleteQueueRequest ): client = CloudTasksClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1409,13 +1446,11 @@ def test_delete_queue( with mock.patch.object(type(client.transport.delete_queue), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = None - response = client.delete_queue(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == cloudtasks.DeleteQueueRequest() # Establish that the response is the type that we expect. @@ -1426,12 +1461,27 @@ def test_delete_queue_from_dict(): test_delete_queue(request_type=dict) +def test_delete_queue_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 = CloudTasksClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_queue), "__call__") as call: + client.delete_queue() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == cloudtasks.DeleteQueueRequest() + + @pytest.mark.asyncio async def test_delete_queue_async( transport: str = "grpc_asyncio", request_type=cloudtasks.DeleteQueueRequest ): client = CloudTasksAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1442,13 +1492,11 @@ async def test_delete_queue_async( with mock.patch.object(type(client.transport.delete_queue), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_queue(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == cloudtasks.DeleteQueueRequest() # Establish that the response is the type that we expect. @@ -1461,17 +1509,17 @@ async def test_delete_queue_async_from_dict(): def test_delete_queue_field_headers(): - client = CloudTasksClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = cloudtasks.DeleteQueueRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.delete_queue), "__call__") as call: call.return_value = None - client.delete_queue(request) # Establish that the underlying gRPC stub method was called. @@ -1486,17 +1534,17 @@ def test_delete_queue_field_headers(): @pytest.mark.asyncio async def test_delete_queue_field_headers_async(): - client = CloudTasksAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = cloudtasks.DeleteQueueRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.delete_queue), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_queue(request) # Establish that the underlying gRPC stub method was called. @@ -1510,13 +1558,12 @@ async def test_delete_queue_field_headers_async(): def test_delete_queue_flattened(): - client = CloudTasksClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.delete_queue), "__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_queue(name="name_value",) @@ -1525,12 +1572,11 @@ def test_delete_queue_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" def test_delete_queue_flattened_error(): - client = CloudTasksClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1542,7 +1588,7 @@ def test_delete_queue_flattened_error(): @pytest.mark.asyncio async def test_delete_queue_flattened_async(): - client = CloudTasksAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.delete_queue), "__call__") as call: @@ -1558,13 +1604,12 @@ async def test_delete_queue_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_queue_flattened_error_async(): - client = CloudTasksAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1578,7 +1623,7 @@ def test_purge_queue( transport: str = "grpc", request_type=cloudtasks.PurgeQueueRequest ): client = CloudTasksClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1598,23 +1643,17 @@ def test_purge_queue( ) ), ) - response = client.purge_queue(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == cloudtasks.PurgeQueueRequest() # Establish that the response is the type that we expect. - assert isinstance(response, queue.Queue) - assert response.name == "name_value" - assert response.state == queue.Queue.State.RUNNING - assert response.type_ == queue.Queue.Type.PULL @@ -1622,12 +1661,27 @@ def test_purge_queue_from_dict(): test_purge_queue(request_type=dict) +def test_purge_queue_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 = CloudTasksClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.purge_queue), "__call__") as call: + client.purge_queue() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == cloudtasks.PurgeQueueRequest() + + @pytest.mark.asyncio async def test_purge_queue_async( transport: str = "grpc_asyncio", request_type=cloudtasks.PurgeQueueRequest ): client = CloudTasksAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1644,22 +1698,17 @@ async def test_purge_queue_async( type_=queue.Queue.Type.PULL, ) ) - response = await client.purge_queue(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == cloudtasks.PurgeQueueRequest() # Establish that the response is the type that we expect. assert isinstance(response, queue.Queue) - assert response.name == "name_value" - assert response.state == queue.Queue.State.RUNNING - assert response.type_ == queue.Queue.Type.PULL @@ -1669,17 +1718,17 @@ async def test_purge_queue_async_from_dict(): def test_purge_queue_field_headers(): - client = CloudTasksClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = cloudtasks.PurgeQueueRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.purge_queue), "__call__") as call: call.return_value = queue.Queue() - client.purge_queue(request) # Establish that the underlying gRPC stub method was called. @@ -1694,17 +1743,17 @@ def test_purge_queue_field_headers(): @pytest.mark.asyncio async def test_purge_queue_field_headers_async(): - client = CloudTasksAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = cloudtasks.PurgeQueueRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.purge_queue), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(queue.Queue()) - await client.purge_queue(request) # Establish that the underlying gRPC stub method was called. @@ -1718,13 +1767,12 @@ async def test_purge_queue_field_headers_async(): def test_purge_queue_flattened(): - client = CloudTasksClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.purge_queue), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = queue.Queue() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.purge_queue(name="name_value",) @@ -1733,12 +1781,11 @@ def test_purge_queue_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" def test_purge_queue_flattened_error(): - client = CloudTasksClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1750,7 +1797,7 @@ def test_purge_queue_flattened_error(): @pytest.mark.asyncio async def test_purge_queue_flattened_async(): - client = CloudTasksAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.purge_queue), "__call__") as call: @@ -1766,13 +1813,12 @@ async def test_purge_queue_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_purge_queue_flattened_error_async(): - client = CloudTasksAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1786,7 +1832,7 @@ def test_pause_queue( transport: str = "grpc", request_type=cloudtasks.PauseQueueRequest ): client = CloudTasksClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1806,23 +1852,17 @@ def test_pause_queue( ) ), ) - response = client.pause_queue(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == cloudtasks.PauseQueueRequest() # Establish that the response is the type that we expect. - assert isinstance(response, queue.Queue) - assert response.name == "name_value" - assert response.state == queue.Queue.State.RUNNING - assert response.type_ == queue.Queue.Type.PULL @@ -1830,12 +1870,27 @@ def test_pause_queue_from_dict(): test_pause_queue(request_type=dict) +def test_pause_queue_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 = CloudTasksClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.pause_queue), "__call__") as call: + client.pause_queue() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == cloudtasks.PauseQueueRequest() + + @pytest.mark.asyncio async def test_pause_queue_async( transport: str = "grpc_asyncio", request_type=cloudtasks.PauseQueueRequest ): client = CloudTasksAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1852,22 +1907,17 @@ async def test_pause_queue_async( type_=queue.Queue.Type.PULL, ) ) - response = await client.pause_queue(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == cloudtasks.PauseQueueRequest() # Establish that the response is the type that we expect. assert isinstance(response, queue.Queue) - assert response.name == "name_value" - assert response.state == queue.Queue.State.RUNNING - assert response.type_ == queue.Queue.Type.PULL @@ -1877,17 +1927,17 @@ async def test_pause_queue_async_from_dict(): def test_pause_queue_field_headers(): - client = CloudTasksClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = cloudtasks.PauseQueueRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.pause_queue), "__call__") as call: call.return_value = queue.Queue() - client.pause_queue(request) # Establish that the underlying gRPC stub method was called. @@ -1902,17 +1952,17 @@ def test_pause_queue_field_headers(): @pytest.mark.asyncio async def test_pause_queue_field_headers_async(): - client = CloudTasksAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = cloudtasks.PauseQueueRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.pause_queue), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(queue.Queue()) - await client.pause_queue(request) # Establish that the underlying gRPC stub method was called. @@ -1926,13 +1976,12 @@ async def test_pause_queue_field_headers_async(): def test_pause_queue_flattened(): - client = CloudTasksClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.pause_queue), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = queue.Queue() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.pause_queue(name="name_value",) @@ -1941,12 +1990,11 @@ def test_pause_queue_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" def test_pause_queue_flattened_error(): - client = CloudTasksClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1958,7 +2006,7 @@ def test_pause_queue_flattened_error(): @pytest.mark.asyncio async def test_pause_queue_flattened_async(): - client = CloudTasksAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.pause_queue), "__call__") as call: @@ -1974,13 +2022,12 @@ async def test_pause_queue_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_pause_queue_flattened_error_async(): - client = CloudTasksAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1994,7 +2041,7 @@ def test_resume_queue( transport: str = "grpc", request_type=cloudtasks.ResumeQueueRequest ): client = CloudTasksClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -2014,23 +2061,17 @@ def test_resume_queue( ) ), ) - response = client.resume_queue(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == cloudtasks.ResumeQueueRequest() # Establish that the response is the type that we expect. - assert isinstance(response, queue.Queue) - assert response.name == "name_value" - assert response.state == queue.Queue.State.RUNNING - assert response.type_ == queue.Queue.Type.PULL @@ -2038,12 +2079,27 @@ def test_resume_queue_from_dict(): test_resume_queue(request_type=dict) +def test_resume_queue_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 = CloudTasksClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.resume_queue), "__call__") as call: + client.resume_queue() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == cloudtasks.ResumeQueueRequest() + + @pytest.mark.asyncio async def test_resume_queue_async( transport: str = "grpc_asyncio", request_type=cloudtasks.ResumeQueueRequest ): client = CloudTasksAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -2060,22 +2116,17 @@ async def test_resume_queue_async( type_=queue.Queue.Type.PULL, ) ) - response = await client.resume_queue(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == cloudtasks.ResumeQueueRequest() # Establish that the response is the type that we expect. assert isinstance(response, queue.Queue) - assert response.name == "name_value" - assert response.state == queue.Queue.State.RUNNING - assert response.type_ == queue.Queue.Type.PULL @@ -2085,17 +2136,17 @@ async def test_resume_queue_async_from_dict(): def test_resume_queue_field_headers(): - client = CloudTasksClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = cloudtasks.ResumeQueueRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.resume_queue), "__call__") as call: call.return_value = queue.Queue() - client.resume_queue(request) # Establish that the underlying gRPC stub method was called. @@ -2110,17 +2161,17 @@ def test_resume_queue_field_headers(): @pytest.mark.asyncio async def test_resume_queue_field_headers_async(): - client = CloudTasksAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = cloudtasks.ResumeQueueRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.resume_queue), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(queue.Queue()) - await client.resume_queue(request) # Establish that the underlying gRPC stub method was called. @@ -2134,13 +2185,12 @@ async def test_resume_queue_field_headers_async(): def test_resume_queue_flattened(): - client = CloudTasksClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.resume_queue), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = queue.Queue() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.resume_queue(name="name_value",) @@ -2149,12 +2199,11 @@ def test_resume_queue_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" def test_resume_queue_flattened_error(): - client = CloudTasksClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -2166,7 +2215,7 @@ def test_resume_queue_flattened_error(): @pytest.mark.asyncio async def test_resume_queue_flattened_async(): - client = CloudTasksAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.resume_queue), "__call__") as call: @@ -2182,13 +2231,12 @@ async def test_resume_queue_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_resume_queue_flattened_error_async(): - client = CloudTasksAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -2199,10 +2247,10 @@ async def test_resume_queue_flattened_error_async(): def test_get_iam_policy( - transport: str = "grpc", request_type=iam_policy.GetIamPolicyRequest + transport: str = "grpc", request_type=iam_policy_pb2.GetIamPolicyRequest ): client = CloudTasksClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -2212,22 +2260,17 @@ def test_get_iam_policy( # 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) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - - assert args[0] == iam_policy.GetIamPolicyRequest() + assert args[0] == iam_policy_pb2.GetIamPolicyRequest() # 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 - assert response.etag == b"etag_blob" @@ -2235,12 +2278,27 @@ def test_get_iam_policy_from_dict(): test_get_iam_policy(request_type=dict) +def test_get_iam_policy_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 = CloudTasksClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: + client.get_iam_policy() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.GetIamPolicyRequest() + + @pytest.mark.asyncio async def test_get_iam_policy_async( - transport: str = "grpc_asyncio", request_type=iam_policy.GetIamPolicyRequest + transport: str = "grpc_asyncio", request_type=iam_policy_pb2.GetIamPolicyRequest ): client = CloudTasksAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -2251,22 +2309,18 @@ async def test_get_iam_policy_async( 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) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - - assert args[0] == iam_policy.GetIamPolicyRequest() + assert args[0] == iam_policy_pb2.GetIamPolicyRequest() # 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 - assert response.etag == b"etag_blob" @@ -2276,17 +2330,17 @@ async def test_get_iam_policy_async_from_dict(): def test_get_iam_policy_field_headers(): - client = CloudTasksClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value 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) # Establish that the underlying gRPC stub method was called. @@ -2301,17 +2355,17 @@ def test_get_iam_policy_field_headers(): @pytest.mark.asyncio async def test_get_iam_policy_field_headers_async(): - client = CloudTasksAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value 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) # Establish that the underlying gRPC stub method was called. @@ -2325,29 +2379,27 @@ async def test_get_iam_policy_field_headers_async(): def test_get_iam_policy_from_dict_foreign(): - client = CloudTasksClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksClient(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() def test_get_iam_policy_flattened(): - client = CloudTasksClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksClient(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() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.get_iam_policy(resource="resource_value",) @@ -2356,31 +2408,30 @@ def test_get_iam_policy_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].resource == "resource_value" def test_get_iam_policy_flattened_error(): - client = CloudTasksClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): client.get_iam_policy( - iam_policy.GetIamPolicyRequest(), resource="resource_value", + iam_policy_pb2.GetIamPolicyRequest(), resource="resource_value", ) @pytest.mark.asyncio async def test_get_iam_policy_flattened_async(): - client = CloudTasksAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksAsyncClient(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() - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy.Policy()) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. response = await client.get_iam_policy(resource="resource_value",) @@ -2389,27 +2440,26 @@ async def test_get_iam_policy_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].resource == "resource_value" @pytest.mark.asyncio async def test_get_iam_policy_flattened_error_async(): - client = CloudTasksAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): await client.get_iam_policy( - iam_policy.GetIamPolicyRequest(), resource="resource_value", + iam_policy_pb2.GetIamPolicyRequest(), resource="resource_value", ) def test_set_iam_policy( - transport: str = "grpc", request_type=iam_policy.SetIamPolicyRequest + transport: str = "grpc", request_type=iam_policy_pb2.SetIamPolicyRequest ): client = CloudTasksClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -2419,22 +2469,17 @@ def test_set_iam_policy( # 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) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - - assert args[0] == iam_policy.SetIamPolicyRequest() + assert args[0] == iam_policy_pb2.SetIamPolicyRequest() # 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 - assert response.etag == b"etag_blob" @@ -2442,12 +2487,27 @@ def test_set_iam_policy_from_dict(): test_set_iam_policy(request_type=dict) +def test_set_iam_policy_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 = CloudTasksClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + client.set_iam_policy() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.SetIamPolicyRequest() + + @pytest.mark.asyncio async def test_set_iam_policy_async( - transport: str = "grpc_asyncio", request_type=iam_policy.SetIamPolicyRequest + transport: str = "grpc_asyncio", request_type=iam_policy_pb2.SetIamPolicyRequest ): client = CloudTasksAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -2458,22 +2518,18 @@ async def test_set_iam_policy_async( 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) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - - assert args[0] == iam_policy.SetIamPolicyRequest() + assert args[0] == iam_policy_pb2.SetIamPolicyRequest() # 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 - assert response.etag == b"etag_blob" @@ -2483,17 +2539,17 @@ async def test_set_iam_policy_async_from_dict(): def test_set_iam_policy_field_headers(): - client = CloudTasksClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value 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) # Establish that the underlying gRPC stub method was called. @@ -2508,17 +2564,17 @@ def test_set_iam_policy_field_headers(): @pytest.mark.asyncio async def test_set_iam_policy_field_headers_async(): - client = CloudTasksAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value 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) # Establish that the underlying gRPC stub method was called. @@ -2532,29 +2588,27 @@ async def test_set_iam_policy_field_headers_async(): def test_set_iam_policy_from_dict_foreign(): - client = CloudTasksClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksClient(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() def test_set_iam_policy_flattened(): - client = CloudTasksClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksClient(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() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.set_iam_policy(resource="resource_value",) @@ -2563,31 +2617,30 @@ def test_set_iam_policy_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].resource == "resource_value" def test_set_iam_policy_flattened_error(): - client = CloudTasksClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): client.set_iam_policy( - iam_policy.SetIamPolicyRequest(), resource="resource_value", + iam_policy_pb2.SetIamPolicyRequest(), resource="resource_value", ) @pytest.mark.asyncio async def test_set_iam_policy_flattened_async(): - client = CloudTasksAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksAsyncClient(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() - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy.Policy()) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. response = await client.set_iam_policy(resource="resource_value",) @@ -2596,27 +2649,26 @@ async def test_set_iam_policy_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].resource == "resource_value" @pytest.mark.asyncio async def test_set_iam_policy_flattened_error_async(): - client = CloudTasksAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): await client.set_iam_policy( - iam_policy.SetIamPolicyRequest(), resource="resource_value", + iam_policy_pb2.SetIamPolicyRequest(), resource="resource_value", ) def test_test_iam_permissions( - transport: str = "grpc", request_type=iam_policy.TestIamPermissionsRequest + transport: str = "grpc", request_type=iam_policy_pb2.TestIamPermissionsRequest ): client = CloudTasksClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -2628,22 +2680,18 @@ def test_test_iam_permissions( 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"], ) - 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] == iam_policy.TestIamPermissionsRequest() + assert args[0] == iam_policy_pb2.TestIamPermissionsRequest() # 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"] @@ -2651,12 +2699,30 @@ def test_test_iam_permissions_from_dict(): test_test_iam_permissions(request_type=dict) +def test_test_iam_permissions_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 = CloudTasksClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + client.test_iam_permissions() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.TestIamPermissionsRequest() + + @pytest.mark.asyncio async def test_test_iam_permissions_async( - transport: str = "grpc_asyncio", request_type=iam_policy.TestIamPermissionsRequest + transport: str = "grpc_asyncio", + request_type=iam_policy_pb2.TestIamPermissionsRequest, ): client = CloudTasksAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -2669,20 +2735,19 @@ async def test_test_iam_permissions_async( ) 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) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - - assert args[0] == iam_policy.TestIamPermissionsRequest() + assert args[0] == iam_policy_pb2.TestIamPermissionsRequest() # 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"] @@ -2692,19 +2757,19 @@ async def test_test_iam_permissions_async_from_dict(): def test_test_iam_permissions_field_headers(): - client = CloudTasksClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value 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) # Establish that the underlying gRPC stub method was called. @@ -2719,11 +2784,12 @@ def test_test_iam_permissions_field_headers(): @pytest.mark.asyncio async def test_test_iam_permissions_field_headers_async(): - client = CloudTasksAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value 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. @@ -2731,9 +2797,8 @@ 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) # Establish that the underlying gRPC stub method was called. @@ -2747,14 +2812,13 @@ async def test_test_iam_permissions_field_headers_async(): def test_test_iam_permissions_from_dict_foreign(): - client = CloudTasksClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksClient(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={ "resource": "resource_value", @@ -2765,15 +2829,14 @@ def test_test_iam_permissions_from_dict_foreign(): def test_test_iam_permissions_flattened(): - client = CloudTasksClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksClient(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() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.test_iam_permissions( @@ -2784,20 +2847,18 @@ def test_test_iam_permissions_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].resource == "resource_value" - assert args[0].permissions == ["permissions_value"] def test_test_iam_permissions_flattened_error(): - client = CloudTasksClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): client.test_iam_permissions( - iam_policy.TestIamPermissionsRequest(), + iam_policy_pb2.TestIamPermissionsRequest(), resource="resource_value", permissions=["permissions_value"], ) @@ -2805,17 +2866,17 @@ def test_test_iam_permissions_flattened_error(): @pytest.mark.asyncio async def test_test_iam_permissions_flattened_async(): - client = CloudTasksAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksAsyncClient(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() call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - iam_policy.TestIamPermissionsResponse() + iam_policy_pb2.TestIamPermissionsResponse() ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. @@ -2827,21 +2888,19 @@ async def test_test_iam_permissions_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].resource == "resource_value" - assert args[0].permissions == ["permissions_value"] @pytest.mark.asyncio async def test_test_iam_permissions_flattened_error_async(): - client = CloudTasksAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): await client.test_iam_permissions( - iam_policy.TestIamPermissionsRequest(), + iam_policy_pb2.TestIamPermissionsRequest(), resource="resource_value", permissions=["permissions_value"], ) @@ -2849,7 +2908,7 @@ async def test_test_iam_permissions_flattened_error_async(): def test_list_tasks(transport: str = "grpc", request_type=cloudtasks.ListTasksRequest): client = CloudTasksClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -2862,19 +2921,15 @@ def test_list_tasks(transport: str = "grpc", request_type=cloudtasks.ListTasksRe call.return_value = cloudtasks.ListTasksResponse( next_page_token="next_page_token_value", ) - response = client.list_tasks(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == cloudtasks.ListTasksRequest() # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListTasksPager) - assert response.next_page_token == "next_page_token_value" @@ -2882,12 +2937,27 @@ def test_list_tasks_from_dict(): test_list_tasks(request_type=dict) +def test_list_tasks_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 = CloudTasksClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_tasks), "__call__") as call: + client.list_tasks() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == cloudtasks.ListTasksRequest() + + @pytest.mark.asyncio async def test_list_tasks_async( transport: str = "grpc_asyncio", request_type=cloudtasks.ListTasksRequest ): client = CloudTasksAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -2900,18 +2970,15 @@ async def test_list_tasks_async( call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( cloudtasks.ListTasksResponse(next_page_token="next_page_token_value",) ) - response = await client.list_tasks(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == cloudtasks.ListTasksRequest() # Establish that the response is the type that we expect. assert isinstance(response, pagers.ListTasksAsyncPager) - assert response.next_page_token == "next_page_token_value" @@ -2921,17 +2988,17 @@ async def test_list_tasks_async_from_dict(): def test_list_tasks_field_headers(): - client = CloudTasksClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = cloudtasks.ListTasksRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_tasks), "__call__") as call: call.return_value = cloudtasks.ListTasksResponse() - client.list_tasks(request) # Establish that the underlying gRPC stub method was called. @@ -2946,11 +3013,12 @@ def test_list_tasks_field_headers(): @pytest.mark.asyncio async def test_list_tasks_field_headers_async(): - client = CloudTasksAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = cloudtasks.ListTasksRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -2958,7 +3026,6 @@ async def test_list_tasks_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( cloudtasks.ListTasksResponse() ) - await client.list_tasks(request) # Establish that the underlying gRPC stub method was called. @@ -2972,13 +3039,12 @@ async def test_list_tasks_field_headers_async(): def test_list_tasks_flattened(): - client = CloudTasksClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_tasks), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = cloudtasks.ListTasksResponse() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.list_tasks(parent="parent_value",) @@ -2987,12 +3053,11 @@ def test_list_tasks_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" def test_list_tasks_flattened_error(): - client = CloudTasksClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -3004,7 +3069,7 @@ def test_list_tasks_flattened_error(): @pytest.mark.asyncio async def test_list_tasks_flattened_async(): - client = CloudTasksAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_tasks), "__call__") as call: @@ -3022,13 +3087,12 @@ async def test_list_tasks_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_tasks_flattened_error_async(): - client = CloudTasksAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -3039,7 +3103,7 @@ async def test_list_tasks_flattened_error_async(): def test_list_tasks_pager(): - client = CloudTasksClient(credentials=credentials.AnonymousCredentials,) + client = CloudTasksClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_tasks), "__call__") as call: @@ -3068,7 +3132,7 @@ def test_list_tasks_pager(): def test_list_tasks_pages(): - client = CloudTasksClient(credentials=credentials.AnonymousCredentials,) + client = CloudTasksClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_tasks), "__call__") as call: @@ -3089,7 +3153,7 @@ def test_list_tasks_pages(): @pytest.mark.asyncio async def test_list_tasks_async_pager(): - client = CloudTasksAsyncClient(credentials=credentials.AnonymousCredentials,) + client = CloudTasksAsyncClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -3117,7 +3181,7 @@ async def test_list_tasks_async_pager(): @pytest.mark.asyncio async def test_list_tasks_async_pages(): - client = CloudTasksAsyncClient(credentials=credentials.AnonymousCredentials,) + client = CloudTasksAsyncClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -3142,7 +3206,7 @@ async def test_list_tasks_async_pages(): def test_get_task(transport: str = "grpc", request_type=cloudtasks.GetTaskRequest): client = CloudTasksClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -3161,25 +3225,18 @@ def test_get_task(transport: str = "grpc", request_type=cloudtasks.GetTaskReques http_method=target.HttpMethod.POST ), ) - response = client.get_task(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == cloudtasks.GetTaskRequest() # Establish that the response is the type that we expect. - assert isinstance(response, task.Task) - assert response.name == "name_value" - assert response.dispatch_count == 1496 - assert response.response_count == 1527 - assert response.view == task.Task.View.BASIC @@ -3187,12 +3244,27 @@ def test_get_task_from_dict(): test_get_task(request_type=dict) +def test_get_task_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 = CloudTasksClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_task), "__call__") as call: + client.get_task() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == cloudtasks.GetTaskRequest() + + @pytest.mark.asyncio async def test_get_task_async( transport: str = "grpc_asyncio", request_type=cloudtasks.GetTaskRequest ): client = CloudTasksAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -3210,24 +3282,18 @@ async def test_get_task_async( view=task.Task.View.BASIC, ) ) - response = await client.get_task(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == cloudtasks.GetTaskRequest() # Establish that the response is the type that we expect. assert isinstance(response, task.Task) - assert response.name == "name_value" - assert response.dispatch_count == 1496 - assert response.response_count == 1527 - assert response.view == task.Task.View.BASIC @@ -3237,17 +3303,17 @@ async def test_get_task_async_from_dict(): def test_get_task_field_headers(): - client = CloudTasksClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = cloudtasks.GetTaskRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_task), "__call__") as call: call.return_value = task.Task() - client.get_task(request) # Establish that the underlying gRPC stub method was called. @@ -3262,17 +3328,17 @@ def test_get_task_field_headers(): @pytest.mark.asyncio async def test_get_task_field_headers_async(): - client = CloudTasksAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = cloudtasks.GetTaskRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_task), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(task.Task()) - await client.get_task(request) # Establish that the underlying gRPC stub method was called. @@ -3286,13 +3352,12 @@ async def test_get_task_field_headers_async(): def test_get_task_flattened(): - client = CloudTasksClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_task), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = task.Task() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.get_task(name="name_value",) @@ -3301,12 +3366,11 @@ def test_get_task_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" def test_get_task_flattened_error(): - client = CloudTasksClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -3318,7 +3382,7 @@ def test_get_task_flattened_error(): @pytest.mark.asyncio async def test_get_task_flattened_async(): - client = CloudTasksAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_task), "__call__") as call: @@ -3334,13 +3398,12 @@ async def test_get_task_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_task_flattened_error_async(): - client = CloudTasksAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -3354,7 +3417,7 @@ def test_create_task( transport: str = "grpc", request_type=cloudtasks.CreateTaskRequest ): client = CloudTasksClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -3373,25 +3436,18 @@ def test_create_task( http_method=target.HttpMethod.POST ), ) - response = client.create_task(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == cloudtasks.CreateTaskRequest() # Establish that the response is the type that we expect. - assert isinstance(response, gct_task.Task) - assert response.name == "name_value" - assert response.dispatch_count == 1496 - assert response.response_count == 1527 - assert response.view == gct_task.Task.View.BASIC @@ -3399,12 +3455,27 @@ def test_create_task_from_dict(): test_create_task(request_type=dict) +def test_create_task_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 = CloudTasksClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.create_task), "__call__") as call: + client.create_task() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == cloudtasks.CreateTaskRequest() + + @pytest.mark.asyncio async def test_create_task_async( transport: str = "grpc_asyncio", request_type=cloudtasks.CreateTaskRequest ): client = CloudTasksAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -3422,24 +3493,18 @@ async def test_create_task_async( view=gct_task.Task.View.BASIC, ) ) - response = await client.create_task(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == cloudtasks.CreateTaskRequest() # Establish that the response is the type that we expect. assert isinstance(response, gct_task.Task) - assert response.name == "name_value" - assert response.dispatch_count == 1496 - assert response.response_count == 1527 - assert response.view == gct_task.Task.View.BASIC @@ -3449,17 +3514,17 @@ async def test_create_task_async_from_dict(): def test_create_task_field_headers(): - client = CloudTasksClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = cloudtasks.CreateTaskRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.create_task), "__call__") as call: call.return_value = gct_task.Task() - client.create_task(request) # Establish that the underlying gRPC stub method was called. @@ -3474,17 +3539,17 @@ def test_create_task_field_headers(): @pytest.mark.asyncio async def test_create_task_field_headers_async(): - client = CloudTasksAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = cloudtasks.CreateTaskRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.create_task), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gct_task.Task()) - await client.create_task(request) # Establish that the underlying gRPC stub method was called. @@ -3498,13 +3563,12 @@ async def test_create_task_field_headers_async(): def test_create_task_flattened(): - client = CloudTasksClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.create_task), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = gct_task.Task() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.create_task( @@ -3515,14 +3579,12 @@ def test_create_task_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" - assert args[0].task == gct_task.Task(name="name_value") def test_create_task_flattened_error(): - client = CloudTasksClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -3536,7 +3598,7 @@ def test_create_task_flattened_error(): @pytest.mark.asyncio async def test_create_task_flattened_async(): - client = CloudTasksAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.create_task), "__call__") as call: @@ -3554,15 +3616,13 @@ async def test_create_task_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" - assert args[0].task == gct_task.Task(name="name_value") @pytest.mark.asyncio async def test_create_task_flattened_error_async(): - client = CloudTasksAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -3578,7 +3638,7 @@ def test_delete_task( transport: str = "grpc", request_type=cloudtasks.DeleteTaskRequest ): client = CloudTasksClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -3589,13 +3649,11 @@ def test_delete_task( with mock.patch.object(type(client.transport.delete_task), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = None - response = client.delete_task(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == cloudtasks.DeleteTaskRequest() # Establish that the response is the type that we expect. @@ -3606,12 +3664,27 @@ def test_delete_task_from_dict(): test_delete_task(request_type=dict) +def test_delete_task_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 = CloudTasksClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_task), "__call__") as call: + client.delete_task() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == cloudtasks.DeleteTaskRequest() + + @pytest.mark.asyncio async def test_delete_task_async( transport: str = "grpc_asyncio", request_type=cloudtasks.DeleteTaskRequest ): client = CloudTasksAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -3622,13 +3695,11 @@ async def test_delete_task_async( with mock.patch.object(type(client.transport.delete_task), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_task(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == cloudtasks.DeleteTaskRequest() # Establish that the response is the type that we expect. @@ -3641,17 +3712,17 @@ async def test_delete_task_async_from_dict(): def test_delete_task_field_headers(): - client = CloudTasksClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = cloudtasks.DeleteTaskRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.delete_task), "__call__") as call: call.return_value = None - client.delete_task(request) # Establish that the underlying gRPC stub method was called. @@ -3666,17 +3737,17 @@ def test_delete_task_field_headers(): @pytest.mark.asyncio async def test_delete_task_field_headers_async(): - client = CloudTasksAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = cloudtasks.DeleteTaskRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.delete_task), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_task(request) # Establish that the underlying gRPC stub method was called. @@ -3690,13 +3761,12 @@ async def test_delete_task_field_headers_async(): def test_delete_task_flattened(): - client = CloudTasksClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.delete_task), "__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_task(name="name_value",) @@ -3705,12 +3775,11 @@ def test_delete_task_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" def test_delete_task_flattened_error(): - client = CloudTasksClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -3722,7 +3791,7 @@ def test_delete_task_flattened_error(): @pytest.mark.asyncio async def test_delete_task_flattened_async(): - client = CloudTasksAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.delete_task), "__call__") as call: @@ -3738,13 +3807,12 @@ async def test_delete_task_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_task_flattened_error_async(): - client = CloudTasksAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -3756,7 +3824,7 @@ async def test_delete_task_flattened_error_async(): def test_run_task(transport: str = "grpc", request_type=cloudtasks.RunTaskRequest): client = CloudTasksClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -3775,25 +3843,18 @@ def test_run_task(transport: str = "grpc", request_type=cloudtasks.RunTaskReques http_method=target.HttpMethod.POST ), ) - response = client.run_task(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == cloudtasks.RunTaskRequest() # Establish that the response is the type that we expect. - assert isinstance(response, task.Task) - assert response.name == "name_value" - assert response.dispatch_count == 1496 - assert response.response_count == 1527 - assert response.view == task.Task.View.BASIC @@ -3801,12 +3862,27 @@ def test_run_task_from_dict(): test_run_task(request_type=dict) +def test_run_task_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 = CloudTasksClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.run_task), "__call__") as call: + client.run_task() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == cloudtasks.RunTaskRequest() + + @pytest.mark.asyncio async def test_run_task_async( transport: str = "grpc_asyncio", request_type=cloudtasks.RunTaskRequest ): client = CloudTasksAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -3824,24 +3900,18 @@ async def test_run_task_async( view=task.Task.View.BASIC, ) ) - response = await client.run_task(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == cloudtasks.RunTaskRequest() # Establish that the response is the type that we expect. assert isinstance(response, task.Task) - assert response.name == "name_value" - assert response.dispatch_count == 1496 - assert response.response_count == 1527 - assert response.view == task.Task.View.BASIC @@ -3851,17 +3921,17 @@ async def test_run_task_async_from_dict(): def test_run_task_field_headers(): - client = CloudTasksClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = cloudtasks.RunTaskRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.run_task), "__call__") as call: call.return_value = task.Task() - client.run_task(request) # Establish that the underlying gRPC stub method was called. @@ -3876,17 +3946,17 @@ def test_run_task_field_headers(): @pytest.mark.asyncio async def test_run_task_field_headers_async(): - client = CloudTasksAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = cloudtasks.RunTaskRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.run_task), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(task.Task()) - await client.run_task(request) # Establish that the underlying gRPC stub method was called. @@ -3900,13 +3970,12 @@ async def test_run_task_field_headers_async(): def test_run_task_flattened(): - client = CloudTasksClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.run_task), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = task.Task() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.run_task(name="name_value",) @@ -3915,12 +3984,11 @@ def test_run_task_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" def test_run_task_flattened_error(): - client = CloudTasksClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -3932,7 +4000,7 @@ def test_run_task_flattened_error(): @pytest.mark.asyncio async def test_run_task_flattened_async(): - client = CloudTasksAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.run_task), "__call__") as call: @@ -3948,13 +4016,12 @@ async def test_run_task_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_run_task_flattened_error_async(): - client = CloudTasksAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -3967,16 +4034,16 @@ async def test_run_task_flattened_error_async(): def test_credentials_transport_error(): # It is an error to provide credentials and a transport instance. transport = transports.CloudTasksGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = CloudTasksClient( - 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.CloudTasksGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = CloudTasksClient( @@ -3986,7 +4053,7 @@ def test_credentials_transport_error(): # It is an error to provide scopes and a transport instance. transport = transports.CloudTasksGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = CloudTasksClient( @@ -3997,7 +4064,7 @@ def test_credentials_transport_error(): def test_transport_instance(): # A client may be instantiated with a custom transport instance. transport = transports.CloudTasksGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) client = CloudTasksClient(transport=transport) assert client.transport is transport @@ -4006,13 +4073,13 @@ def test_transport_instance(): def test_transport_get_channel(): # A client may be instantiated with a custom transport instance. transport = transports.CloudTasksGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) channel = transport.grpc_channel assert channel transport = transports.CloudTasksGrpcAsyncIOTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) channel = transport.grpc_channel assert channel @@ -4024,23 +4091,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 = CloudTasksClient(credentials=credentials.AnonymousCredentials(),) + client = CloudTasksClient(credentials=ga_credentials.AnonymousCredentials(),) assert isinstance(client.transport, transports.CloudTasksGrpcTransport,) def test_cloud_tasks_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.CloudTasksTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), credentials_file="credentials.json", ) @@ -4052,7 +4119,7 @@ def test_cloud_tasks_base_transport(): ) as Transport: Transport.return_value = None transport = transports.CloudTasksTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Every method on the transport should just blindly @@ -4080,15 +4147,37 @@ def test_cloud_tasks_base_transport(): getattr(transport, method)(request=object()) +@requires_google_auth_gte_1_25_0 def test_cloud_tasks_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.cloud.tasks_v2beta3.services.cloud_tasks.transports.CloudTasksTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.CloudTasksTransport( + 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",), + quota_project_id="octopus", + ) + + +@requires_google_auth_lt_1_25_0 +def test_cloud_tasks_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.cloud.tasks_v2beta3.services.cloud_tasks.transports.CloudTasksTransport._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.CloudTasksTransport( credentials_file="credentials.json", quota_project_id="octopus", ) @@ -4101,19 +4190,33 @@ def test_cloud_tasks_base_transport_with_credentials_file(): def test_cloud_tasks_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.cloud.tasks_v2beta3.services.cloud_tasks.transports.CloudTasksTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - adc.return_value = (credentials.AnonymousCredentials(), None) + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.CloudTasksTransport() adc.assert_called_once() +@requires_google_auth_gte_1_25_0 def test_cloud_tasks_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) + CloudTasksClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=("https://www.googleapis.com/auth/cloud-platform",), + quota_project_id=None, + ) + + +@requires_google_auth_lt_1_25_0 +def test_cloud_tasks_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) CloudTasksClient() adc.assert_called_once_with( scopes=("https://www.googleapis.com/auth/cloud-platform",), @@ -4121,26 +4224,156 @@ def test_cloud_tasks_auth_adc(): ) -def test_cloud_tasks_transport_auth_adc(): +@pytest.mark.parametrize( + "transport_class", + [transports.CloudTasksGrpcTransport, transports.CloudTasksGrpcAsyncIOTransport,], +) +@requires_google_auth_gte_1_25_0 +def test_cloud_tasks_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.CloudTasksGrpcTransport( - 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",), + quota_project_id="octopus", ) + + +@pytest.mark.parametrize( + "transport_class", + [transports.CloudTasksGrpcTransport, transports.CloudTasksGrpcAsyncIOTransport,], +) +@requires_google_auth_lt_1_25_0 +def test_cloud_tasks_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",), quota_project_id="octopus", ) +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.CloudTasksGrpcTransport, grpc_helpers), + (transports.CloudTasksGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_gte_1_26_0 +def test_cloud_tasks_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( + "cloudtasks.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + default_scopes=("https://www.googleapis.com/auth/cloud-platform",), + scopes=["1", "2"], + default_host="cloudtasks.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.CloudTasksGrpcTransport, grpc_helpers), + (transports.CloudTasksGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_cloud_tasks_transport_create_channel_old_api_core( + transport_class, grpc_helpers +): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class(quota_project_id="octopus") + + create_channel.assert_called_with( + "cloudtasks.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + scopes=("https://www.googleapis.com/auth/cloud-platform",), + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.CloudTasksGrpcTransport, grpc_helpers), + (transports.CloudTasksGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_cloud_tasks_transport_create_channel_user_scopes( + transport_class, grpc_helpers +): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + + create_channel.assert_called_with( + "cloudtasks.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + scopes=["1", "2"], + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + @pytest.mark.parametrize( "transport_class", [transports.CloudTasksGrpcTransport, transports.CloudTasksGrpcAsyncIOTransport], ) def test_cloud_tasks_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: @@ -4179,7 +4412,7 @@ def test_cloud_tasks_grpc_transport_client_cert_source_for_mtls(transport_class) def test_cloud_tasks_host_no_port(): client = CloudTasksClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="cloudtasks.googleapis.com" ), @@ -4189,7 +4422,7 @@ def test_cloud_tasks_host_no_port(): def test_cloud_tasks_host_with_port(): client = CloudTasksClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="cloudtasks.googleapis.com:8000" ), @@ -4240,9 +4473,9 @@ def test_cloud_tasks_transport_channel_mtls_with_client_cert_source(transport_cl 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", @@ -4317,7 +4550,6 @@ def test_queue_path(): project = "squid" location = "clam" queue = "whelk" - expected = "projects/{project}/locations/{location}/queues/{queue}".format( project=project, location=location, queue=queue, ) @@ -4343,7 +4575,6 @@ def test_task_path(): location = "mussel" queue = "winkle" task = "nautilus" - expected = "projects/{project}/locations/{location}/queues/{queue}/tasks/{task}".format( project=project, location=location, queue=queue, task=task, ) @@ -4367,7 +4598,6 @@ def test_parse_task_path(): def test_common_billing_account_path(): billing_account = "whelk" - expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -4388,7 +4618,6 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): folder = "oyster" - expected = "folders/{folder}".format(folder=folder,) actual = CloudTasksClient.common_folder_path(folder) assert expected == actual @@ -4407,7 +4636,6 @@ def test_parse_common_folder_path(): def test_common_organization_path(): organization = "cuttlefish" - expected = "organizations/{organization}".format(organization=organization,) actual = CloudTasksClient.common_organization_path(organization) assert expected == actual @@ -4426,7 +4654,6 @@ def test_parse_common_organization_path(): def test_common_project_path(): project = "winkle" - expected = "projects/{project}".format(project=project,) actual = CloudTasksClient.common_project_path(project) assert expected == actual @@ -4446,7 +4673,6 @@ def test_parse_common_project_path(): def test_common_location_path(): project = "scallop" location = "abalone" - expected = "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -4473,7 +4699,7 @@ def test_client_withDEFAULT_CLIENT_INFO(): transports.CloudTasksTransport, "_prep_wrapped_messages" ) as prep: client = CloudTasksClient( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) @@ -4482,6 +4708,6 @@ def test_client_withDEFAULT_CLIENT_INFO(): ) as prep: transport_class = CloudTasksClient.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)