From 511e9f3d5da4c8b86adca8bddc65dc37a989edcf Mon Sep 17 00:00:00 2001 From: Yoshi Automation Bot Date: Mon, 7 Dec 2020 15:48:38 -0800 Subject: [PATCH] feat: add common resource helpers; expose client transport; add shebang to fixup scripts (#34) --- .kokoro/docs/common.cfg | 2 +- .kokoro/populate-secrets.sh | 43 + .kokoro/release/common.cfg | 50 +- .kokoro/samples/python3.6/common.cfg | 6 + .kokoro/samples/python3.7/common.cfg | 6 + .kokoro/samples/python3.8/common.cfg | 6 + .kokoro/test-samples.sh | 8 +- .kokoro/trampoline.sh | 15 +- .pre-commit-config.yaml | 17 + CODE_OF_CONDUCT.md | 123 +- CONTRIBUTING.rst | 29 +- docs/conf.py | 10 +- docs/tasks_v2/types.rst | 1 + docs/tasks_v2beta2/types.rst | 1 + docs/tasks_v2beta3/types.rst | 1 + .../services/cloud_tasks/async_client.py | 147 +- .../tasks_v2/services/cloud_tasks/client.py | 193 ++- .../services/cloud_tasks/transports/base.py | 16 +- .../services/cloud_tasks/transports/grpc.py | 64 +- .../cloud_tasks/transports/grpc_asyncio.py | 55 +- .../services/cloud_tasks/async_client.py | 159 +- .../services/cloud_tasks/client.py | 193 ++- .../services/cloud_tasks/transports/base.py | 16 +- .../services/cloud_tasks/transports/grpc.py | 64 +- .../cloud_tasks/transports/grpc_asyncio.py | 55 +- .../services/cloud_tasks/async_client.py | 147 +- .../services/cloud_tasks/client.py | 193 ++- .../services/cloud_tasks/transports/base.py | 16 +- .../services/cloud_tasks/transports/grpc.py | 64 +- .../cloud_tasks/transports/grpc_asyncio.py | 55 +- google/cloud/tasks_v2beta3/types/queue.py | 4 +- noxfile.py | 17 +- samples/snippets/noxfile.py | 39 +- scripts/decrypt-secrets.sh | 15 +- scripts/fixup_tasks_v2_keywords.py | 1 + scripts/fixup_tasks_v2beta2_keywords.py | 1 + scripts/fixup_tasks_v2beta3_keywords.py | 1 + synth.metadata | 16 +- synth.py | 3 - tests/unit/gapic/tasks_v2/test_cloud_tasks.py | 1149 ++++++++------- .../gapic/tasks_v2beta2/test_cloud_tasks.py | 1304 +++++++++-------- .../gapic/tasks_v2beta3/test_cloud_tasks.py | 1219 ++++++++------- 42 files changed, 3297 insertions(+), 2227 deletions(-) create mode 100755 .kokoro/populate-secrets.sh create mode 100644 .pre-commit-config.yaml diff --git a/.kokoro/docs/common.cfg b/.kokoro/docs/common.cfg index 832ce9a2..095814be 100644 --- a/.kokoro/docs/common.cfg +++ b/.kokoro/docs/common.cfg @@ -30,7 +30,7 @@ env_vars: { env_vars: { key: "V2_STAGING_BUCKET" - value: "docs-staging-v2-staging" + value: "docs-staging-v2" } # It will upload the docker image after successful builds. diff --git a/.kokoro/populate-secrets.sh b/.kokoro/populate-secrets.sh new file mode 100755 index 00000000..f5251425 --- /dev/null +++ b/.kokoro/populate-secrets.sh @@ -0,0 +1,43 @@ +#!/bin/bash +# Copyright 2020 Google LLC. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +set -eo pipefail + +function now { date +"%Y-%m-%d %H:%M:%S" | tr -d '\n' ;} +function msg { println "$*" >&2 ;} +function println { printf '%s\n' "$(now) $*" ;} + + +# Populates requested secrets set in SECRET_MANAGER_KEYS from service account: +# kokoro-trampoline@cloud-devrel-kokoro-resources.iam.gserviceaccount.com +SECRET_LOCATION="${KOKORO_GFILE_DIR}/secret_manager" +msg "Creating folder on disk for secrets: ${SECRET_LOCATION}" +mkdir -p ${SECRET_LOCATION} +for key in $(echo ${SECRET_MANAGER_KEYS} | sed "s/,/ /g") +do + msg "Retrieving secret ${key}" + docker run --entrypoint=gcloud \ + --volume=${KOKORO_GFILE_DIR}:${KOKORO_GFILE_DIR} \ + gcr.io/google.com/cloudsdktool/cloud-sdk \ + secrets versions access latest \ + --project cloud-devrel-kokoro-resources \ + --secret ${key} > \ + "${SECRET_LOCATION}/${key}" + if [[ $? == 0 ]]; then + msg "Secret written to ${SECRET_LOCATION}/${key}" + else + msg "Error retrieving secret ${key}" + fi +done diff --git a/.kokoro/release/common.cfg b/.kokoro/release/common.cfg index 79054a6a..bef59347 100644 --- a/.kokoro/release/common.cfg +++ b/.kokoro/release/common.cfg @@ -23,42 +23,18 @@ env_vars: { value: "github/python-tasks/.kokoro/release.sh" } -# Fetch the token needed for reporting release status to GitHub -before_action { - fetch_keystore { - keystore_resource { - keystore_config_id: 73713 - keyname: "yoshi-automation-github-key" - } - } -} - -# Fetch PyPI password -before_action { - fetch_keystore { - keystore_resource { - keystore_config_id: 73713 - keyname: "google_cloud_pypi_password" - } - } -} - -# Fetch magictoken to use with Magic Github Proxy -before_action { - fetch_keystore { - keystore_resource { - keystore_config_id: 73713 - keyname: "releasetool-magictoken" - } - } +# Fetch PyPI password +before_action { + fetch_keystore { + keystore_resource { + keystore_config_id: 73713 + keyname: "google_cloud_pypi_password" + } + } } -# Fetch api key to use with Magic Github Proxy -before_action { - fetch_keystore { - keystore_resource { - keystore_config_id: 73713 - keyname: "magic-github-proxy-api-key" - } - } -} +# 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 diff --git a/.kokoro/samples/python3.6/common.cfg b/.kokoro/samples/python3.6/common.cfg index d999f828..20a9c132 100644 --- a/.kokoro/samples/python3.6/common.cfg +++ b/.kokoro/samples/python3.6/common.cfg @@ -13,6 +13,12 @@ env_vars: { value: "py-3.6" } +# Declare build specific Cloud project. +env_vars: { + key: "BUILD_SPECIFIC_GCLOUD_PROJECT" + value: "python-docs-samples-tests-py36" +} + env_vars: { key: "TRAMPOLINE_BUILD_FILE" value: "github/python-tasks/.kokoro/test-samples.sh" diff --git a/.kokoro/samples/python3.7/common.cfg b/.kokoro/samples/python3.7/common.cfg index 70c5a021..3f4d453b 100644 --- a/.kokoro/samples/python3.7/common.cfg +++ b/.kokoro/samples/python3.7/common.cfg @@ -13,6 +13,12 @@ env_vars: { value: "py-3.7" } +# Declare build specific Cloud project. +env_vars: { + key: "BUILD_SPECIFIC_GCLOUD_PROJECT" + value: "python-docs-samples-tests-py37" +} + env_vars: { key: "TRAMPOLINE_BUILD_FILE" value: "github/python-tasks/.kokoro/test-samples.sh" diff --git a/.kokoro/samples/python3.8/common.cfg b/.kokoro/samples/python3.8/common.cfg index d9216c2b..9d61066d 100644 --- a/.kokoro/samples/python3.8/common.cfg +++ b/.kokoro/samples/python3.8/common.cfg @@ -13,6 +13,12 @@ env_vars: { value: "py-3.8" } +# Declare build specific Cloud project. +env_vars: { + key: "BUILD_SPECIFIC_GCLOUD_PROJECT" + value: "python-docs-samples-tests-py38" +} + env_vars: { key: "TRAMPOLINE_BUILD_FILE" value: "github/python-tasks/.kokoro/test-samples.sh" diff --git a/.kokoro/test-samples.sh b/.kokoro/test-samples.sh index b2c51ae2..fd088577 100755 --- a/.kokoro/test-samples.sh +++ b/.kokoro/test-samples.sh @@ -28,6 +28,12 @@ if [[ $KOKORO_BUILD_ARTIFACTS_SUBDIR = *"periodic"* ]]; then 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 @@ -101,4 +107,4 @@ cd "$ROOT" # Workaround for Kokoro permissions issue: delete secrets rm testing/{test-env.sh,client-secrets.json,service-account.json} -exit "$RTN" \ No newline at end of file +exit "$RTN" diff --git a/.kokoro/trampoline.sh b/.kokoro/trampoline.sh index e8c4251f..f39236e9 100755 --- a/.kokoro/trampoline.sh +++ b/.kokoro/trampoline.sh @@ -15,9 +15,14 @@ set -eo pipefail -python3 "${KOKORO_GFILE_DIR}/trampoline_v1.py" || ret_code=$? +# Always run the cleanup script, regardless of the success of bouncing into +# the container. +function cleanup() { + chmod +x ${KOKORO_GFILE_DIR}/trampoline_cleanup.sh + ${KOKORO_GFILE_DIR}/trampoline_cleanup.sh + echo "cleanup"; +} +trap cleanup EXIT -chmod +x ${KOKORO_GFILE_DIR}/trampoline_cleanup.sh -${KOKORO_GFILE_DIR}/trampoline_cleanup.sh || true - -exit ${ret_code} +$(dirname $0)/populate-secrets.sh # Secret Manager secrets. +python3 "${KOKORO_GFILE_DIR}/trampoline_v1.py" \ No newline at end of file diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml new file mode 100644 index 00000000..6ad83346 --- /dev/null +++ b/.pre-commit-config.yaml @@ -0,0 +1,17 @@ +# See https://pre-commit.com for more information +# See https://pre-commit.com/hooks.html for more hooks +repos: +- repo: https://github.com/pre-commit/pre-commit-hooks + rev: v3.3.0 + hooks: + - id: trailing-whitespace + - id: end-of-file-fixer + - id: check-yaml +- repo: https://github.com/psf/black + rev: 19.10b0 + hooks: + - id: black +- repo: https://gitlab.com/pycqa/flake8 + rev: 3.8.4 + hooks: + - id: flake8 diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md index b3d1f602..039f4368 100644 --- a/CODE_OF_CONDUCT.md +++ b/CODE_OF_CONDUCT.md @@ -1,44 +1,95 @@ -# Contributor Code of Conduct +# Code of Conduct -As contributors and maintainers of this project, -and in the interest of fostering an open and welcoming community, -we pledge to respect all people who contribute through reporting issues, -posting feature requests, updating documentation, -submitting pull requests or patches, and other activities. +## Our Pledge -We are committed to making participation in this project -a harassment-free experience for everyone, -regardless of level of experience, gender, gender identity and expression, -sexual orientation, disability, personal appearance, -body size, race, ethnicity, age, religion, or nationality. +In the interest of fostering an open and welcoming environment, we as +contributors and maintainers pledge to making participation in our project and +our community a harassment-free experience for everyone, regardless of age, body +size, disability, ethnicity, gender identity and expression, level of +experience, education, socio-economic status, nationality, personal appearance, +race, religion, or sexual identity and orientation. + +## Our Standards + +Examples of behavior that contributes to creating a positive environment +include: + +* Using welcoming and inclusive language +* Being respectful of differing viewpoints and experiences +* Gracefully accepting constructive criticism +* Focusing on what is best for the community +* Showing empathy towards other community members Examples of unacceptable behavior by participants include: -* The use of sexualized language or imagery -* Personal attacks -* Trolling or insulting/derogatory comments -* Public or private harassment -* Publishing other's private information, -such as physical or electronic -addresses, without explicit permission -* Other unethical or unprofessional conduct. +* The use of sexualized language or imagery and unwelcome sexual attention or + advances +* Trolling, insulting/derogatory comments, and personal or political attacks +* Public or private harassment +* Publishing others' private information, such as a physical or electronic + address, without explicit permission +* Other conduct which could reasonably be considered inappropriate in a + professional setting + +## Our Responsibilities + +Project maintainers are responsible for clarifying the standards of acceptable +behavior and are expected to take appropriate and fair corrective action in +response to any instances of unacceptable behavior. Project maintainers have the right and responsibility to remove, edit, or reject -comments, commits, code, wiki edits, issues, and other contributions -that are not aligned to this Code of Conduct. -By adopting this Code of Conduct, -project maintainers commit themselves to fairly and consistently -applying these principles to every aspect of managing this project. -Project maintainers who do not follow or enforce the Code of Conduct -may be permanently removed from the project team. - -This code of conduct applies both within project spaces and in public spaces -when an individual is representing the project or its community. - -Instances of abusive, harassing, or otherwise unacceptable behavior -may be reported by opening an issue -or contacting one or more of the project maintainers. - -This Code of Conduct is adapted from the [Contributor Covenant](http://contributor-covenant.org), version 1.2.0, -available at [http://contributor-covenant.org/version/1/2/0/](http://contributor-covenant.org/version/1/2/0/) +comments, commits, code, wiki edits, issues, and other contributions that are +not aligned to this Code of Conduct, or to ban temporarily or permanently any +contributor for other behaviors that they deem inappropriate, threatening, +offensive, or harmful. + +## Scope + +This Code of Conduct applies both within project spaces and in public spaces +when an individual is representing the project or its community. Examples of +representing a project or community include using an official project e-mail +address, posting via an official social media account, or acting as an appointed +representative at an online or offline event. Representation of a project may be +further defined and clarified by project maintainers. + +This Code of Conduct also applies outside the project spaces when the Project +Steward has a reasonable belief that an individual's behavior may have a +negative impact on the project or its community. + +## Conflict Resolution + +We do not believe that all conflict is bad; healthy debate and disagreement +often yield positive results. However, it is never okay to be disrespectful or +to engage in behavior that violates the project’s code of conduct. + +If you see someone violating the code of conduct, you are encouraged to address +the behavior directly with those involved. Many issues can be resolved quickly +and easily, and this gives people more control over the outcome of their +dispute. If you are unable to resolve the matter for any reason, or if the +behavior is threatening or harassing, report it. We are dedicated to providing +an environment where participants feel welcome and safe. + + +Reports should be directed to *googleapis-stewards@google.com*, the +Project Steward(s) for *Google Cloud Client Libraries*. It is the Project Steward’s duty to +receive and address reported violations of the code of conduct. They will then +work with a committee consisting of representatives from the Open Source +Programs Office and the Google Open Source Strategy team. If for any reason you +are uncomfortable reaching out to the Project Steward, please email +opensource@google.com. + +We will investigate every complaint, but you may not receive a direct response. +We will use our discretion in determining when and how to follow up on reported +incidents, which may range from not taking action to permanent expulsion from +the project and project-sponsored spaces. We will notify the accused of the +report and provide them an opportunity to discuss it before any action is taken. +The identity of the reporter will be omitted from the details of the report +supplied to the accused. In potentially harmful situations, such as ongoing +harassment or threats to anyone's safety, we may take action without notice. + +## Attribution + +This Code of Conduct is adapted from the Contributor Covenant, version 1.4, +available at +https://www.contributor-covenant.org/version/1/4/code-of-conduct.html \ No newline at end of file diff --git a/CONTRIBUTING.rst b/CONTRIBUTING.rst index 31d020a2..40e2ef6b 100644 --- a/CONTRIBUTING.rst +++ b/CONTRIBUTING.rst @@ -80,25 +80,6 @@ We use `nox `__ to instrument our tests. .. nox: https://pypi.org/project/nox/ -Note on Editable Installs / Develop Mode -======================================== - -- As mentioned previously, using ``setuptools`` in `develop mode`_ - or a ``pip`` `editable install`_ is not possible with this - library. This is because this library uses `namespace packages`_. - For context see `Issue #2316`_ and the relevant `PyPA issue`_. - - Since ``editable`` / ``develop`` mode can't be used, packages - need to be installed directly. Hence your changes to the source - tree don't get incorporated into the **already installed** - package. - -.. _namespace packages: https://www.python.org/dev/peps/pep-0420/ -.. _Issue #2316: https://github.com/GoogleCloudPlatform/google-cloud-python/issues/2316 -.. _PyPA issue: https://github.com/pypa/packaging-problems/issues/12 -.. _develop mode: https://setuptools.readthedocs.io/en/latest/setuptools.html#development-mode -.. _editable install: https://pip.pypa.io/en/stable/reference/pip_install/#editable-installs - ***************************************** I'm getting weird errors... Can you help? ***************************************** @@ -130,6 +111,16 @@ Coding Style should point to the official ``googleapis`` checkout and the the branch should be the main branch on that remote (``master``). +- This repository contains configuration for the + `pre-commit `__ tool, which automates checking + our linters during a commit. If you have it installed on your ``$PATH``, + you can enable enforcing those checks via: + +.. code-block:: bash + + $ pre-commit install + pre-commit installed at .git/hooks/pre-commit + Exceptions to PEP8: - Many unit tests use a helper method, ``_call_fut`` ("FUT" is short for diff --git a/docs/conf.py b/docs/conf.py index 1b881e42..00ccf92b 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -29,7 +29,7 @@ # -- General configuration ------------------------------------------------ # If your documentation needs a minimal Sphinx version, state it here. -needs_sphinx = "1.6.3" +needs_sphinx = "1.5.5" # Add any Sphinx extension module names here, as strings. They can be # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom @@ -39,6 +39,7 @@ "sphinx.ext.autosummary", "sphinx.ext.intersphinx", "sphinx.ext.coverage", + "sphinx.ext.doctest", "sphinx.ext.napoleon", "sphinx.ext.todo", "sphinx.ext.viewcode", @@ -344,10 +345,11 @@ # Example configuration for intersphinx: refer to the Python standard library. intersphinx_mapping = { - "python": ("http://python.readthedocs.org/en/latest/", None), - "google-auth": ("https://google-auth.readthedocs.io/en/stable", None), + "python": ("https://python.readthedocs.org/en/latest/", None), + "google-auth": ("https://googleapis.dev/python/google-auth/latest/", None), "google.api_core": ("https://googleapis.dev/python/google-api-core/latest/", None,), - "grpc": ("https://grpc.io/grpc/python/", None), + "grpc": ("https://grpc.github.io/grpc/python/", None), + "proto-plus": ("https://proto-plus-python.readthedocs.io/en/latest/", None), } diff --git a/docs/tasks_v2/types.rst b/docs/tasks_v2/types.rst index 886cf90e..a43c04fd 100644 --- a/docs/tasks_v2/types.rst +++ b/docs/tasks_v2/types.rst @@ -3,3 +3,4 @@ Types for Google Cloud Tasks v2 API .. automodule:: google.cloud.tasks_v2.types :members: + :show-inheritance: diff --git a/docs/tasks_v2beta2/types.rst b/docs/tasks_v2beta2/types.rst index b12cd9ed..3a8eb123 100644 --- a/docs/tasks_v2beta2/types.rst +++ b/docs/tasks_v2beta2/types.rst @@ -3,3 +3,4 @@ Types for Google Cloud Tasks v2beta2 API .. automodule:: google.cloud.tasks_v2beta2.types :members: + :show-inheritance: diff --git a/docs/tasks_v2beta3/types.rst b/docs/tasks_v2beta3/types.rst index 50611382..37d181e6 100644 --- a/docs/tasks_v2beta3/types.rst +++ b/docs/tasks_v2beta3/types.rst @@ -3,3 +3,4 @@ Types for Google Cloud Tasks v2beta3 API .. automodule:: google.cloud.tasks_v2beta3.types :members: + :show-inheritance: 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 798f3396..d1673800 100644 --- a/google/cloud/tasks_v2/services/cloud_tasks/async_client.py +++ b/google/cloud/tasks_v2/services/cloud_tasks/async_client.py @@ -57,12 +57,45 @@ class CloudTasksAsyncClient: DEFAULT_MTLS_ENDPOINT = CloudTasksClient.DEFAULT_MTLS_ENDPOINT queue_path = staticmethod(CloudTasksClient.queue_path) - + 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_file = CloudTasksClient.from_service_account_file from_service_account_json = from_service_account_file + @property + def transport(self) -> CloudTasksTransport: + """Return the transport used by the client instance. + + Returns: + CloudTasksTransport: The transport used by the client instance. + """ + return self._client.transport + get_transport_class = functools.partial( type(CloudTasksClient).get_transport_class, type(CloudTasksClient) ) @@ -89,16 +122,19 @@ def __init__( client_options (ClientOptions): Custom options for the client. It won't take effect if a ``transport`` instance is provided. (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT environment variable can also be used to override the endpoint: "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint, this is the default value for - the environment variable) and "auto" (auto switch to the default - mTLS endpoint if client SSL credentials is present). However, - the ``api_endpoint`` property takes precedence if provided. - (2) The ``client_cert_source`` property is used to provide client - SSL credentials for mutual TLS transport. If not provided, the - default SSL credentials will be used if present. + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. Raises: google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport @@ -153,7 +189,8 @@ async def list_queues( # Create or coerce a protobuf request object. # Sanity check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - if request is not None and any([parent]): + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " "the individual field arguments should be set." @@ -176,7 +213,7 @@ async def list_queues( maximum=10.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, + exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, ), ), default_timeout=10.0, @@ -242,7 +279,8 @@ async def get_queue( # Create or coerce a protobuf request object. # Sanity check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - if request is not None and any([name]): + has_flattened_params = any([name]) + if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " "the individual field arguments should be set." @@ -265,7 +303,7 @@ async def get_queue( maximum=10.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, + exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, ), ), default_timeout=10.0, @@ -349,7 +387,8 @@ async def create_queue( # Create or coerce a protobuf request object. # Sanity check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - if request is not None and any([parent, queue]): + has_flattened_params = any([parent, queue]) + if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " "the individual field arguments should be set." @@ -456,7 +495,8 @@ async def update_queue( # Create or coerce a protobuf request object. # Sanity check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - if request is not None and any([queue, update_mask]): + has_flattened_params = any([queue, update_mask]) + if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " "the individual field arguments should be set." @@ -536,7 +576,8 @@ async def delete_queue( # Create or coerce a protobuf request object. # Sanity check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - if request is not None and any([name]): + has_flattened_params = any([name]) + if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " "the individual field arguments should be set." @@ -559,7 +600,7 @@ async def delete_queue( maximum=10.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, + exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, ), ), default_timeout=10.0, @@ -623,7 +664,8 @@ async def purge_queue( # Create or coerce a protobuf request object. # Sanity check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - if request is not None and any([name]): + has_flattened_params = any([name]) + if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " "the individual field arguments should be set." @@ -705,7 +747,8 @@ async def pause_queue( # Create or coerce a protobuf request object. # Sanity check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - if request is not None and any([name]): + has_flattened_params = any([name]) + if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " "the individual field arguments should be set." @@ -794,7 +837,8 @@ async def resume_queue( # Create or coerce a protobuf request object. # Sanity check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - if request is not None and any([name]): + has_flattened_params = any([name]) + if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " "the individual field arguments should be set." @@ -938,7 +982,8 @@ async def get_iam_policy( # Create or coerce a protobuf request object. # Sanity check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - if request is not None and any([resource]): + has_flattened_params = any([resource]) + if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " "the individual field arguments should be set." @@ -950,13 +995,7 @@ async def get_iam_policy( request = iam_policy.GetIamPolicyRequest(**request) elif not request: - request = iam_policy.GetIamPolicyRequest() - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - - if resource is not None: - request.resource = resource + request = iam_policy.GetIamPolicyRequest(resource=resource,) # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. @@ -967,7 +1006,7 @@ async def get_iam_policy( maximum=10.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, + exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, ), ), default_timeout=10.0, @@ -1100,7 +1139,8 @@ async def set_iam_policy( # Create or coerce a protobuf request object. # Sanity check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - if request is not None and any([resource]): + has_flattened_params = any([resource]) + if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " "the individual field arguments should be set." @@ -1112,13 +1152,7 @@ async def set_iam_policy( request = iam_policy.SetIamPolicyRequest(**request) elif not request: - request = iam_policy.SetIamPolicyRequest() - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - - if resource is not None: - request.resource = resource + request = iam_policy.SetIamPolicyRequest(resource=resource,) # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. @@ -1194,7 +1228,8 @@ async def test_iam_permissions( # Create or coerce a protobuf request object. # Sanity check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - if request is not None and any([resource, permissions]): + has_flattened_params = any([resource, permissions]) + if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " "the individual field arguments should be set." @@ -1206,16 +1241,9 @@ async def test_iam_permissions( request = iam_policy.TestIamPermissionsRequest(**request) elif not request: - request = iam_policy.TestIamPermissionsRequest() - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - - if resource is not None: - request.resource = resource - - if permissions: - request.permissions.extend(permissions) + request = iam_policy.TestIamPermissionsRequest( + resource=resource, permissions=permissions, + ) # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. @@ -1226,7 +1254,7 @@ async def test_iam_permissions( maximum=10.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, + exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, ), ), default_timeout=10.0, @@ -1295,7 +1323,8 @@ async def list_tasks( # Create or coerce a protobuf request object. # Sanity check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - if request is not None and any([parent]): + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " "the individual field arguments should be set." @@ -1318,7 +1347,7 @@ async def list_tasks( maximum=10.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, + exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, ), ), default_timeout=10.0, @@ -1379,7 +1408,8 @@ async def get_task( # Create or coerce a protobuf request object. # Sanity check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - if request is not None and any([name]): + has_flattened_params = any([name]) + if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " "the individual field arguments should be set." @@ -1402,7 +1432,7 @@ async def get_task( maximum=10.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, + exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, ), ), default_timeout=10.0, @@ -1509,7 +1539,8 @@ async def create_task( # Create or coerce a protobuf request object. # Sanity check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - if request is not None and any([parent, task]): + has_flattened_params = any([parent, task]) + if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " "the individual field arguments should be set." @@ -1580,7 +1611,8 @@ async def delete_task( # Create or coerce a protobuf request object. # Sanity check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - if request is not None and any([name]): + has_flattened_params = any([name]) + if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " "the individual field arguments should be set." @@ -1603,7 +1635,7 @@ async def delete_task( maximum=10.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, + exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, ), ), default_timeout=10.0, @@ -1683,7 +1715,8 @@ async def run_task( # Create or coerce a protobuf request object. # Sanity check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - if request is not None and any([name]): + has_flattened_params = any([name]) + if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " "the individual field arguments should be set." diff --git a/google/cloud/tasks_v2/services/cloud_tasks/client.py b/google/cloud/tasks_v2/services/cloud_tasks/client.py index 00b5bb18..ecd5a566 100644 --- a/google/cloud/tasks_v2/services/cloud_tasks/client.py +++ b/google/cloud/tasks_v2/services/cloud_tasks/client.py @@ -16,17 +16,19 @@ # from collections import OrderedDict +from distutils import util import os import re -from typing import Callable, Dict, Sequence, Tuple, Type, Union +from typing import Callable, Dict, Optional, Sequence, Tuple, Type, Union import pkg_resources -import google.api_core.client_options as ClientOptions # type: ignore +from google.api_core import client_options as client_options_lib # type: ignore from google.api_core import exceptions # type: ignore from google.api_core import gapic_v1 # type: ignore from google.api_core import retry as retries # type: ignore from google.auth import credentials # type: ignore from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore from google.auth.exceptions import MutualTLSChannelError # type: ignore from google.oauth2 import service_account # type: ignore @@ -138,6 +140,15 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): from_service_account_json = from_service_account_file + @property + def transport(self) -> CloudTasksTransport: + """Return the transport used by the client instance. + + Returns: + 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.""" @@ -170,12 +181,71 @@ def parse_task_path(path: str) -> Dict[str, str]: ) return m.groupdict() if m else {} + @staticmethod + def common_billing_account_path(billing_account: str,) -> str: + """Return a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format( + billing_account=billing_account, + ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str, str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path(folder: str,) -> str: + """Return a fully-qualified folder string.""" + return "folders/{folder}".format(folder=folder,) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str, str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path(organization: str,) -> str: + """Return a fully-qualified organization string.""" + return "organizations/{organization}".format(organization=organization,) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str, str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path(project: str,) -> str: + """Return a fully-qualified project string.""" + return "projects/{project}".format(project=project,) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str, str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path(project: str, location: str,) -> str: + """Return a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format( + project=project, location=location, + ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str, str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + def __init__( self, *, - credentials: credentials.Credentials = None, - transport: Union[str, CloudTasksTransport] = None, - client_options: ClientOptions = None, + credentials: Optional[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. @@ -189,23 +259,26 @@ def __init__( transport (Union[str, ~.CloudTasksTransport]): The transport to use. If set to None, a transport is chosen automatically. - client_options (ClientOptions): Custom options for the client. It - won't take effect if a ``transport`` instance is provided. + client_options (client_options_lib.ClientOptions): Custom options for the + client. It won't take effect if a ``transport`` instance is provided. (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT environment variable can also be used to override the endpoint: "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint, this is the default value for - the environment variable) and "auto" (auto switch to the default - mTLS endpoint if client SSL credentials is present). However, - the ``api_endpoint`` property takes precedence if provided. - (2) The ``client_cert_source`` property is used to provide client - SSL credentials for mutual TLS transport. If not provided, the - default SSL credentials will be used if present. - 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 + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing your own client library. Raises: @@ -213,29 +286,47 @@ def __init__( creation failed for any reason. """ if isinstance(client_options, dict): - client_options = ClientOptions.from_dict(client_options) + client_options = client_options_lib.from_dict(client_options) if client_options is None: - client_options = ClientOptions.ClientOptions() + client_options = client_options_lib.ClientOptions() + + # Create SSL credentials for mutual TLS if needed. + use_client_cert = bool( + util.strtobool(os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false")) + ) + + ssl_credentials = None + is_mtls = False + if use_client_cert: + if client_options.client_cert_source: + import grpc # type: ignore - if client_options.api_endpoint is None: - use_mtls_env = os.getenv("GOOGLE_API_USE_MTLS", "never") + cert, key = client_options.client_cert_source() + ssl_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + is_mtls = True + else: + creds = SslCredentials() + is_mtls = creds.is_mtls + ssl_credentials = creds.ssl_credentials if is_mtls else None + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + else: + use_mtls_env = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") if use_mtls_env == "never": - client_options.api_endpoint = self.DEFAULT_ENDPOINT + api_endpoint = self.DEFAULT_ENDPOINT elif use_mtls_env == "always": - client_options.api_endpoint = self.DEFAULT_MTLS_ENDPOINT + api_endpoint = self.DEFAULT_MTLS_ENDPOINT elif use_mtls_env == "auto": - has_client_cert_source = ( - client_options.client_cert_source is not None - or mtls.has_default_client_cert_source() - ) - client_options.api_endpoint = ( - self.DEFAULT_MTLS_ENDPOINT - if has_client_cert_source - else self.DEFAULT_ENDPOINT + api_endpoint = ( + self.DEFAULT_MTLS_ENDPOINT if is_mtls else self.DEFAULT_ENDPOINT ) else: raise MutualTLSChannelError( - "Unsupported GOOGLE_API_USE_MTLS value. Accepted values: never, auto, always" + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted values: never, auto, always" ) # Save or instantiate the transport. @@ -259,10 +350,9 @@ def __init__( self._transport = Transport( credentials=credentials, credentials_file=client_options.credentials_file, - host=client_options.api_endpoint, + host=api_endpoint, scopes=client_options.scopes, - api_mtls_endpoint=client_options.api_endpoint, - client_cert_source=client_options.client_cert_source, + ssl_channel_credentials=ssl_credentials, quota_project_id=client_options.quota_project_id, client_info=client_info, ) @@ -1098,13 +1188,7 @@ def get_iam_policy( request = iam_policy.GetIamPolicyRequest(**request) elif not request: - request = iam_policy.GetIamPolicyRequest() - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - - if resource is not None: - request.resource = resource + request = iam_policy.GetIamPolicyRequest(resource=resource,) # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. @@ -1249,13 +1333,7 @@ def set_iam_policy( request = iam_policy.SetIamPolicyRequest(**request) elif not request: - request = iam_policy.SetIamPolicyRequest() - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - - if resource is not None: - request.resource = resource + request = iam_policy.SetIamPolicyRequest(resource=resource,) # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. @@ -1340,16 +1418,9 @@ def test_iam_permissions( request = iam_policy.TestIamPermissionsRequest(**request) elif not request: - request = iam_policy.TestIamPermissionsRequest() - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - - if resource is not None: - request.resource = resource - - if permissions: - request.permissions.extend(permissions) + request = iam_policy.TestIamPermissionsRequest( + resource=resource, permissions=permissions, + ) # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. 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 0fc574a0..6ba5f065 100644 --- a/google/cloud/tasks_v2/services/cloud_tasks/transports/base.py +++ b/google/cloud/tasks_v2/services/cloud_tasks/transports/base.py @@ -118,7 +118,7 @@ def _prep_wrapped_messages(self, client_info): maximum=10.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, + exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, ), ), default_timeout=10.0, @@ -131,7 +131,7 @@ def _prep_wrapped_messages(self, client_info): maximum=10.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, + exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, ), ), default_timeout=10.0, @@ -150,7 +150,7 @@ def _prep_wrapped_messages(self, client_info): maximum=10.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, + exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, ), ), default_timeout=10.0, @@ -172,7 +172,7 @@ def _prep_wrapped_messages(self, client_info): maximum=10.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, + exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, ), ), default_timeout=10.0, @@ -188,7 +188,7 @@ def _prep_wrapped_messages(self, client_info): maximum=10.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, + exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, ), ), default_timeout=10.0, @@ -201,7 +201,7 @@ def _prep_wrapped_messages(self, client_info): maximum=10.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, + exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, ), ), default_timeout=10.0, @@ -214,7 +214,7 @@ def _prep_wrapped_messages(self, client_info): maximum=10.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, + exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, ), ), default_timeout=10.0, @@ -230,7 +230,7 @@ def _prep_wrapped_messages(self, client_info): maximum=10.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, + exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, ), ), default_timeout=10.0, 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 87b1c708..c7668cad 100644 --- a/google/cloud/tasks_v2/services/cloud_tasks/transports/grpc.py +++ b/google/cloud/tasks_v2/services/cloud_tasks/transports/grpc.py @@ -15,6 +15,7 @@ # limitations under the License. # +import warnings from typing import Callable, Dict, Optional, Sequence, Tuple from google.api_core import grpc_helpers # type: ignore @@ -23,7 +24,6 @@ from google.auth import credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore - import grpc # type: ignore from google.cloud.tasks_v2.types import cloudtasks @@ -64,6 +64,7 @@ def __init__( channel: grpc.Channel = None, api_mtls_endpoint: str = None, client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, quota_project_id: Optional[str] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: @@ -84,20 +85,22 @@ def __init__( ignored if ``channel`` is provided. channel (Optional[grpc.Channel]): A ``Channel`` instance through which to make calls. - api_mtls_endpoint (Optional[str]): The mutual TLS endpoint. If - provided, it overrides the ``host`` argument and tries to create + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create a mutual TLS channel with client SSL credentials from ``client_cert_source`` or applicatin default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): A - callback to provide client SSL certificate bytes and private key - bytes, both in PEM format. It is ignored if ``api_mtls_endpoint`` - is None. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for grpc channel. It is ignored if ``channel`` is provided. 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: @@ -106,6 +109,8 @@ def __init__( google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` and ``credentials_file`` are passed. """ + self._ssl_channel_credentials = ssl_channel_credentials + if channel: # Sanity check: Ensure that channel and credentials are not both # provided. @@ -113,7 +118,13 @@ def __init__( # If a channel was explicitly provided, set it. self._grpc_channel = channel + self._ssl_channel_credentials = None elif api_mtls_endpoint: + warnings.warn( + "api_mtls_endpoint and client_cert_source are deprecated", + DeprecationWarning, + ) + host = ( api_mtls_endpoint if ":" in api_mtls_endpoint @@ -144,6 +155,24 @@ def __init__( scopes=scopes or self.AUTH_SCOPES, quota_project_id=quota_project_id, ) + self._ssl_channel_credentials = ssl_credentials + else: + host = host if ":" in host else host + ":443" + + if credentials is None: + credentials, _ = auth.default( + scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id + ) + + # 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_channel_credentials, + scopes=scopes or self.AUTH_SCOPES, + quota_project_id=quota_project_id, + ) self._stubs = {} # type: Dict[str, Callable] @@ -204,19 +233,8 @@ def create_channel( @property def grpc_channel(self) -> grpc.Channel: - """Create the channel designed to connect to this service. - - This property caches on the instance; repeated calls return - the same channel. + """Return the channel designed to connect to this service. """ - # Sanity check: Only create a new channel if we do not already - # have one. - if not hasattr(self, "_grpc_channel"): - self._grpc_channel = self.create_channel( - self._host, credentials=self._credentials, - ) - - # Return the channel from cache. return self._grpc_channel @property 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 450aeb0c..c99f75eb 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 @@ -15,10 +15,12 @@ # limitations under the License. # +import warnings from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple from google.api_core import gapic_v1 # type: ignore from google.api_core import grpc_helpers_async # type: ignore +from google import auth # type: ignore from google.auth import credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore @@ -106,6 +108,7 @@ def __init__( channel: aio.Channel = None, api_mtls_endpoint: str = None, client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, quota_project_id=None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: @@ -127,14 +130,16 @@ def __init__( are passed to :func:`google.auth.default`. channel (Optional[aio.Channel]): A ``Channel`` instance through which to make calls. - api_mtls_endpoint (Optional[str]): The mutual TLS endpoint. If - provided, it overrides the ``host`` argument and tries to create + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create a mutual TLS channel with client SSL credentials from ``client_cert_source`` or applicatin default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): A - callback to provide client SSL certificate bytes and private key - bytes, both in PEM format. It is ignored if ``api_mtls_endpoint`` - is None. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for grpc channel. It is ignored if ``channel`` is provided. quota_project_id (Optional[str]): An optional project to use for billing and quota. client_info (google.api_core.gapic_v1.client_info.ClientInfo): @@ -149,6 +154,8 @@ def __init__( google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` and ``credentials_file`` are passed. """ + self._ssl_channel_credentials = ssl_channel_credentials + if channel: # Sanity check: Ensure that channel and credentials are not both # provided. @@ -156,13 +163,24 @@ def __init__( # If a channel was explicitly provided, set it. self._grpc_channel = channel + self._ssl_channel_credentials = None elif api_mtls_endpoint: + warnings.warn( + "api_mtls_endpoint and client_cert_source are deprecated", + DeprecationWarning, + ) + 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: @@ -182,6 +200,24 @@ def __init__( scopes=scopes or self.AUTH_SCOPES, quota_project_id=quota_project_id, ) + self._ssl_channel_credentials = ssl_credentials + else: + host = host if ":" in host else host + ":443" + + if credentials is None: + credentials, _ = auth.default( + scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id + ) + + # 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_channel_credentials, + scopes=scopes or self.AUTH_SCOPES, + quota_project_id=quota_project_id, + ) # Run the base constructor. super().__init__( @@ -202,13 +238,6 @@ def grpc_channel(self) -> aio.Channel: This property caches on the instance; repeated calls return the same channel. """ - # Sanity check: Only create a new channel if we do not already - # have one. - if not hasattr(self, "_grpc_channel"): - self._grpc_channel = self.create_channel( - self._host, credentials=self._credentials, - ) - # Return the channel from cache. return self._grpc_channel 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 6e198977..ce6cf5a7 100644 --- a/google/cloud/tasks_v2beta2/services/cloud_tasks/async_client.py +++ b/google/cloud/tasks_v2beta2/services/cloud_tasks/async_client.py @@ -56,13 +56,46 @@ class CloudTasksAsyncClient: DEFAULT_ENDPOINT = CloudTasksClient.DEFAULT_ENDPOINT DEFAULT_MTLS_ENDPOINT = CloudTasksClient.DEFAULT_MTLS_ENDPOINT + queue_path = staticmethod(CloudTasksClient.queue_path) + parse_queue_path = staticmethod(CloudTasksClient.parse_queue_path) task_path = staticmethod(CloudTasksClient.task_path) + parse_task_path = staticmethod(CloudTasksClient.parse_task_path) - queue_path = staticmethod(CloudTasksClient.queue_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_file = CloudTasksClient.from_service_account_file from_service_account_json = from_service_account_file + @property + def transport(self) -> CloudTasksTransport: + """Return the transport used by the client instance. + + Returns: + CloudTasksTransport: The transport used by the client instance. + """ + return self._client.transport + get_transport_class = functools.partial( type(CloudTasksClient).get_transport_class, type(CloudTasksClient) ) @@ -89,16 +122,19 @@ def __init__( client_options (ClientOptions): Custom options for the client. It won't take effect if a ``transport`` instance is provided. (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT environment variable can also be used to override the endpoint: "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint, this is the default value for - the environment variable) and "auto" (auto switch to the default - mTLS endpoint if client SSL credentials is present). However, - the ``api_endpoint`` property takes precedence if provided. - (2) The ``client_cert_source`` property is used to provide client - SSL credentials for mutual TLS transport. If not provided, the - default SSL credentials will be used if present. + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. Raises: google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport @@ -153,7 +189,8 @@ async def list_queues( # Create or coerce a protobuf request object. # Sanity check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - if request is not None and any([parent]): + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " "the individual field arguments should be set." @@ -176,7 +213,7 @@ async def list_queues( maximum=10.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, + exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, ), ), default_timeout=10.0, @@ -242,7 +279,8 @@ async def get_queue( # Create or coerce a protobuf request object. # Sanity check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - if request is not None and any([name]): + has_flattened_params = any([name]) + if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " "the individual field arguments should be set." @@ -265,7 +303,7 @@ async def get_queue( maximum=10.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, + exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, ), ), default_timeout=10.0, @@ -349,7 +387,8 @@ async def create_queue( # Create or coerce a protobuf request object. # Sanity check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - if request is not None and any([parent, queue]): + has_flattened_params = any([parent, queue]) + if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " "the individual field arguments should be set." @@ -457,7 +496,8 @@ async def update_queue( # Create or coerce a protobuf request object. # Sanity check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - if request is not None and any([queue, update_mask]): + has_flattened_params = any([queue, update_mask]) + if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " "the individual field arguments should be set." @@ -537,7 +577,8 @@ async def delete_queue( # Create or coerce a protobuf request object. # Sanity check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - if request is not None and any([name]): + has_flattened_params = any([name]) + if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " "the individual field arguments should be set." @@ -560,7 +601,7 @@ async def delete_queue( maximum=10.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, + exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, ), ), default_timeout=10.0, @@ -624,7 +665,8 @@ async def purge_queue( # Create or coerce a protobuf request object. # Sanity check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - if request is not None and any([name]): + has_flattened_params = any([name]) + if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " "the individual field arguments should be set." @@ -706,7 +748,8 @@ async def pause_queue( # Create or coerce a protobuf request object. # Sanity check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - if request is not None and any([name]): + has_flattened_params = any([name]) + if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " "the individual field arguments should be set." @@ -795,7 +838,8 @@ async def resume_queue( # Create or coerce a protobuf request object. # Sanity check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - if request is not None and any([name]): + has_flattened_params = any([name]) + if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " "the individual field arguments should be set." @@ -939,7 +983,8 @@ async def get_iam_policy( # Create or coerce a protobuf request object. # Sanity check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - if request is not None and any([resource]): + has_flattened_params = any([resource]) + if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " "the individual field arguments should be set." @@ -951,13 +996,7 @@ async def get_iam_policy( request = iam_policy.GetIamPolicyRequest(**request) elif not request: - request = iam_policy.GetIamPolicyRequest() - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - - if resource is not None: - request.resource = resource + request = iam_policy.GetIamPolicyRequest(resource=resource,) # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. @@ -968,7 +1007,7 @@ async def get_iam_policy( maximum=10.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, + exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, ), ), default_timeout=10.0, @@ -1101,7 +1140,8 @@ async def set_iam_policy( # Create or coerce a protobuf request object. # Sanity check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - if request is not None and any([resource]): + has_flattened_params = any([resource]) + if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " "the individual field arguments should be set." @@ -1113,13 +1153,7 @@ async def set_iam_policy( request = iam_policy.SetIamPolicyRequest(**request) elif not request: - request = iam_policy.SetIamPolicyRequest() - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - - if resource is not None: - request.resource = resource + request = iam_policy.SetIamPolicyRequest(resource=resource,) # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. @@ -1195,7 +1229,8 @@ async def test_iam_permissions( # Create or coerce a protobuf request object. # Sanity check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - if request is not None and any([resource, permissions]): + has_flattened_params = any([resource, permissions]) + if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " "the individual field arguments should be set." @@ -1207,16 +1242,9 @@ async def test_iam_permissions( request = iam_policy.TestIamPermissionsRequest(**request) elif not request: - request = iam_policy.TestIamPermissionsRequest() - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - - if resource is not None: - request.resource = resource - - if permissions: - request.permissions.extend(permissions) + request = iam_policy.TestIamPermissionsRequest( + resource=resource, permissions=permissions, + ) # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. @@ -1227,7 +1255,7 @@ async def test_iam_permissions( maximum=10.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, + exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, ), ), default_timeout=10.0, @@ -1296,7 +1324,8 @@ async def list_tasks( # Create or coerce a protobuf request object. # Sanity check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - if request is not None and any([parent]): + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " "the individual field arguments should be set." @@ -1319,7 +1348,7 @@ async def list_tasks( maximum=10.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, + exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, ), ), default_timeout=10.0, @@ -1380,7 +1409,8 @@ async def get_task( # Create or coerce a protobuf request object. # Sanity check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - if request is not None and any([name]): + has_flattened_params = any([name]) + if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " "the individual field arguments should be set." @@ -1403,7 +1433,7 @@ async def get_task( maximum=10.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, + exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, ), ), default_timeout=10.0, @@ -1514,7 +1544,8 @@ async def create_task( # Create or coerce a protobuf request object. # Sanity check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - if request is not None and any([parent, task]): + has_flattened_params = any([parent, task]) + if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " "the individual field arguments should be set." @@ -1585,7 +1616,8 @@ async def delete_task( # Create or coerce a protobuf request object. # Sanity check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - if request is not None and any([name]): + has_flattened_params = any([name]) + if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " "the individual field arguments should be set." @@ -1608,7 +1640,7 @@ async def delete_task( maximum=10.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, + exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, ), ), default_timeout=10.0, @@ -1717,7 +1749,8 @@ async def lease_tasks( # Create or coerce a protobuf request object. # Sanity check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - if request is not None and any([parent, lease_duration]): + has_flattened_params = any([parent, lease_duration]) + if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " "the individual field arguments should be set." @@ -1813,7 +1846,8 @@ async def acknowledge_task( # Create or coerce a protobuf request object. # Sanity check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - if request is not None and any([name, schedule_time]): + has_flattened_params = any([name, schedule_time]) + if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " "the individual field arguments should be set." @@ -1913,7 +1947,8 @@ async def renew_lease( # Create or coerce a protobuf request object. # Sanity check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - if request is not None and any([name, schedule_time, lease_duration]): + has_flattened_params = any([name, schedule_time, lease_duration]) + if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " "the individual field arguments should be set." @@ -2008,7 +2043,8 @@ async def cancel_lease( # Create or coerce a protobuf request object. # Sanity check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - if request is not None and any([name, schedule_time]): + has_flattened_params = any([name, schedule_time]) + if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " "the individual field arguments should be set." @@ -2112,7 +2148,8 @@ async def run_task( # Create or coerce a protobuf request object. # Sanity check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - if request is not None and any([name]): + has_flattened_params = any([name]) + if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " "the individual field arguments should be set." diff --git a/google/cloud/tasks_v2beta2/services/cloud_tasks/client.py b/google/cloud/tasks_v2beta2/services/cloud_tasks/client.py index 2cace164..133b77c9 100644 --- a/google/cloud/tasks_v2beta2/services/cloud_tasks/client.py +++ b/google/cloud/tasks_v2beta2/services/cloud_tasks/client.py @@ -16,17 +16,19 @@ # from collections import OrderedDict +from distutils import util import os import re -from typing import Callable, Dict, Sequence, Tuple, Type, Union +from typing import Callable, Dict, Optional, Sequence, Tuple, Type, Union import pkg_resources -import google.api_core.client_options as ClientOptions # type: ignore +from google.api_core import client_options as client_options_lib # type: ignore from google.api_core import exceptions # type: ignore from google.api_core import gapic_v1 # type: ignore from google.api_core import retry as retries # type: ignore from google.auth import credentials # type: ignore from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore from google.auth.exceptions import MutualTLSChannelError # type: ignore from google.oauth2 import service_account # type: ignore @@ -138,6 +140,15 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): from_service_account_json = from_service_account_file + @property + def transport(self) -> CloudTasksTransport: + """Return the transport used by the client instance. + + Returns: + 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.""" @@ -170,12 +181,71 @@ def parse_task_path(path: str) -> Dict[str, str]: ) return m.groupdict() if m else {} + @staticmethod + def common_billing_account_path(billing_account: str,) -> str: + """Return a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format( + billing_account=billing_account, + ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str, str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path(folder: str,) -> str: + """Return a fully-qualified folder string.""" + return "folders/{folder}".format(folder=folder,) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str, str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path(organization: str,) -> str: + """Return a fully-qualified organization string.""" + return "organizations/{organization}".format(organization=organization,) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str, str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path(project: str,) -> str: + """Return a fully-qualified project string.""" + return "projects/{project}".format(project=project,) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str, str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path(project: str, location: str,) -> str: + """Return a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format( + project=project, location=location, + ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str, str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + def __init__( self, *, - credentials: credentials.Credentials = None, - transport: Union[str, CloudTasksTransport] = None, - client_options: ClientOptions = None, + credentials: Optional[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. @@ -189,23 +259,26 @@ def __init__( transport (Union[str, ~.CloudTasksTransport]): The transport to use. If set to None, a transport is chosen automatically. - client_options (ClientOptions): Custom options for the client. It - won't take effect if a ``transport`` instance is provided. + client_options (client_options_lib.ClientOptions): Custom options for the + client. It won't take effect if a ``transport`` instance is provided. (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT environment variable can also be used to override the endpoint: "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint, this is the default value for - the environment variable) and "auto" (auto switch to the default - mTLS endpoint if client SSL credentials is present). However, - the ``api_endpoint`` property takes precedence if provided. - (2) The ``client_cert_source`` property is used to provide client - SSL credentials for mutual TLS transport. If not provided, the - default SSL credentials will be used if present. - 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 + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing your own client library. Raises: @@ -213,29 +286,47 @@ def __init__( creation failed for any reason. """ if isinstance(client_options, dict): - client_options = ClientOptions.from_dict(client_options) + client_options = client_options_lib.from_dict(client_options) if client_options is None: - client_options = ClientOptions.ClientOptions() + client_options = client_options_lib.ClientOptions() + + # Create SSL credentials for mutual TLS if needed. + use_client_cert = bool( + util.strtobool(os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false")) + ) + + ssl_credentials = None + is_mtls = False + if use_client_cert: + if client_options.client_cert_source: + import grpc # type: ignore - if client_options.api_endpoint is None: - use_mtls_env = os.getenv("GOOGLE_API_USE_MTLS", "never") + cert, key = client_options.client_cert_source() + ssl_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + is_mtls = True + else: + creds = SslCredentials() + is_mtls = creds.is_mtls + ssl_credentials = creds.ssl_credentials if is_mtls else None + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + else: + use_mtls_env = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") if use_mtls_env == "never": - client_options.api_endpoint = self.DEFAULT_ENDPOINT + api_endpoint = self.DEFAULT_ENDPOINT elif use_mtls_env == "always": - client_options.api_endpoint = self.DEFAULT_MTLS_ENDPOINT + api_endpoint = self.DEFAULT_MTLS_ENDPOINT elif use_mtls_env == "auto": - has_client_cert_source = ( - client_options.client_cert_source is not None - or mtls.has_default_client_cert_source() - ) - client_options.api_endpoint = ( - self.DEFAULT_MTLS_ENDPOINT - if has_client_cert_source - else self.DEFAULT_ENDPOINT + api_endpoint = ( + self.DEFAULT_MTLS_ENDPOINT if is_mtls else self.DEFAULT_ENDPOINT ) else: raise MutualTLSChannelError( - "Unsupported GOOGLE_API_USE_MTLS value. Accepted values: never, auto, always" + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted values: never, auto, always" ) # Save or instantiate the transport. @@ -259,10 +350,9 @@ def __init__( self._transport = Transport( credentials=credentials, credentials_file=client_options.credentials_file, - host=client_options.api_endpoint, + host=api_endpoint, scopes=client_options.scopes, - api_mtls_endpoint=client_options.api_endpoint, - client_cert_source=client_options.client_cert_source, + ssl_channel_credentials=ssl_credentials, quota_project_id=client_options.quota_project_id, client_info=client_info, ) @@ -1099,13 +1189,7 @@ def get_iam_policy( request = iam_policy.GetIamPolicyRequest(**request) elif not request: - request = iam_policy.GetIamPolicyRequest() - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - - if resource is not None: - request.resource = resource + request = iam_policy.GetIamPolicyRequest(resource=resource,) # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. @@ -1250,13 +1334,7 @@ def set_iam_policy( request = iam_policy.SetIamPolicyRequest(**request) elif not request: - request = iam_policy.SetIamPolicyRequest() - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - - if resource is not None: - request.resource = resource + request = iam_policy.SetIamPolicyRequest(resource=resource,) # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. @@ -1341,16 +1419,9 @@ def test_iam_permissions( request = iam_policy.TestIamPermissionsRequest(**request) elif not request: - request = iam_policy.TestIamPermissionsRequest() - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - - if resource is not None: - request.resource = resource - - if permissions: - request.permissions.extend(permissions) + request = iam_policy.TestIamPermissionsRequest( + resource=resource, permissions=permissions, + ) # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. 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 17ac8ced..a2107f27 100644 --- a/google/cloud/tasks_v2beta2/services/cloud_tasks/transports/base.py +++ b/google/cloud/tasks_v2beta2/services/cloud_tasks/transports/base.py @@ -118,7 +118,7 @@ def _prep_wrapped_messages(self, client_info): maximum=10.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, + exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, ), ), default_timeout=10.0, @@ -131,7 +131,7 @@ def _prep_wrapped_messages(self, client_info): maximum=10.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, + exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, ), ), default_timeout=10.0, @@ -150,7 +150,7 @@ def _prep_wrapped_messages(self, client_info): maximum=10.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, + exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, ), ), default_timeout=10.0, @@ -172,7 +172,7 @@ def _prep_wrapped_messages(self, client_info): maximum=10.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, + exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, ), ), default_timeout=10.0, @@ -188,7 +188,7 @@ def _prep_wrapped_messages(self, client_info): maximum=10.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, + exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, ), ), default_timeout=10.0, @@ -201,7 +201,7 @@ def _prep_wrapped_messages(self, client_info): maximum=10.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, + exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, ), ), default_timeout=10.0, @@ -214,7 +214,7 @@ def _prep_wrapped_messages(self, client_info): maximum=10.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, + exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, ), ), default_timeout=10.0, @@ -230,7 +230,7 @@ def _prep_wrapped_messages(self, client_info): maximum=10.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, + exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, ), ), default_timeout=10.0, 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 224f657c..832a4623 100644 --- a/google/cloud/tasks_v2beta2/services/cloud_tasks/transports/grpc.py +++ b/google/cloud/tasks_v2beta2/services/cloud_tasks/transports/grpc.py @@ -15,6 +15,7 @@ # limitations under the License. # +import warnings from typing import Callable, Dict, Optional, Sequence, Tuple from google.api_core import grpc_helpers # type: ignore @@ -23,7 +24,6 @@ from google.auth import credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore - import grpc # type: ignore from google.cloud.tasks_v2beta2.types import cloudtasks @@ -64,6 +64,7 @@ def __init__( channel: grpc.Channel = None, api_mtls_endpoint: str = None, client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, quota_project_id: Optional[str] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: @@ -84,20 +85,22 @@ def __init__( ignored if ``channel`` is provided. channel (Optional[grpc.Channel]): A ``Channel`` instance through which to make calls. - api_mtls_endpoint (Optional[str]): The mutual TLS endpoint. If - provided, it overrides the ``host`` argument and tries to create + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create a mutual TLS channel with client SSL credentials from ``client_cert_source`` or applicatin default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): A - callback to provide client SSL certificate bytes and private key - bytes, both in PEM format. It is ignored if ``api_mtls_endpoint`` - is None. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for grpc channel. It is ignored if ``channel`` is provided. 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: @@ -106,6 +109,8 @@ def __init__( google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` and ``credentials_file`` are passed. """ + self._ssl_channel_credentials = ssl_channel_credentials + if channel: # Sanity check: Ensure that channel and credentials are not both # provided. @@ -113,7 +118,13 @@ def __init__( # If a channel was explicitly provided, set it. self._grpc_channel = channel + self._ssl_channel_credentials = None elif api_mtls_endpoint: + warnings.warn( + "api_mtls_endpoint and client_cert_source are deprecated", + DeprecationWarning, + ) + host = ( api_mtls_endpoint if ":" in api_mtls_endpoint @@ -144,6 +155,24 @@ def __init__( scopes=scopes or self.AUTH_SCOPES, quota_project_id=quota_project_id, ) + self._ssl_channel_credentials = ssl_credentials + else: + host = host if ":" in host else host + ":443" + + if credentials is None: + credentials, _ = auth.default( + scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id + ) + + # 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_channel_credentials, + scopes=scopes or self.AUTH_SCOPES, + quota_project_id=quota_project_id, + ) self._stubs = {} # type: Dict[str, Callable] @@ -204,19 +233,8 @@ def create_channel( @property def grpc_channel(self) -> grpc.Channel: - """Create the channel designed to connect to this service. - - This property caches on the instance; repeated calls return - the same channel. + """Return the channel designed to connect to this service. """ - # Sanity check: Only create a new channel if we do not already - # have one. - if not hasattr(self, "_grpc_channel"): - self._grpc_channel = self.create_channel( - self._host, credentials=self._credentials, - ) - - # Return the channel from cache. return self._grpc_channel @property 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 62acdc4d..c10763e9 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 @@ -15,10 +15,12 @@ # limitations under the License. # +import warnings from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple from google.api_core import gapic_v1 # type: ignore from google.api_core import grpc_helpers_async # type: ignore +from google import auth # type: ignore from google.auth import credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore @@ -106,6 +108,7 @@ def __init__( channel: aio.Channel = None, api_mtls_endpoint: str = None, client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, quota_project_id=None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: @@ -127,14 +130,16 @@ def __init__( are passed to :func:`google.auth.default`. channel (Optional[aio.Channel]): A ``Channel`` instance through which to make calls. - api_mtls_endpoint (Optional[str]): The mutual TLS endpoint. If - provided, it overrides the ``host`` argument and tries to create + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create a mutual TLS channel with client SSL credentials from ``client_cert_source`` or applicatin default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): A - callback to provide client SSL certificate bytes and private key - bytes, both in PEM format. It is ignored if ``api_mtls_endpoint`` - is None. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for grpc channel. It is ignored if ``channel`` is provided. quota_project_id (Optional[str]): An optional project to use for billing and quota. client_info (google.api_core.gapic_v1.client_info.ClientInfo): @@ -149,6 +154,8 @@ def __init__( google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` and ``credentials_file`` are passed. """ + self._ssl_channel_credentials = ssl_channel_credentials + if channel: # Sanity check: Ensure that channel and credentials are not both # provided. @@ -156,13 +163,24 @@ def __init__( # If a channel was explicitly provided, set it. self._grpc_channel = channel + self._ssl_channel_credentials = None elif api_mtls_endpoint: + warnings.warn( + "api_mtls_endpoint and client_cert_source are deprecated", + DeprecationWarning, + ) + 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: @@ -182,6 +200,24 @@ def __init__( scopes=scopes or self.AUTH_SCOPES, quota_project_id=quota_project_id, ) + self._ssl_channel_credentials = ssl_credentials + else: + host = host if ":" in host else host + ":443" + + if credentials is None: + credentials, _ = auth.default( + scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id + ) + + # 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_channel_credentials, + scopes=scopes or self.AUTH_SCOPES, + quota_project_id=quota_project_id, + ) # Run the base constructor. super().__init__( @@ -202,13 +238,6 @@ def grpc_channel(self) -> aio.Channel: This property caches on the instance; repeated calls return the same channel. """ - # Sanity check: Only create a new channel if we do not already - # have one. - if not hasattr(self, "_grpc_channel"): - self._grpc_channel = self.create_channel( - self._host, credentials=self._credentials, - ) - # Return the channel from cache. return self._grpc_channel 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 d56f5e57..8ef25925 100644 --- a/google/cloud/tasks_v2beta3/services/cloud_tasks/async_client.py +++ b/google/cloud/tasks_v2beta3/services/cloud_tasks/async_client.py @@ -56,13 +56,46 @@ class CloudTasksAsyncClient: DEFAULT_ENDPOINT = CloudTasksClient.DEFAULT_ENDPOINT DEFAULT_MTLS_ENDPOINT = CloudTasksClient.DEFAULT_MTLS_ENDPOINT + queue_path = staticmethod(CloudTasksClient.queue_path) + parse_queue_path = staticmethod(CloudTasksClient.parse_queue_path) task_path = staticmethod(CloudTasksClient.task_path) + parse_task_path = staticmethod(CloudTasksClient.parse_task_path) - queue_path = staticmethod(CloudTasksClient.queue_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_file = CloudTasksClient.from_service_account_file from_service_account_json = from_service_account_file + @property + def transport(self) -> CloudTasksTransport: + """Return the transport used by the client instance. + + Returns: + CloudTasksTransport: The transport used by the client instance. + """ + return self._client.transport + get_transport_class = functools.partial( type(CloudTasksClient).get_transport_class, type(CloudTasksClient) ) @@ -89,16 +122,19 @@ def __init__( client_options (ClientOptions): Custom options for the client. It won't take effect if a ``transport`` instance is provided. (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT environment variable can also be used to override the endpoint: "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint, this is the default value for - the environment variable) and "auto" (auto switch to the default - mTLS endpoint if client SSL credentials is present). However, - the ``api_endpoint`` property takes precedence if provided. - (2) The ``client_cert_source`` property is used to provide client - SSL credentials for mutual TLS transport. If not provided, the - default SSL credentials will be used if present. + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. Raises: google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport @@ -153,7 +189,8 @@ async def list_queues( # Create or coerce a protobuf request object. # Sanity check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - if request is not None and any([parent]): + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " "the individual field arguments should be set." @@ -176,7 +213,7 @@ async def list_queues( maximum=10.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, + exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, ), ), default_timeout=10.0, @@ -242,7 +279,8 @@ async def get_queue( # Create or coerce a protobuf request object. # Sanity check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - if request is not None and any([name]): + has_flattened_params = any([name]) + if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " "the individual field arguments should be set." @@ -265,7 +303,7 @@ async def get_queue( maximum=10.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, + exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, ), ), default_timeout=10.0, @@ -349,7 +387,8 @@ async def create_queue( # Create or coerce a protobuf request object. # Sanity check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - if request is not None and any([parent, queue]): + has_flattened_params = any([parent, queue]) + if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " "the individual field arguments should be set." @@ -457,7 +496,8 @@ async def update_queue( # Create or coerce a protobuf request object. # Sanity check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - if request is not None and any([queue, update_mask]): + has_flattened_params = any([queue, update_mask]) + if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " "the individual field arguments should be set." @@ -537,7 +577,8 @@ async def delete_queue( # Create or coerce a protobuf request object. # Sanity check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - if request is not None and any([name]): + has_flattened_params = any([name]) + if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " "the individual field arguments should be set." @@ -560,7 +601,7 @@ async def delete_queue( maximum=10.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, + exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, ), ), default_timeout=10.0, @@ -624,7 +665,8 @@ async def purge_queue( # Create or coerce a protobuf request object. # Sanity check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - if request is not None and any([name]): + has_flattened_params = any([name]) + if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " "the individual field arguments should be set." @@ -706,7 +748,8 @@ async def pause_queue( # Create or coerce a protobuf request object. # Sanity check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - if request is not None and any([name]): + has_flattened_params = any([name]) + if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " "the individual field arguments should be set." @@ -795,7 +838,8 @@ async def resume_queue( # Create or coerce a protobuf request object. # Sanity check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - if request is not None and any([name]): + has_flattened_params = any([name]) + if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " "the individual field arguments should be set." @@ -939,7 +983,8 @@ async def get_iam_policy( # Create or coerce a protobuf request object. # Sanity check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - if request is not None and any([resource]): + has_flattened_params = any([resource]) + if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " "the individual field arguments should be set." @@ -951,13 +996,7 @@ async def get_iam_policy( request = iam_policy.GetIamPolicyRequest(**request) elif not request: - request = iam_policy.GetIamPolicyRequest() - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - - if resource is not None: - request.resource = resource + request = iam_policy.GetIamPolicyRequest(resource=resource,) # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. @@ -968,7 +1007,7 @@ async def get_iam_policy( maximum=10.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, + exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, ), ), default_timeout=10.0, @@ -1101,7 +1140,8 @@ async def set_iam_policy( # Create or coerce a protobuf request object. # Sanity check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - if request is not None and any([resource]): + has_flattened_params = any([resource]) + if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " "the individual field arguments should be set." @@ -1113,13 +1153,7 @@ async def set_iam_policy( request = iam_policy.SetIamPolicyRequest(**request) elif not request: - request = iam_policy.SetIamPolicyRequest() - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - - if resource is not None: - request.resource = resource + request = iam_policy.SetIamPolicyRequest(resource=resource,) # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. @@ -1195,7 +1229,8 @@ async def test_iam_permissions( # Create or coerce a protobuf request object. # Sanity check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - if request is not None and any([resource, permissions]): + has_flattened_params = any([resource, permissions]) + if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " "the individual field arguments should be set." @@ -1207,16 +1242,9 @@ async def test_iam_permissions( request = iam_policy.TestIamPermissionsRequest(**request) elif not request: - request = iam_policy.TestIamPermissionsRequest() - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - - if resource is not None: - request.resource = resource - - if permissions: - request.permissions.extend(permissions) + request = iam_policy.TestIamPermissionsRequest( + resource=resource, permissions=permissions, + ) # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. @@ -1227,7 +1255,7 @@ async def test_iam_permissions( maximum=10.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, + exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, ), ), default_timeout=10.0, @@ -1296,7 +1324,8 @@ async def list_tasks( # Create or coerce a protobuf request object. # Sanity check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - if request is not None and any([parent]): + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " "the individual field arguments should be set." @@ -1319,7 +1348,7 @@ async def list_tasks( maximum=10.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, + exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, ), ), default_timeout=10.0, @@ -1380,7 +1409,8 @@ async def get_task( # Create or coerce a protobuf request object. # Sanity check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - if request is not None and any([name]): + has_flattened_params = any([name]) + if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " "the individual field arguments should be set." @@ -1403,7 +1433,7 @@ async def get_task( maximum=10.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, + exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, ), ), default_timeout=10.0, @@ -1510,7 +1540,8 @@ async def create_task( # Create or coerce a protobuf request object. # Sanity check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - if request is not None and any([parent, task]): + has_flattened_params = any([parent, task]) + if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " "the individual field arguments should be set." @@ -1581,7 +1612,8 @@ async def delete_task( # Create or coerce a protobuf request object. # Sanity check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - if request is not None and any([name]): + has_flattened_params = any([name]) + if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " "the individual field arguments should be set." @@ -1604,7 +1636,7 @@ async def delete_task( maximum=10.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, + exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, ), ), default_timeout=10.0, @@ -1685,7 +1717,8 @@ async def run_task( # Create or coerce a protobuf request object. # Sanity check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - if request is not None and any([name]): + has_flattened_params = any([name]) + if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " "the individual field arguments should be set." diff --git a/google/cloud/tasks_v2beta3/services/cloud_tasks/client.py b/google/cloud/tasks_v2beta3/services/cloud_tasks/client.py index 9d9105da..c26eb4fa 100644 --- a/google/cloud/tasks_v2beta3/services/cloud_tasks/client.py +++ b/google/cloud/tasks_v2beta3/services/cloud_tasks/client.py @@ -16,17 +16,19 @@ # from collections import OrderedDict +from distutils import util import os import re -from typing import Callable, Dict, Sequence, Tuple, Type, Union +from typing import Callable, Dict, Optional, Sequence, Tuple, Type, Union import pkg_resources -import google.api_core.client_options as ClientOptions # type: ignore +from google.api_core import client_options as client_options_lib # type: ignore from google.api_core import exceptions # type: ignore from google.api_core import gapic_v1 # type: ignore from google.api_core import retry as retries # type: ignore from google.auth import credentials # type: ignore from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore from google.auth.exceptions import MutualTLSChannelError # type: ignore from google.oauth2 import service_account # type: ignore @@ -138,6 +140,15 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): from_service_account_json = from_service_account_file + @property + def transport(self) -> CloudTasksTransport: + """Return the transport used by the client instance. + + Returns: + 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.""" @@ -170,12 +181,71 @@ def parse_task_path(path: str) -> Dict[str, str]: ) return m.groupdict() if m else {} + @staticmethod + def common_billing_account_path(billing_account: str,) -> str: + """Return a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format( + billing_account=billing_account, + ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str, str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path(folder: str,) -> str: + """Return a fully-qualified folder string.""" + return "folders/{folder}".format(folder=folder,) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str, str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path(organization: str,) -> str: + """Return a fully-qualified organization string.""" + return "organizations/{organization}".format(organization=organization,) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str, str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path(project: str,) -> str: + """Return a fully-qualified project string.""" + return "projects/{project}".format(project=project,) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str, str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path(project: str, location: str,) -> str: + """Return a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format( + project=project, location=location, + ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str, str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + def __init__( self, *, - credentials: credentials.Credentials = None, - transport: Union[str, CloudTasksTransport] = None, - client_options: ClientOptions = None, + credentials: Optional[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. @@ -189,23 +259,26 @@ def __init__( transport (Union[str, ~.CloudTasksTransport]): The transport to use. If set to None, a transport is chosen automatically. - client_options (ClientOptions): Custom options for the client. It - won't take effect if a ``transport`` instance is provided. + client_options (client_options_lib.ClientOptions): Custom options for the + client. It won't take effect if a ``transport`` instance is provided. (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT environment variable can also be used to override the endpoint: "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint, this is the default value for - the environment variable) and "auto" (auto switch to the default - mTLS endpoint if client SSL credentials is present). However, - the ``api_endpoint`` property takes precedence if provided. - (2) The ``client_cert_source`` property is used to provide client - SSL credentials for mutual TLS transport. If not provided, the - default SSL credentials will be used if present. - 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 + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing your own client library. Raises: @@ -213,29 +286,47 @@ def __init__( creation failed for any reason. """ if isinstance(client_options, dict): - client_options = ClientOptions.from_dict(client_options) + client_options = client_options_lib.from_dict(client_options) if client_options is None: - client_options = ClientOptions.ClientOptions() + client_options = client_options_lib.ClientOptions() + + # Create SSL credentials for mutual TLS if needed. + use_client_cert = bool( + util.strtobool(os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false")) + ) + + ssl_credentials = None + is_mtls = False + if use_client_cert: + if client_options.client_cert_source: + import grpc # type: ignore - if client_options.api_endpoint is None: - use_mtls_env = os.getenv("GOOGLE_API_USE_MTLS", "never") + cert, key = client_options.client_cert_source() + ssl_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + is_mtls = True + else: + creds = SslCredentials() + is_mtls = creds.is_mtls + ssl_credentials = creds.ssl_credentials if is_mtls else None + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + else: + use_mtls_env = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") if use_mtls_env == "never": - client_options.api_endpoint = self.DEFAULT_ENDPOINT + api_endpoint = self.DEFAULT_ENDPOINT elif use_mtls_env == "always": - client_options.api_endpoint = self.DEFAULT_MTLS_ENDPOINT + api_endpoint = self.DEFAULT_MTLS_ENDPOINT elif use_mtls_env == "auto": - has_client_cert_source = ( - client_options.client_cert_source is not None - or mtls.has_default_client_cert_source() - ) - client_options.api_endpoint = ( - self.DEFAULT_MTLS_ENDPOINT - if has_client_cert_source - else self.DEFAULT_ENDPOINT + api_endpoint = ( + self.DEFAULT_MTLS_ENDPOINT if is_mtls else self.DEFAULT_ENDPOINT ) else: raise MutualTLSChannelError( - "Unsupported GOOGLE_API_USE_MTLS value. Accepted values: never, auto, always" + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted values: never, auto, always" ) # Save or instantiate the transport. @@ -259,10 +350,9 @@ def __init__( self._transport = Transport( credentials=credentials, credentials_file=client_options.credentials_file, - host=client_options.api_endpoint, + host=api_endpoint, scopes=client_options.scopes, - api_mtls_endpoint=client_options.api_endpoint, - client_cert_source=client_options.client_cert_source, + ssl_channel_credentials=ssl_credentials, quota_project_id=client_options.quota_project_id, client_info=client_info, ) @@ -1099,13 +1189,7 @@ def get_iam_policy( request = iam_policy.GetIamPolicyRequest(**request) elif not request: - request = iam_policy.GetIamPolicyRequest() - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - - if resource is not None: - request.resource = resource + request = iam_policy.GetIamPolicyRequest(resource=resource,) # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. @@ -1250,13 +1334,7 @@ def set_iam_policy( request = iam_policy.SetIamPolicyRequest(**request) elif not request: - request = iam_policy.SetIamPolicyRequest() - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - - if resource is not None: - request.resource = resource + request = iam_policy.SetIamPolicyRequest(resource=resource,) # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. @@ -1341,16 +1419,9 @@ def test_iam_permissions( request = iam_policy.TestIamPermissionsRequest(**request) elif not request: - request = iam_policy.TestIamPermissionsRequest() - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - - if resource is not None: - request.resource = resource - - if permissions: - request.permissions.extend(permissions) + request = iam_policy.TestIamPermissionsRequest( + resource=resource, permissions=permissions, + ) # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. 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 a7c0cfe4..6a16a22d 100644 --- a/google/cloud/tasks_v2beta3/services/cloud_tasks/transports/base.py +++ b/google/cloud/tasks_v2beta3/services/cloud_tasks/transports/base.py @@ -118,7 +118,7 @@ def _prep_wrapped_messages(self, client_info): maximum=10.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, + exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, ), ), default_timeout=10.0, @@ -131,7 +131,7 @@ def _prep_wrapped_messages(self, client_info): maximum=10.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, + exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, ), ), default_timeout=10.0, @@ -150,7 +150,7 @@ def _prep_wrapped_messages(self, client_info): maximum=10.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, + exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, ), ), default_timeout=10.0, @@ -172,7 +172,7 @@ def _prep_wrapped_messages(self, client_info): maximum=10.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, + exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, ), ), default_timeout=10.0, @@ -188,7 +188,7 @@ def _prep_wrapped_messages(self, client_info): maximum=10.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, + exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, ), ), default_timeout=10.0, @@ -201,7 +201,7 @@ def _prep_wrapped_messages(self, client_info): maximum=10.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, + exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, ), ), default_timeout=10.0, @@ -214,7 +214,7 @@ def _prep_wrapped_messages(self, client_info): maximum=10.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, + exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, ), ), default_timeout=10.0, @@ -230,7 +230,7 @@ def _prep_wrapped_messages(self, client_info): maximum=10.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, + exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, ), ), default_timeout=10.0, 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 f026573f..792d2896 100644 --- a/google/cloud/tasks_v2beta3/services/cloud_tasks/transports/grpc.py +++ b/google/cloud/tasks_v2beta3/services/cloud_tasks/transports/grpc.py @@ -15,6 +15,7 @@ # limitations under the License. # +import warnings from typing import Callable, Dict, Optional, Sequence, Tuple from google.api_core import grpc_helpers # type: ignore @@ -23,7 +24,6 @@ from google.auth import credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore - import grpc # type: ignore from google.cloud.tasks_v2beta3.types import cloudtasks @@ -64,6 +64,7 @@ def __init__( channel: grpc.Channel = None, api_mtls_endpoint: str = None, client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, quota_project_id: Optional[str] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: @@ -84,20 +85,22 @@ def __init__( ignored if ``channel`` is provided. channel (Optional[grpc.Channel]): A ``Channel`` instance through which to make calls. - api_mtls_endpoint (Optional[str]): The mutual TLS endpoint. If - provided, it overrides the ``host`` argument and tries to create + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create a mutual TLS channel with client SSL credentials from ``client_cert_source`` or applicatin default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): A - callback to provide client SSL certificate bytes and private key - bytes, both in PEM format. It is ignored if ``api_mtls_endpoint`` - is None. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for grpc channel. It is ignored if ``channel`` is provided. 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: @@ -106,6 +109,8 @@ def __init__( google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` and ``credentials_file`` are passed. """ + self._ssl_channel_credentials = ssl_channel_credentials + if channel: # Sanity check: Ensure that channel and credentials are not both # provided. @@ -113,7 +118,13 @@ def __init__( # If a channel was explicitly provided, set it. self._grpc_channel = channel + self._ssl_channel_credentials = None elif api_mtls_endpoint: + warnings.warn( + "api_mtls_endpoint and client_cert_source are deprecated", + DeprecationWarning, + ) + host = ( api_mtls_endpoint if ":" in api_mtls_endpoint @@ -144,6 +155,24 @@ def __init__( scopes=scopes or self.AUTH_SCOPES, quota_project_id=quota_project_id, ) + self._ssl_channel_credentials = ssl_credentials + else: + host = host if ":" in host else host + ":443" + + if credentials is None: + credentials, _ = auth.default( + scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id + ) + + # 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_channel_credentials, + scopes=scopes or self.AUTH_SCOPES, + quota_project_id=quota_project_id, + ) self._stubs = {} # type: Dict[str, Callable] @@ -204,19 +233,8 @@ def create_channel( @property def grpc_channel(self) -> grpc.Channel: - """Create the channel designed to connect to this service. - - This property caches on the instance; repeated calls return - the same channel. + """Return the channel designed to connect to this service. """ - # Sanity check: Only create a new channel if we do not already - # have one. - if not hasattr(self, "_grpc_channel"): - self._grpc_channel = self.create_channel( - self._host, credentials=self._credentials, - ) - - # Return the channel from cache. return self._grpc_channel @property 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 8de89fc3..0ee12f68 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 @@ -15,10 +15,12 @@ # limitations under the License. # +import warnings from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple from google.api_core import gapic_v1 # type: ignore from google.api_core import grpc_helpers_async # type: ignore +from google import auth # type: ignore from google.auth import credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore @@ -106,6 +108,7 @@ def __init__( channel: aio.Channel = None, api_mtls_endpoint: str = None, client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, quota_project_id=None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: @@ -127,14 +130,16 @@ def __init__( are passed to :func:`google.auth.default`. channel (Optional[aio.Channel]): A ``Channel`` instance through which to make calls. - api_mtls_endpoint (Optional[str]): The mutual TLS endpoint. If - provided, it overrides the ``host`` argument and tries to create + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create a mutual TLS channel with client SSL credentials from ``client_cert_source`` or applicatin default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): A - callback to provide client SSL certificate bytes and private key - bytes, both in PEM format. It is ignored if ``api_mtls_endpoint`` - is None. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for grpc channel. It is ignored if ``channel`` is provided. quota_project_id (Optional[str]): An optional project to use for billing and quota. client_info (google.api_core.gapic_v1.client_info.ClientInfo): @@ -149,6 +154,8 @@ def __init__( google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` and ``credentials_file`` are passed. """ + self._ssl_channel_credentials = ssl_channel_credentials + if channel: # Sanity check: Ensure that channel and credentials are not both # provided. @@ -156,13 +163,24 @@ def __init__( # If a channel was explicitly provided, set it. self._grpc_channel = channel + self._ssl_channel_credentials = None elif api_mtls_endpoint: + warnings.warn( + "api_mtls_endpoint and client_cert_source are deprecated", + DeprecationWarning, + ) + 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: @@ -182,6 +200,24 @@ def __init__( scopes=scopes or self.AUTH_SCOPES, quota_project_id=quota_project_id, ) + self._ssl_channel_credentials = ssl_credentials + else: + host = host if ":" in host else host + ":443" + + if credentials is None: + credentials, _ = auth.default( + scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id + ) + + # 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_channel_credentials, + scopes=scopes or self.AUTH_SCOPES, + quota_project_id=quota_project_id, + ) # Run the base constructor. super().__init__( @@ -202,13 +238,6 @@ def grpc_channel(self) -> aio.Channel: This property caches on the instance; repeated calls return the same channel. """ - # Sanity check: Only create a new channel if we do not already - # have one. - if not hasattr(self, "_grpc_channel"): - self._grpc_channel = self.create_channel( - self._host, credentials=self._credentials, - ) - # Return the channel from cache. return self._grpc_channel diff --git a/google/cloud/tasks_v2beta3/types/queue.py b/google/cloud/tasks_v2beta3/types/queue.py index 1c9cc8a2..4da1b48d 100644 --- a/google/cloud/tasks_v2beta3/types/queue.py +++ b/google/cloud/tasks_v2beta3/types/queue.py @@ -139,7 +139,7 @@ class Queue(proto.Message): Configuration options for writing logs to `Stackdriver Logging `__. If this field is unset, then no logs are written. - type (~.queue.Queue.Type): + type_ (~.queue.Queue.Type): Immutable. The type of a queue (push or pull). ``Queue.type`` is an immutable property of the queue that is @@ -178,7 +178,7 @@ class Type(proto.Enum): proto.MESSAGE, number=10, message="StackdriverLoggingConfig", ) - type = proto.Field(proto.ENUM, number=11, enum=Type,) + type_ = proto.Field(proto.ENUM, number=11, enum=Type,) class RateLimits(proto.Message): diff --git a/noxfile.py b/noxfile.py index 5f789fdd..a57e24be 100644 --- a/noxfile.py +++ b/noxfile.py @@ -28,7 +28,7 @@ DEFAULT_PYTHON_VERSION = "3.8" SYSTEM_TEST_PYTHON_VERSIONS = ["3.8"] -UNIT_TEST_PYTHON_VERSIONS = ["3.6", "3.7", "3.8"] +UNIT_TEST_PYTHON_VERSIONS = ["3.6", "3.7", "3.8", "3.9"] @nox.session(python=DEFAULT_PYTHON_VERSION) @@ -72,16 +72,17 @@ def default(session): # Install all test dependencies, then install this package in-place. session.install("asyncmock", "pytest-asyncio") - session.install("mock", "pytest", "pytest-cov") + session.install( + "mock", "pytest", "pytest-cov", + ) session.install("-e", ".") # Run py.test against the unit tests. session.run( "py.test", "--quiet", - "--cov=google.cloud.cloudtasks", - "--cov=google.cloud", - "--cov=tests.unit", + "--cov=google/cloud", + "--cov=tests/unit", "--cov-append", "--cov-config=.coveragerc", "--cov-report=", @@ -151,7 +152,7 @@ def docs(session): """Build the docs for this library.""" session.install("-e", ".") - session.install("sphinx<3.0.0", "alabaster", "recommonmark") + session.install("sphinx", "alabaster", "recommonmark") shutil.rmtree(os.path.join("docs", "_build"), ignore_errors=True) session.run( @@ -173,7 +174,9 @@ def docfx(session): """Build the docfx yaml files for this library.""" session.install("-e", ".") - session.install("sphinx<3.0.0", "alabaster", "recommonmark", "sphinx-docfx-yaml") + # 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") shutil.rmtree(os.path.join("docs", "_build"), ignore_errors=True) session.run( diff --git a/samples/snippets/noxfile.py b/samples/snippets/noxfile.py index ba55d7ce..bca0522e 100644 --- a/samples/snippets/noxfile.py +++ b/samples/snippets/noxfile.py @@ -17,6 +17,7 @@ import os from pathlib import Path import sys +from typing import Callable, Dict, List, Optional import nox @@ -39,6 +40,10 @@ # You can opt out from the test for specific Python versions. 'ignored_versions': ["2.7"], + # Old samples are opted out of enforcing Python type hints + # All new samples should feature them + 'enforce_type_hints': False, + # An envvar key for determining the project id to use. Change it # to 'BUILD_SPECIFIC_GCLOUD_PROJECT' if you want to opt in using a # build specific Cloud project. You can also use your own string @@ -64,7 +69,7 @@ TEST_CONFIG.update(TEST_CONFIG_OVERRIDE) -def get_pytest_env_vars(): +def get_pytest_env_vars() -> Dict[str, str]: """Returns a dict for pytest invocation.""" ret = {} @@ -93,7 +98,7 @@ def get_pytest_env_vars(): # -def _determine_local_import_names(start_dir): +def _determine_local_import_names(start_dir: str) -> List[str]: """Determines all import names that should be considered "local". This is used when running the linter to insure that import order is @@ -131,8 +136,11 @@ def _determine_local_import_names(start_dir): @nox.session -def lint(session): - session.install("flake8", "flake8-import-order") +def lint(session: nox.sessions.Session) -> None: + if not TEST_CONFIG['enforce_type_hints']: + session.install("flake8", "flake8-import-order") + else: + session.install("flake8", "flake8-import-order", "flake8-annotations") local_names = _determine_local_import_names(".") args = FLAKE8_COMMON_ARGS + [ @@ -141,8 +149,18 @@ def lint(session): "." ] session.run("flake8", *args) +# +# Black +# +@nox.session +def blacken(session: nox.sessions.Session) -> None: + session.install("black") + python_files = [path for path in os.listdir(".") if path.endswith(".py")] + + session.run("black", *python_files) + # # Sample Tests # @@ -151,7 +169,7 @@ def lint(session): PYTEST_COMMON_ARGS = ["--junitxml=sponge_log.xml"] -def _session_tests(session, post_install=None): +def _session_tests(session: nox.sessions.Session, post_install: Callable = None) -> None: """Runs py.test for a particular project.""" if os.path.exists("requirements.txt"): session.install("-r", "requirements.txt") @@ -177,7 +195,7 @@ def _session_tests(session, post_install=None): @nox.session(python=ALL_VERSIONS) -def py(session): +def py(session: nox.sessions.Session) -> None: """Runs py.test for a sample using the specified version of Python.""" if session.python in TESTED_VERSIONS: _session_tests(session) @@ -192,7 +210,7 @@ def py(session): # -def _get_repo_root(): +def _get_repo_root() -> Optional[str]: """ Returns the root folder of the project. """ # Get root of this repository. Assume we don't have directories nested deeper than 10 items. p = Path(os.getcwd()) @@ -201,6 +219,11 @@ def _get_repo_root(): break if Path(p / ".git").exists(): return str(p) + # .git is not available in repos cloned via Cloud Build + # setup.py is always in the library's root, so use that instead + # https://github.com/googleapis/synthtool/issues/792 + if Path(p / "setup.py").exists(): + return str(p) p = p.parent raise Exception("Unable to detect repository root.") @@ -210,7 +233,7 @@ def _get_repo_root(): @nox.session @nox.parametrize("path", GENERATED_READMES) -def readmegen(session, path): +def readmegen(session: nox.sessions.Session, path: str) -> None: """(Re-)generates the readme for a sample.""" session.install("jinja2", "pyyaml") dir_ = os.path.dirname(path) diff --git a/scripts/decrypt-secrets.sh b/scripts/decrypt-secrets.sh index ff599eb2..21f6d2a2 100755 --- a/scripts/decrypt-secrets.sh +++ b/scripts/decrypt-secrets.sh @@ -20,14 +20,27 @@ ROOT=$( dirname "$DIR" ) # Work from the project root. cd $ROOT +# Prevent it from overriding files. +# We recommend that sample authors use their own service account files and cloud project. +# In that case, they are supposed to prepare these files by themselves. +if [[ -f "testing/test-env.sh" ]] || \ + [[ -f "testing/service-account.json" ]] || \ + [[ -f "testing/client-secrets.json" ]]; then + echo "One or more target files exist, aborting." + exit 1 +fi + # Use SECRET_MANAGER_PROJECT if set, fallback to cloud-devrel-kokoro-resources. PROJECT_ID="${SECRET_MANAGER_PROJECT:-cloud-devrel-kokoro-resources}" gcloud secrets versions access latest --secret="python-docs-samples-test-env" \ + --project="${PROJECT_ID}" \ > testing/test-env.sh gcloud secrets versions access latest \ --secret="python-docs-samples-service-account" \ + --project="${PROJECT_ID}" \ > testing/service-account.json gcloud secrets versions access latest \ --secret="python-docs-samples-client-secrets" \ - > testing/client-secrets.json \ No newline at end of file + --project="${PROJECT_ID}" \ + > testing/client-secrets.json diff --git a/scripts/fixup_tasks_v2_keywords.py b/scripts/fixup_tasks_v2_keywords.py index 30d65ed0..30997b65 100644 --- a/scripts/fixup_tasks_v2_keywords.py +++ b/scripts/fixup_tasks_v2_keywords.py @@ -1,3 +1,4 @@ +#! /usr/bin/env python3 # -*- coding: utf-8 -*- # Copyright 2020 Google LLC diff --git a/scripts/fixup_tasks_v2beta2_keywords.py b/scripts/fixup_tasks_v2beta2_keywords.py index 3d480836..7277f4ab 100644 --- a/scripts/fixup_tasks_v2beta2_keywords.py +++ b/scripts/fixup_tasks_v2beta2_keywords.py @@ -1,3 +1,4 @@ +#! /usr/bin/env python3 # -*- coding: utf-8 -*- # Copyright 2020 Google LLC diff --git a/scripts/fixup_tasks_v2beta3_keywords.py b/scripts/fixup_tasks_v2beta3_keywords.py index 30d65ed0..30997b65 100644 --- a/scripts/fixup_tasks_v2beta3_keywords.py +++ b/scripts/fixup_tasks_v2beta3_keywords.py @@ -1,3 +1,4 @@ +#! /usr/bin/env python3 # -*- coding: utf-8 -*- # Copyright 2020 Google LLC diff --git a/synth.metadata b/synth.metadata index 08fb9823..eae9e096 100644 --- a/synth.metadata +++ b/synth.metadata @@ -3,22 +3,30 @@ { "git": { "name": ".", - "remote": "https://github.com/googleapis/python-tasks.git", - "sha": "1a5a65fd55ba23421b4e7fbce0e74a46697ba092" + "remote": "git@github.com:googleapis/python-tasks", + "sha": "2261c21b962c7e0aaa3e1b5c7c66a04258ec0339" + } + }, + { + "git": { + "name": "googleapis", + "remote": "https://github.com/googleapis/googleapis.git", + "sha": "d9bc6eb41bdacddcd5bd3a0af581bc769cc080d3", + "internalRef": "346185632" } }, { "git": { "name": "synthtool", "remote": "https://github.com/googleapis/synthtool.git", - "sha": "d91dd8aac77f7a9c5506c238038a26fa4f9e361e" + "sha": "5d11bd2888c38ce1fb6fa6bf25494a4219a73928" } }, { "git": { "name": "synthtool", "remote": "https://github.com/googleapis/synthtool.git", - "sha": "d91dd8aac77f7a9c5506c238038a26fa4f9e361e" + "sha": "5d11bd2888c38ce1fb6fa6bf25494a4219a73928" } } ], diff --git a/synth.py b/synth.py index 4d558c30..f01a891b 100644 --- a/synth.py +++ b/synth.py @@ -57,7 +57,4 @@ # ---------------------------------------------------------------------------- python.py_samples(skip_readmes=True) -# TODO(busunkim): Use latest sphinx after microgenerator transition -s.replace("noxfile.py", """['"]sphinx['"]""", '"sphinx<3.0.0"') - s.shell.run(["nox", "-s", "blacken"], hide_output=False) diff --git a/tests/unit/gapic/tasks_v2/test_cloud_tasks.py b/tests/unit/gapic/tasks_v2/test_cloud_tasks.py index f4e2e44b..1f97901d 100644 --- a/tests/unit/gapic/tasks_v2/test_cloud_tasks.py +++ b/tests/unit/gapic/tasks_v2/test_cloud_tasks.py @@ -46,7 +46,7 @@ from google.iam.v1 import options_pb2 as options # type: ignore from google.iam.v1 import policy_pb2 as policy # type: ignore from google.oauth2 import service_account -from google.protobuf import any_pb2 as any # type: ignore +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 @@ -103,12 +103,12 @@ def test_cloud_tasks_client_from_service_account_file(client_class): ) as factory: factory.return_value = creds client = client_class.from_service_account_file("dummy/file/path.json") - assert client._transport._credentials == creds + assert client.transport._credentials == creds client = client_class.from_service_account_json("dummy/file/path.json") - assert client._transport._credentials == creds + assert client.transport._credentials == creds - assert client._transport._host == "cloudtasks.googleapis.com:443" + assert client.transport._host == "cloudtasks.googleapis.com:443" def test_cloud_tasks_client_get_transport_class(): @@ -162,15 +162,14 @@ def test_cloud_tasks_client_client_options( credentials_file=None, host="squid.clam.whelk", scopes=None, - api_mtls_endpoint="squid.clam.whelk", - client_cert_source=None, + ssl_channel_credentials=None, quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, ) - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS is + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is # "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS": "never"}): + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): with mock.patch.object(transport_class, "__init__") as patched: patched.return_value = None client = client_class() @@ -179,15 +178,14 @@ def test_cloud_tasks_client_client_options( credentials_file=None, host=client.DEFAULT_ENDPOINT, scopes=None, - api_mtls_endpoint=client.DEFAULT_ENDPOINT, - client_cert_source=None, + ssl_channel_credentials=None, quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, ) - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS is + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is # "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS": "always"}): + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): with mock.patch.object(transport_class, "__init__") as patched: patched.return_value = None client = client_class() @@ -196,95 +194,173 @@ def test_cloud_tasks_client_client_options( credentials_file=None, host=client.DEFAULT_MTLS_ENDPOINT, scopes=None, - api_mtls_endpoint=client.DEFAULT_MTLS_ENDPOINT, - client_cert_source=None, + ssl_channel_credentials=None, quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, ) - # Check the case api_endpoint is not provided, GOOGLE_API_USE_MTLS is - # "auto", and client_cert_source is provided. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS": "auto"}): + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError): + client = client_class() + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"} + ): + with pytest.raises(ValueError): + client = client_class() + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + ssl_channel_credentials=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name,use_client_cert_env", + [ + (CloudTasksClient, transports.CloudTasksGrpcTransport, "grpc", "true"), + ( + CloudTasksAsyncClient, + transports.CloudTasksGrpcAsyncIOTransport, + "grpc_asyncio", + "true", + ), + (CloudTasksClient, transports.CloudTasksGrpcTransport, "grpc", "false"), + ( + CloudTasksAsyncClient, + transports.CloudTasksGrpcAsyncIOTransport, + "grpc_asyncio", + "false", + ), + ], +) +@mock.patch.object( + CloudTasksClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CloudTasksClient) +) +@mock.patch.object( + CloudTasksAsyncClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(CloudTasksAsyncClient), +) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_cloud_tasks_client_mtls_env_auto( + client_class, transport_class, transport_name, use_client_cert_env +): + # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default + # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. + + # Check the case client_cert_source is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} + ): options = client_options.ClientOptions( client_cert_source=client_cert_source_callback ) with mock.patch.object(transport_class, "__init__") as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_MTLS_ENDPOINT, - scopes=None, - api_mtls_endpoint=client.DEFAULT_MTLS_ENDPOINT, - client_cert_source=client_cert_source_callback, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - - # Check the case api_endpoint is not provided, GOOGLE_API_USE_MTLS is - # "auto", and default_client_cert_source is provided. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS": "auto"}): - with mock.patch.object(transport_class, "__init__") as patched: + ssl_channel_creds = mock.Mock() with mock.patch( - "google.auth.transport.mtls.has_default_client_cert_source", - return_value=True, + "grpc.ssl_channel_credentials", return_value=ssl_channel_creds ): patched.return_value = None - client = client_class() + client = client_class(client_options=options) + + if use_client_cert_env == "false": + expected_ssl_channel_creds = None + expected_host = client.DEFAULT_ENDPOINT + else: + expected_ssl_channel_creds = ssl_channel_creds + expected_host = client.DEFAULT_MTLS_ENDPOINT + patched.assert_called_once_with( credentials=None, credentials_file=None, - host=client.DEFAULT_MTLS_ENDPOINT, + host=expected_host, scopes=None, - api_mtls_endpoint=client.DEFAULT_MTLS_ENDPOINT, - client_cert_source=None, + ssl_channel_credentials=expected_ssl_channel_creds, quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, ) - # Check the case api_endpoint is not provided, GOOGLE_API_USE_MTLS is - # "auto", but client_cert_source and default_client_cert_source are None. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS": "auto"}): + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} + ): with mock.patch.object(transport_class, "__init__") as patched: with mock.patch( - "google.auth.transport.mtls.has_default_client_cert_source", - return_value=False, + "google.auth.transport.grpc.SslCredentials.__init__", return_value=None ): - patched.return_value = None - client = client_class() - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - api_mtls_endpoint=client.DEFAULT_ENDPOINT, - client_cert_source=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS has - # unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS": "Unsupported"}): - with pytest.raises(MutualTLSChannelError): - client = client_class() - - # Check the case quota_project_id is provided - options = client_options.ClientOptions(quota_project_id="octopus") - with mock.patch.object(transport_class, "__init__") as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - api_mtls_endpoint=client.DEFAULT_ENDPOINT, - client_cert_source=None, - quota_project_id="octopus", - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) + with mock.patch( + "google.auth.transport.grpc.SslCredentials.is_mtls", + new_callable=mock.PropertyMock, + ) as is_mtls_mock: + with mock.patch( + "google.auth.transport.grpc.SslCredentials.ssl_credentials", + new_callable=mock.PropertyMock, + ) as ssl_credentials_mock: + if use_client_cert_env == "false": + is_mtls_mock.return_value = False + ssl_credentials_mock.return_value = None + expected_host = client.DEFAULT_ENDPOINT + expected_ssl_channel_creds = None + else: + is_mtls_mock.return_value = True + ssl_credentials_mock.return_value = mock.Mock() + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_ssl_channel_creds = ( + ssl_credentials_mock.return_value + ) + + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + ssl_channel_credentials=expected_ssl_channel_creds, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} + ): + with mock.patch.object(transport_class, "__init__") as patched: + with mock.patch( + "google.auth.transport.grpc.SslCredentials.__init__", return_value=None + ): + with mock.patch( + "google.auth.transport.grpc.SslCredentials.is_mtls", + new_callable=mock.PropertyMock, + ) as is_mtls_mock: + is_mtls_mock.return_value = False + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + ssl_channel_credentials=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) @pytest.mark.parametrize( @@ -311,8 +387,7 @@ def test_cloud_tasks_client_client_options_scopes( credentials_file=None, host=client.DEFAULT_ENDPOINT, scopes=["1", "2"], - api_mtls_endpoint=client.DEFAULT_ENDPOINT, - client_cert_source=None, + ssl_channel_credentials=None, quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, ) @@ -342,8 +417,7 @@ def test_cloud_tasks_client_client_options_credentials_file( credentials_file="credentials.json", host=client.DEFAULT_ENDPOINT, scopes=None, - api_mtls_endpoint=client.DEFAULT_ENDPOINT, - client_cert_source=None, + ssl_channel_credentials=None, quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, ) @@ -360,8 +434,7 @@ def test_cloud_tasks_client_client_options_from_dict(): credentials_file=None, host="squid.clam.whelk", scopes=None, - api_mtls_endpoint="squid.clam.whelk", - client_cert_source=None, + ssl_channel_credentials=None, quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, ) @@ -379,7 +452,7 @@ def test_list_queues( request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client._transport.list_queues), "__call__") as call: + 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( next_page_token="next_page_token_value", @@ -394,6 +467,7 @@ def test_list_queues( 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" @@ -404,19 +478,19 @@ def test_list_queues_from_dict(): @pytest.mark.asyncio -async def test_list_queues_async(transport: str = "grpc_asyncio"): +async def test_list_queues_async( + transport: str = "grpc_asyncio", request_type=cloudtasks.ListQueuesRequest +): client = CloudTasksAsyncClient( credentials=credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, # and we are mocking out the actual API, so just send an empty request. - request = cloudtasks.ListQueuesRequest() + request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client._client._transport.list_queues), "__call__" - ) as call: + with mock.patch.object(type(client.transport.list_queues), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( cloudtasks.ListQueuesResponse(next_page_token="next_page_token_value",) @@ -428,7 +502,7 @@ async def test_list_queues_async(transport: str = "grpc_asyncio"): assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == request + assert args[0] == cloudtasks.ListQueuesRequest() # Establish that the response is the type that we expect. assert isinstance(response, pagers.ListQueuesAsyncPager) @@ -436,6 +510,11 @@ async def test_list_queues_async(transport: str = "grpc_asyncio"): assert response.next_page_token == "next_page_token_value" +@pytest.mark.asyncio +async def test_list_queues_async_from_dict(): + await test_list_queues_async(request_type=dict) + + def test_list_queues_field_headers(): client = CloudTasksClient(credentials=credentials.AnonymousCredentials(),) @@ -445,7 +524,7 @@ def test_list_queues_field_headers(): 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: + with mock.patch.object(type(client.transport.list_queues), "__call__") as call: call.return_value = cloudtasks.ListQueuesResponse() client.list_queues(request) @@ -470,9 +549,7 @@ async def test_list_queues_field_headers_async(): request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client._client._transport.list_queues), "__call__" - ) as call: + with mock.patch.object(type(client.transport.list_queues), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( cloudtasks.ListQueuesResponse() ) @@ -493,7 +570,7 @@ def test_list_queues_flattened(): client = CloudTasksClient(credentials=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: + 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() @@ -525,9 +602,7 @@ async def test_list_queues_flattened_async(): client = CloudTasksAsyncClient(credentials=credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client._client._transport.list_queues), "__call__" - ) as call: + 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() @@ -562,7 +637,7 @@ def test_list_queues_pager(): client = CloudTasksClient(credentials=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: + with mock.patch.object(type(client.transport.list_queues), "__call__") as call: # Set the response to a series of pages. call.side_effect = ( cloudtasks.ListQueuesResponse( @@ -594,7 +669,7 @@ def test_list_queues_pages(): client = CloudTasksClient(credentials=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: + with mock.patch.object(type(client.transport.list_queues), "__call__") as call: # Set the response to a series of pages. call.side_effect = ( cloudtasks.ListQueuesResponse( @@ -619,9 +694,7 @@ async def test_list_queues_async_pager(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client._client._transport.list_queues), - "__call__", - new_callable=mock.AsyncMock, + type(client.transport.list_queues), "__call__", new_callable=mock.AsyncMock ) as call: # Set the response to a series of pages. call.side_effect = ( @@ -652,9 +725,7 @@ async def test_list_queues_async_pages(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client._client._transport.list_queues), - "__call__", - new_callable=mock.AsyncMock, + type(client.transport.list_queues), "__call__", new_callable=mock.AsyncMock ) as call: # Set the response to a series of pages. call.side_effect = ( @@ -686,7 +757,7 @@ def test_get_queue(transport: str = "grpc", request_type=cloudtasks.GetQueueRequ request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client._transport.get_queue), "__call__") as call: + 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( name="name_value", state=queue.Queue.State.RUNNING, @@ -701,6 +772,7 @@ def test_get_queue(transport: str = "grpc", request_type=cloudtasks.GetQueueRequ 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" @@ -713,19 +785,19 @@ def test_get_queue_from_dict(): @pytest.mark.asyncio -async def test_get_queue_async(transport: str = "grpc_asyncio"): +async def test_get_queue_async( + transport: str = "grpc_asyncio", request_type=cloudtasks.GetQueueRequest +): client = CloudTasksAsyncClient( credentials=credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, # and we are mocking out the actual API, so just send an empty request. - request = cloudtasks.GetQueueRequest() + request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client._client._transport.get_queue), "__call__" - ) as call: + with mock.patch.object(type(client.transport.get_queue), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( queue.Queue(name="name_value", state=queue.Queue.State.RUNNING,) @@ -737,7 +809,7 @@ async def test_get_queue_async(transport: str = "grpc_asyncio"): assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == request + assert args[0] == cloudtasks.GetQueueRequest() # Establish that the response is the type that we expect. assert isinstance(response, queue.Queue) @@ -747,6 +819,11 @@ async def test_get_queue_async(transport: str = "grpc_asyncio"): assert response.state == queue.Queue.State.RUNNING +@pytest.mark.asyncio +async def test_get_queue_async_from_dict(): + await test_get_queue_async(request_type=dict) + + def test_get_queue_field_headers(): client = CloudTasksClient(credentials=credentials.AnonymousCredentials(),) @@ -756,7 +833,7 @@ def test_get_queue_field_headers(): 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: + with mock.patch.object(type(client.transport.get_queue), "__call__") as call: call.return_value = queue.Queue() client.get_queue(request) @@ -781,9 +858,7 @@ async def test_get_queue_field_headers_async(): request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client._client._transport.get_queue), "__call__" - ) as call: + 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) @@ -802,7 +877,7 @@ def test_get_queue_flattened(): client = CloudTasksClient(credentials=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: + 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() @@ -834,9 +909,7 @@ async def test_get_queue_flattened_async(): client = CloudTasksAsyncClient(credentials=credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client._client._transport.get_queue), "__call__" - ) as call: + 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() @@ -877,7 +950,7 @@ def test_create_queue( request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client._transport.create_queue), "__call__") as call: + 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( name="name_value", state=gct_queue.Queue.State.RUNNING, @@ -892,6 +965,7 @@ def test_create_queue( 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" @@ -904,19 +978,19 @@ def test_create_queue_from_dict(): @pytest.mark.asyncio -async def test_create_queue_async(transport: str = "grpc_asyncio"): +async def test_create_queue_async( + transport: str = "grpc_asyncio", request_type=cloudtasks.CreateQueueRequest +): client = CloudTasksAsyncClient( credentials=credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, # and we are mocking out the actual API, so just send an empty request. - request = cloudtasks.CreateQueueRequest() + request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client._client._transport.create_queue), "__call__" - ) as call: + with mock.patch.object(type(client.transport.create_queue), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( gct_queue.Queue(name="name_value", state=gct_queue.Queue.State.RUNNING,) @@ -928,7 +1002,7 @@ async def test_create_queue_async(transport: str = "grpc_asyncio"): assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == request + assert args[0] == cloudtasks.CreateQueueRequest() # Establish that the response is the type that we expect. assert isinstance(response, gct_queue.Queue) @@ -938,6 +1012,11 @@ async def test_create_queue_async(transport: str = "grpc_asyncio"): assert response.state == gct_queue.Queue.State.RUNNING +@pytest.mark.asyncio +async def test_create_queue_async_from_dict(): + await test_create_queue_async(request_type=dict) + + def test_create_queue_field_headers(): client = CloudTasksClient(credentials=credentials.AnonymousCredentials(),) @@ -947,7 +1026,7 @@ def test_create_queue_field_headers(): 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: + with mock.patch.object(type(client.transport.create_queue), "__call__") as call: call.return_value = gct_queue.Queue() client.create_queue(request) @@ -972,9 +1051,7 @@ async def test_create_queue_field_headers_async(): request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client._client._transport.create_queue), "__call__" - ) as call: + 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) @@ -993,7 +1070,7 @@ def test_create_queue_flattened(): client = CloudTasksClient(credentials=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: + 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() @@ -1031,9 +1108,7 @@ async def test_create_queue_flattened_async(): client = CloudTasksAsyncClient(credentials=credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client._client._transport.create_queue), "__call__" - ) as call: + 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() @@ -1080,7 +1155,7 @@ def test_update_queue( request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client._transport.update_queue), "__call__") as call: + 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( name="name_value", state=gct_queue.Queue.State.RUNNING, @@ -1095,6 +1170,7 @@ def test_update_queue( 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" @@ -1107,19 +1183,19 @@ def test_update_queue_from_dict(): @pytest.mark.asyncio -async def test_update_queue_async(transport: str = "grpc_asyncio"): +async def test_update_queue_async( + transport: str = "grpc_asyncio", request_type=cloudtasks.UpdateQueueRequest +): client = CloudTasksAsyncClient( credentials=credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, # and we are mocking out the actual API, so just send an empty request. - request = cloudtasks.UpdateQueueRequest() + request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client._client._transport.update_queue), "__call__" - ) as call: + with mock.patch.object(type(client.transport.update_queue), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( gct_queue.Queue(name="name_value", state=gct_queue.Queue.State.RUNNING,) @@ -1131,7 +1207,7 @@ async def test_update_queue_async(transport: str = "grpc_asyncio"): assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == request + assert args[0] == cloudtasks.UpdateQueueRequest() # Establish that the response is the type that we expect. assert isinstance(response, gct_queue.Queue) @@ -1141,6 +1217,11 @@ async def test_update_queue_async(transport: str = "grpc_asyncio"): assert response.state == gct_queue.Queue.State.RUNNING +@pytest.mark.asyncio +async def test_update_queue_async_from_dict(): + await test_update_queue_async(request_type=dict) + + def test_update_queue_field_headers(): client = CloudTasksClient(credentials=credentials.AnonymousCredentials(),) @@ -1150,7 +1231,7 @@ def test_update_queue_field_headers(): 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: + with mock.patch.object(type(client.transport.update_queue), "__call__") as call: call.return_value = gct_queue.Queue() client.update_queue(request) @@ -1175,9 +1256,7 @@ async def test_update_queue_field_headers_async(): request.queue.name = "queue.name/value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client._client._transport.update_queue), "__call__" - ) as call: + 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) @@ -1196,7 +1275,7 @@ def test_update_queue_flattened(): client = CloudTasksClient(credentials=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: + 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() @@ -1235,9 +1314,7 @@ async def test_update_queue_flattened_async(): client = CloudTasksAsyncClient(credentials=credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client._client._transport.update_queue), "__call__" - ) as call: + 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() @@ -1285,7 +1362,7 @@ def test_delete_queue( request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client._transport.delete_queue), "__call__") as call: + with mock.patch.object(type(client.transport.delete_queue), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = None @@ -1306,19 +1383,19 @@ def test_delete_queue_from_dict(): @pytest.mark.asyncio -async def test_delete_queue_async(transport: str = "grpc_asyncio"): +async def test_delete_queue_async( + transport: str = "grpc_asyncio", request_type=cloudtasks.DeleteQueueRequest +): client = CloudTasksAsyncClient( credentials=credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, # and we are mocking out the actual API, so just send an empty request. - request = cloudtasks.DeleteQueueRequest() + request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client._client._transport.delete_queue), "__call__" - ) as call: + 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) @@ -1328,12 +1405,17 @@ async def test_delete_queue_async(transport: str = "grpc_asyncio"): assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == request + assert args[0] == cloudtasks.DeleteQueueRequest() # Establish that the response is the type that we expect. assert response is None +@pytest.mark.asyncio +async def test_delete_queue_async_from_dict(): + await test_delete_queue_async(request_type=dict) + + def test_delete_queue_field_headers(): client = CloudTasksClient(credentials=credentials.AnonymousCredentials(),) @@ -1343,7 +1425,7 @@ def test_delete_queue_field_headers(): 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: + with mock.patch.object(type(client.transport.delete_queue), "__call__") as call: call.return_value = None client.delete_queue(request) @@ -1368,9 +1450,7 @@ async def test_delete_queue_field_headers_async(): request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client._client._transport.delete_queue), "__call__" - ) as call: + 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) @@ -1389,7 +1469,7 @@ def test_delete_queue_flattened(): client = CloudTasksClient(credentials=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: + with mock.patch.object(type(client.transport.delete_queue), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = None @@ -1421,9 +1501,7 @@ async def test_delete_queue_flattened_async(): client = CloudTasksAsyncClient(credentials=credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client._client._transport.delete_queue), "__call__" - ) as call: + with mock.patch.object(type(client.transport.delete_queue), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = None @@ -1464,7 +1542,7 @@ def test_purge_queue( request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client._transport.purge_queue), "__call__") as call: + 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( name="name_value", state=queue.Queue.State.RUNNING, @@ -1479,6 +1557,7 @@ def test_purge_queue( 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" @@ -1491,19 +1570,19 @@ def test_purge_queue_from_dict(): @pytest.mark.asyncio -async def test_purge_queue_async(transport: str = "grpc_asyncio"): +async def test_purge_queue_async( + transport: str = "grpc_asyncio", request_type=cloudtasks.PurgeQueueRequest +): client = CloudTasksAsyncClient( credentials=credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, # and we are mocking out the actual API, so just send an empty request. - request = cloudtasks.PurgeQueueRequest() + request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client._client._transport.purge_queue), "__call__" - ) as call: + with mock.patch.object(type(client.transport.purge_queue), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( queue.Queue(name="name_value", state=queue.Queue.State.RUNNING,) @@ -1515,7 +1594,7 @@ async def test_purge_queue_async(transport: str = "grpc_asyncio"): assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == request + assert args[0] == cloudtasks.PurgeQueueRequest() # Establish that the response is the type that we expect. assert isinstance(response, queue.Queue) @@ -1525,6 +1604,11 @@ async def test_purge_queue_async(transport: str = "grpc_asyncio"): assert response.state == queue.Queue.State.RUNNING +@pytest.mark.asyncio +async def test_purge_queue_async_from_dict(): + await test_purge_queue_async(request_type=dict) + + def test_purge_queue_field_headers(): client = CloudTasksClient(credentials=credentials.AnonymousCredentials(),) @@ -1534,7 +1618,7 @@ def test_purge_queue_field_headers(): 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: + with mock.patch.object(type(client.transport.purge_queue), "__call__") as call: call.return_value = queue.Queue() client.purge_queue(request) @@ -1559,9 +1643,7 @@ async def test_purge_queue_field_headers_async(): request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client._client._transport.purge_queue), "__call__" - ) as call: + 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) @@ -1580,7 +1662,7 @@ def test_purge_queue_flattened(): client = CloudTasksClient(credentials=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: + 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() @@ -1612,9 +1694,7 @@ async def test_purge_queue_flattened_async(): client = CloudTasksAsyncClient(credentials=credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client._client._transport.purge_queue), "__call__" - ) as call: + 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() @@ -1655,7 +1735,7 @@ def test_pause_queue( request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client._transport.pause_queue), "__call__") as call: + 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( name="name_value", state=queue.Queue.State.RUNNING, @@ -1670,6 +1750,7 @@ def test_pause_queue( 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" @@ -1682,19 +1763,19 @@ def test_pause_queue_from_dict(): @pytest.mark.asyncio -async def test_pause_queue_async(transport: str = "grpc_asyncio"): +async def test_pause_queue_async( + transport: str = "grpc_asyncio", request_type=cloudtasks.PauseQueueRequest +): client = CloudTasksAsyncClient( credentials=credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, # and we are mocking out the actual API, so just send an empty request. - request = cloudtasks.PauseQueueRequest() + request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client._client._transport.pause_queue), "__call__" - ) as call: + with mock.patch.object(type(client.transport.pause_queue), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( queue.Queue(name="name_value", state=queue.Queue.State.RUNNING,) @@ -1706,7 +1787,7 @@ async def test_pause_queue_async(transport: str = "grpc_asyncio"): assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == request + assert args[0] == cloudtasks.PauseQueueRequest() # Establish that the response is the type that we expect. assert isinstance(response, queue.Queue) @@ -1716,6 +1797,11 @@ async def test_pause_queue_async(transport: str = "grpc_asyncio"): assert response.state == queue.Queue.State.RUNNING +@pytest.mark.asyncio +async def test_pause_queue_async_from_dict(): + await test_pause_queue_async(request_type=dict) + + def test_pause_queue_field_headers(): client = CloudTasksClient(credentials=credentials.AnonymousCredentials(),) @@ -1725,7 +1811,7 @@ def test_pause_queue_field_headers(): 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: + with mock.patch.object(type(client.transport.pause_queue), "__call__") as call: call.return_value = queue.Queue() client.pause_queue(request) @@ -1750,9 +1836,7 @@ async def test_pause_queue_field_headers_async(): request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client._client._transport.pause_queue), "__call__" - ) as call: + 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) @@ -1771,7 +1855,7 @@ def test_pause_queue_flattened(): client = CloudTasksClient(credentials=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: + 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() @@ -1803,9 +1887,7 @@ async def test_pause_queue_flattened_async(): client = CloudTasksAsyncClient(credentials=credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client._client._transport.pause_queue), "__call__" - ) as call: + 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() @@ -1846,7 +1928,7 @@ def test_resume_queue( request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client._transport.resume_queue), "__call__") as call: + 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( name="name_value", state=queue.Queue.State.RUNNING, @@ -1861,6 +1943,7 @@ def test_resume_queue( 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" @@ -1873,19 +1956,19 @@ def test_resume_queue_from_dict(): @pytest.mark.asyncio -async def test_resume_queue_async(transport: str = "grpc_asyncio"): +async def test_resume_queue_async( + transport: str = "grpc_asyncio", request_type=cloudtasks.ResumeQueueRequest +): client = CloudTasksAsyncClient( credentials=credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, # and we are mocking out the actual API, so just send an empty request. - request = cloudtasks.ResumeQueueRequest() + request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client._client._transport.resume_queue), "__call__" - ) as call: + with mock.patch.object(type(client.transport.resume_queue), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( queue.Queue(name="name_value", state=queue.Queue.State.RUNNING,) @@ -1897,7 +1980,7 @@ async def test_resume_queue_async(transport: str = "grpc_asyncio"): assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == request + assert args[0] == cloudtasks.ResumeQueueRequest() # Establish that the response is the type that we expect. assert isinstance(response, queue.Queue) @@ -1907,6 +1990,11 @@ async def test_resume_queue_async(transport: str = "grpc_asyncio"): assert response.state == queue.Queue.State.RUNNING +@pytest.mark.asyncio +async def test_resume_queue_async_from_dict(): + await test_resume_queue_async(request_type=dict) + + def test_resume_queue_field_headers(): client = CloudTasksClient(credentials=credentials.AnonymousCredentials(),) @@ -1916,7 +2004,7 @@ def test_resume_queue_field_headers(): 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: + with mock.patch.object(type(client.transport.resume_queue), "__call__") as call: call.return_value = queue.Queue() client.resume_queue(request) @@ -1941,9 +2029,7 @@ async def test_resume_queue_field_headers_async(): request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client._client._transport.resume_queue), "__call__" - ) as call: + 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) @@ -1962,7 +2048,7 @@ def test_resume_queue_flattened(): client = CloudTasksClient(credentials=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: + 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() @@ -1994,9 +2080,7 @@ async def test_resume_queue_flattened_async(): client = CloudTasksAsyncClient(credentials=credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client._client._transport.resume_queue), "__call__" - ) as call: + 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() @@ -2037,7 +2121,7 @@ def test_get_iam_policy( request = request_type() # 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: + 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",) @@ -2050,6 +2134,7 @@ def test_get_iam_policy( assert args[0] == iam_policy.GetIamPolicyRequest() # Establish that the response is the type that we expect. + assert isinstance(response, policy.Policy) assert response.version == 774 @@ -2062,19 +2147,19 @@ def test_get_iam_policy_from_dict(): @pytest.mark.asyncio -async def test_get_iam_policy_async(transport: str = "grpc_asyncio"): +async def test_get_iam_policy_async( + transport: str = "grpc_asyncio", request_type=iam_policy.GetIamPolicyRequest +): client = CloudTasksAsyncClient( credentials=credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, # and we are mocking out the actual API, so just send an empty request. - request = iam_policy.GetIamPolicyRequest() + request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client._client._transport.get_iam_policy), "__call__" - ) as call: + 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",) @@ -2086,7 +2171,7 @@ async def test_get_iam_policy_async(transport: str = "grpc_asyncio"): assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == request + assert args[0] == iam_policy.GetIamPolicyRequest() # Establish that the response is the type that we expect. assert isinstance(response, policy.Policy) @@ -2096,6 +2181,11 @@ async def test_get_iam_policy_async(transport: str = "grpc_asyncio"): assert response.etag == b"etag_blob" +@pytest.mark.asyncio +async def test_get_iam_policy_async_from_dict(): + await test_get_iam_policy_async(request_type=dict) + + def test_get_iam_policy_field_headers(): client = CloudTasksClient(credentials=credentials.AnonymousCredentials(),) @@ -2105,7 +2195,7 @@ def test_get_iam_policy_field_headers(): 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: + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: call.return_value = policy.Policy() client.get_iam_policy(request) @@ -2130,9 +2220,7 @@ async def test_get_iam_policy_field_headers_async(): request.resource = "resource/value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client._client._transport.get_iam_policy), "__call__" - ) as call: + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy.Policy()) await client.get_iam_policy(request) @@ -2147,10 +2235,10 @@ async def test_get_iam_policy_field_headers_async(): assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] -def test_get_iam_policy_from_dict(): +def test_get_iam_policy_from_dict_foreign(): client = CloudTasksClient(credentials=credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client._transport.get_iam_policy), "__call__") as call: + 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() @@ -2167,7 +2255,7 @@ def test_get_iam_policy_flattened(): client = CloudTasksClient(credentials=credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client._transport.get_iam_policy), "__call__") as call: + 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() @@ -2199,9 +2287,7 @@ async def test_get_iam_policy_flattened_async(): client = CloudTasksAsyncClient(credentials=credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client._client._transport.get_iam_policy), "__call__" - ) as call: + 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() @@ -2242,7 +2328,7 @@ def test_set_iam_policy( 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: + 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",) @@ -2255,6 +2341,7 @@ def test_set_iam_policy( assert args[0] == iam_policy.SetIamPolicyRequest() # Establish that the response is the type that we expect. + assert isinstance(response, policy.Policy) assert response.version == 774 @@ -2267,19 +2354,19 @@ def test_set_iam_policy_from_dict(): @pytest.mark.asyncio -async def test_set_iam_policy_async(transport: str = "grpc_asyncio"): +async def test_set_iam_policy_async( + transport: str = "grpc_asyncio", request_type=iam_policy.SetIamPolicyRequest +): client = CloudTasksAsyncClient( credentials=credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, # and we are mocking out the actual API, so just send an empty request. - request = iam_policy.SetIamPolicyRequest() + request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client._client._transport.set_iam_policy), "__call__" - ) as call: + 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",) @@ -2291,7 +2378,7 @@ async def test_set_iam_policy_async(transport: str = "grpc_asyncio"): assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == request + assert args[0] == iam_policy.SetIamPolicyRequest() # Establish that the response is the type that we expect. assert isinstance(response, policy.Policy) @@ -2301,6 +2388,11 @@ async def test_set_iam_policy_async(transport: str = "grpc_asyncio"): assert response.etag == b"etag_blob" +@pytest.mark.asyncio +async def test_set_iam_policy_async_from_dict(): + await test_set_iam_policy_async(request_type=dict) + + def test_set_iam_policy_field_headers(): client = CloudTasksClient(credentials=credentials.AnonymousCredentials(),) @@ -2310,7 +2402,7 @@ def test_set_iam_policy_field_headers(): 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: + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: call.return_value = policy.Policy() client.set_iam_policy(request) @@ -2335,9 +2427,7 @@ async def test_set_iam_policy_field_headers_async(): request.resource = "resource/value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client._client._transport.set_iam_policy), "__call__" - ) as call: + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy.Policy()) await client.set_iam_policy(request) @@ -2352,10 +2442,10 @@ async def test_set_iam_policy_field_headers_async(): assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] -def test_set_iam_policy_from_dict(): +def test_set_iam_policy_from_dict_foreign(): client = CloudTasksClient(credentials=credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client._transport.set_iam_policy), "__call__") as call: + 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() @@ -2372,7 +2462,7 @@ def test_set_iam_policy_flattened(): client = CloudTasksClient(credentials=credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client._transport.set_iam_policy), "__call__") as call: + 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() @@ -2404,9 +2494,7 @@ async def test_set_iam_policy_flattened_async(): client = CloudTasksAsyncClient(credentials=credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client._client._transport.set_iam_policy), "__call__" - ) as call: + 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() @@ -2448,7 +2536,7 @@ def test_test_iam_permissions( # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client._transport.test_iam_permissions), "__call__" + type(client.transport.test_iam_permissions), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = iam_policy.TestIamPermissionsResponse( @@ -2464,6 +2552,7 @@ def test_test_iam_permissions( assert args[0] == iam_policy.TestIamPermissionsRequest() # Establish that the response is the type that we expect. + assert isinstance(response, iam_policy.TestIamPermissionsResponse) assert response.permissions == ["permissions_value"] @@ -2474,18 +2563,20 @@ def test_test_iam_permissions_from_dict(): @pytest.mark.asyncio -async def test_test_iam_permissions_async(transport: str = "grpc_asyncio"): +async def test_test_iam_permissions_async( + transport: str = "grpc_asyncio", request_type=iam_policy.TestIamPermissionsRequest +): client = CloudTasksAsyncClient( credentials=credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, # and we are mocking out the actual API, so just send an empty request. - request = iam_policy.TestIamPermissionsRequest() + request = request_type() # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client._client._transport.test_iam_permissions), "__call__" + type(client.transport.test_iam_permissions), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( @@ -2498,7 +2589,7 @@ async def test_test_iam_permissions_async(transport: str = "grpc_asyncio"): assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == request + assert args[0] == iam_policy.TestIamPermissionsRequest() # Establish that the response is the type that we expect. assert isinstance(response, iam_policy.TestIamPermissionsResponse) @@ -2506,6 +2597,11 @@ async def test_test_iam_permissions_async(transport: str = "grpc_asyncio"): assert response.permissions == ["permissions_value"] +@pytest.mark.asyncio +async def test_test_iam_permissions_async_from_dict(): + await test_test_iam_permissions_async(request_type=dict) + + def test_test_iam_permissions_field_headers(): client = CloudTasksClient(credentials=credentials.AnonymousCredentials(),) @@ -2516,7 +2612,7 @@ def test_test_iam_permissions_field_headers(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client._transport.test_iam_permissions), "__call__" + type(client.transport.test_iam_permissions), "__call__" ) as call: call.return_value = iam_policy.TestIamPermissionsResponse() @@ -2543,7 +2639,7 @@ async def test_test_iam_permissions_field_headers_async(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client._client._transport.test_iam_permissions), "__call__" + type(client.transport.test_iam_permissions), "__call__" ) as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( iam_policy.TestIamPermissionsResponse() @@ -2561,11 +2657,11 @@ async def test_test_iam_permissions_field_headers_async(): assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] -def test_test_iam_permissions_from_dict(): +def test_test_iam_permissions_from_dict_foreign(): client = CloudTasksClient(credentials=credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client._transport.test_iam_permissions), "__call__" + type(client.transport.test_iam_permissions), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = iam_policy.TestIamPermissionsResponse() @@ -2584,7 +2680,7 @@ def test_test_iam_permissions_flattened(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client._transport.test_iam_permissions), "__call__" + type(client.transport.test_iam_permissions), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = iam_policy.TestIamPermissionsResponse() @@ -2624,7 +2720,7 @@ async def test_test_iam_permissions_flattened_async(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client._client._transport.test_iam_permissions), "__call__" + type(client.transport.test_iam_permissions), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = iam_policy.TestIamPermissionsResponse() @@ -2672,7 +2768,7 @@ def test_list_tasks(transport: str = "grpc", request_type=cloudtasks.ListTasksRe request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client._transport.list_tasks), "__call__") as call: + 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( next_page_token="next_page_token_value", @@ -2687,6 +2783,7 @@ def test_list_tasks(transport: str = "grpc", request_type=cloudtasks.ListTasksRe 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" @@ -2697,19 +2794,19 @@ def test_list_tasks_from_dict(): @pytest.mark.asyncio -async def test_list_tasks_async(transport: str = "grpc_asyncio"): +async def test_list_tasks_async( + transport: str = "grpc_asyncio", request_type=cloudtasks.ListTasksRequest +): client = CloudTasksAsyncClient( credentials=credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, # and we are mocking out the actual API, so just send an empty request. - request = cloudtasks.ListTasksRequest() + request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client._client._transport.list_tasks), "__call__" - ) as call: + with mock.patch.object(type(client.transport.list_tasks), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( cloudtasks.ListTasksResponse(next_page_token="next_page_token_value",) @@ -2721,7 +2818,7 @@ async def test_list_tasks_async(transport: str = "grpc_asyncio"): assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == request + assert args[0] == cloudtasks.ListTasksRequest() # Establish that the response is the type that we expect. assert isinstance(response, pagers.ListTasksAsyncPager) @@ -2729,6 +2826,11 @@ async def test_list_tasks_async(transport: str = "grpc_asyncio"): assert response.next_page_token == "next_page_token_value" +@pytest.mark.asyncio +async def test_list_tasks_async_from_dict(): + await test_list_tasks_async(request_type=dict) + + def test_list_tasks_field_headers(): client = CloudTasksClient(credentials=credentials.AnonymousCredentials(),) @@ -2738,7 +2840,7 @@ def test_list_tasks_field_headers(): 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: + with mock.patch.object(type(client.transport.list_tasks), "__call__") as call: call.return_value = cloudtasks.ListTasksResponse() client.list_tasks(request) @@ -2763,9 +2865,7 @@ async def test_list_tasks_field_headers_async(): request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client._client._transport.list_tasks), "__call__" - ) as call: + with mock.patch.object(type(client.transport.list_tasks), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( cloudtasks.ListTasksResponse() ) @@ -2786,7 +2886,7 @@ def test_list_tasks_flattened(): client = CloudTasksClient(credentials=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: + 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() @@ -2818,9 +2918,7 @@ async def test_list_tasks_flattened_async(): client = CloudTasksAsyncClient(credentials=credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client._client._transport.list_tasks), "__call__" - ) as call: + 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() @@ -2855,7 +2953,7 @@ def test_list_tasks_pager(): client = CloudTasksClient(credentials=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: + with mock.patch.object(type(client.transport.list_tasks), "__call__") as call: # Set the response to a series of pages. call.side_effect = ( cloudtasks.ListTasksResponse( @@ -2884,7 +2982,7 @@ def test_list_tasks_pages(): client = CloudTasksClient(credentials=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: + with mock.patch.object(type(client.transport.list_tasks), "__call__") as call: # Set the response to a series of pages. call.side_effect = ( cloudtasks.ListTasksResponse( @@ -2906,9 +3004,7 @@ async def test_list_tasks_async_pager(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client._client._transport.list_tasks), - "__call__", - new_callable=mock.AsyncMock, + type(client.transport.list_tasks), "__call__", new_callable=mock.AsyncMock ) as call: # Set the response to a series of pages. call.side_effect = ( @@ -2936,9 +3032,7 @@ async def test_list_tasks_async_pages(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client._client._transport.list_tasks), - "__call__", - new_callable=mock.AsyncMock, + type(client.transport.list_tasks), "__call__", new_callable=mock.AsyncMock ) as call: # Set the response to a series of pages. call.side_effect = ( @@ -2967,7 +3061,7 @@ def test_get_task(transport: str = "grpc", request_type=cloudtasks.GetTaskReques request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client._transport.get_task), "__call__") as call: + 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( name="name_value", @@ -2988,6 +3082,7 @@ def test_get_task(transport: str = "grpc", request_type=cloudtasks.GetTaskReques 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" @@ -3004,19 +3099,19 @@ def test_get_task_from_dict(): @pytest.mark.asyncio -async def test_get_task_async(transport: str = "grpc_asyncio"): +async def test_get_task_async( + transport: str = "grpc_asyncio", request_type=cloudtasks.GetTaskRequest +): client = CloudTasksAsyncClient( credentials=credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, # and we are mocking out the actual API, so just send an empty request. - request = cloudtasks.GetTaskRequest() + request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client._client._transport.get_task), "__call__" - ) as call: + with mock.patch.object(type(client.transport.get_task), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( task.Task( @@ -3033,7 +3128,7 @@ async def test_get_task_async(transport: str = "grpc_asyncio"): assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == request + assert args[0] == cloudtasks.GetTaskRequest() # Establish that the response is the type that we expect. assert isinstance(response, task.Task) @@ -3047,6 +3142,11 @@ async def test_get_task_async(transport: str = "grpc_asyncio"): assert response.view == task.Task.View.BASIC +@pytest.mark.asyncio +async def test_get_task_async_from_dict(): + await test_get_task_async(request_type=dict) + + def test_get_task_field_headers(): client = CloudTasksClient(credentials=credentials.AnonymousCredentials(),) @@ -3056,7 +3156,7 @@ def test_get_task_field_headers(): 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: + with mock.patch.object(type(client.transport.get_task), "__call__") as call: call.return_value = task.Task() client.get_task(request) @@ -3081,9 +3181,7 @@ async def test_get_task_field_headers_async(): request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client._client._transport.get_task), "__call__" - ) as call: + 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) @@ -3102,7 +3200,7 @@ def test_get_task_flattened(): client = CloudTasksClient(credentials=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: + 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() @@ -3134,9 +3232,7 @@ async def test_get_task_flattened_async(): client = CloudTasksAsyncClient(credentials=credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client._client._transport.get_task), "__call__" - ) as call: + 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() @@ -3177,7 +3273,7 @@ def test_create_task( request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client._transport.create_task), "__call__") as call: + 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( name="name_value", @@ -3198,6 +3294,7 @@ def test_create_task( 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" @@ -3214,19 +3311,19 @@ def test_create_task_from_dict(): @pytest.mark.asyncio -async def test_create_task_async(transport: str = "grpc_asyncio"): +async def test_create_task_async( + transport: str = "grpc_asyncio", request_type=cloudtasks.CreateTaskRequest +): client = CloudTasksAsyncClient( credentials=credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, # and we are mocking out the actual API, so just send an empty request. - request = cloudtasks.CreateTaskRequest() + request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client._client._transport.create_task), "__call__" - ) as call: + with mock.patch.object(type(client.transport.create_task), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( gct_task.Task( @@ -3243,7 +3340,7 @@ async def test_create_task_async(transport: str = "grpc_asyncio"): assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == request + assert args[0] == cloudtasks.CreateTaskRequest() # Establish that the response is the type that we expect. assert isinstance(response, gct_task.Task) @@ -3257,6 +3354,11 @@ async def test_create_task_async(transport: str = "grpc_asyncio"): assert response.view == gct_task.Task.View.BASIC +@pytest.mark.asyncio +async def test_create_task_async_from_dict(): + await test_create_task_async(request_type=dict) + + def test_create_task_field_headers(): client = CloudTasksClient(credentials=credentials.AnonymousCredentials(),) @@ -3266,7 +3368,7 @@ def test_create_task_field_headers(): 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: + with mock.patch.object(type(client.transport.create_task), "__call__") as call: call.return_value = gct_task.Task() client.create_task(request) @@ -3291,9 +3393,7 @@ async def test_create_task_field_headers_async(): request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client._client._transport.create_task), "__call__" - ) as call: + 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) @@ -3312,7 +3412,7 @@ def test_create_task_flattened(): client = CloudTasksClient(credentials=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: + 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() @@ -3350,9 +3450,7 @@ async def test_create_task_flattened_async(): client = CloudTasksAsyncClient(credentials=credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client._client._transport.create_task), "__call__" - ) as call: + 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() @@ -3399,7 +3497,7 @@ def test_delete_task( request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client._transport.delete_task), "__call__") as call: + with mock.patch.object(type(client.transport.delete_task), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = None @@ -3420,19 +3518,19 @@ def test_delete_task_from_dict(): @pytest.mark.asyncio -async def test_delete_task_async(transport: str = "grpc_asyncio"): +async def test_delete_task_async( + transport: str = "grpc_asyncio", request_type=cloudtasks.DeleteTaskRequest +): client = CloudTasksAsyncClient( credentials=credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, # and we are mocking out the actual API, so just send an empty request. - request = cloudtasks.DeleteTaskRequest() + request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client._client._transport.delete_task), "__call__" - ) as call: + 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) @@ -3442,12 +3540,17 @@ async def test_delete_task_async(transport: str = "grpc_asyncio"): assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == request + assert args[0] == cloudtasks.DeleteTaskRequest() # Establish that the response is the type that we expect. assert response is None +@pytest.mark.asyncio +async def test_delete_task_async_from_dict(): + await test_delete_task_async(request_type=dict) + + def test_delete_task_field_headers(): client = CloudTasksClient(credentials=credentials.AnonymousCredentials(),) @@ -3457,7 +3560,7 @@ def test_delete_task_field_headers(): 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: + with mock.patch.object(type(client.transport.delete_task), "__call__") as call: call.return_value = None client.delete_task(request) @@ -3482,9 +3585,7 @@ async def test_delete_task_field_headers_async(): request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client._client._transport.delete_task), "__call__" - ) as call: + 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) @@ -3503,7 +3604,7 @@ def test_delete_task_flattened(): client = CloudTasksClient(credentials=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: + with mock.patch.object(type(client.transport.delete_task), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = None @@ -3535,9 +3636,7 @@ async def test_delete_task_flattened_async(): client = CloudTasksAsyncClient(credentials=credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client._client._transport.delete_task), "__call__" - ) as call: + with mock.patch.object(type(client.transport.delete_task), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = None @@ -3576,7 +3675,7 @@ def test_run_task(transport: str = "grpc", request_type=cloudtasks.RunTaskReques request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client._transport.run_task), "__call__") as call: + 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( name="name_value", @@ -3597,6 +3696,7 @@ def test_run_task(transport: str = "grpc", request_type=cloudtasks.RunTaskReques 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" @@ -3613,19 +3713,19 @@ def test_run_task_from_dict(): @pytest.mark.asyncio -async def test_run_task_async(transport: str = "grpc_asyncio"): +async def test_run_task_async( + transport: str = "grpc_asyncio", request_type=cloudtasks.RunTaskRequest +): client = CloudTasksAsyncClient( credentials=credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, # and we are mocking out the actual API, so just send an empty request. - request = cloudtasks.RunTaskRequest() + request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client._client._transport.run_task), "__call__" - ) as call: + with mock.patch.object(type(client.transport.run_task), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( task.Task( @@ -3642,7 +3742,7 @@ async def test_run_task_async(transport: str = "grpc_asyncio"): assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == request + assert args[0] == cloudtasks.RunTaskRequest() # Establish that the response is the type that we expect. assert isinstance(response, task.Task) @@ -3656,6 +3756,11 @@ async def test_run_task_async(transport: str = "grpc_asyncio"): assert response.view == task.Task.View.BASIC +@pytest.mark.asyncio +async def test_run_task_async_from_dict(): + await test_run_task_async(request_type=dict) + + def test_run_task_field_headers(): client = CloudTasksClient(credentials=credentials.AnonymousCredentials(),) @@ -3665,7 +3770,7 @@ def test_run_task_field_headers(): 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: + with mock.patch.object(type(client.transport.run_task), "__call__") as call: call.return_value = task.Task() client.run_task(request) @@ -3690,9 +3795,7 @@ async def test_run_task_field_headers_async(): request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client._client._transport.run_task), "__call__" - ) as call: + 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) @@ -3711,7 +3814,7 @@ def test_run_task_flattened(): client = CloudTasksClient(credentials=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: + 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() @@ -3743,9 +3846,7 @@ async def test_run_task_flattened_async(): client = CloudTasksAsyncClient(credentials=credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client._client._transport.run_task), "__call__" - ) as call: + 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() @@ -3810,7 +3911,7 @@ def test_transport_instance(): credentials=credentials.AnonymousCredentials(), ) client = CloudTasksClient(transport=transport) - assert client._transport is transport + assert client.transport is transport def test_transport_get_channel(): @@ -3828,10 +3929,22 @@ def test_transport_get_channel(): assert channel +@pytest.mark.parametrize( + "transport_class", + [transports.CloudTasksGrpcTransport, transports.CloudTasksGrpcAsyncIOTransport], +) +def test_transport_adc(transport_class): + # Test default credentials are used if not provided. + with mock.patch.object(auth, "default") as adc: + adc.return_value = (credentials.AnonymousCredentials(), None) + transport_class() + adc.assert_called_once() + + def test_transport_grpc_default(): # A client should use the gRPC transport by default. client = CloudTasksClient(credentials=credentials.AnonymousCredentials(),) - assert isinstance(client._transport, transports.CloudTasksGrpcTransport,) + assert isinstance(client.transport, transports.CloudTasksGrpcTransport,) def test_cloud_tasks_base_transport_error(): @@ -3897,6 +4010,17 @@ 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( + "google.cloud.tasks_v2.services.cloud_tasks.transports.CloudTasksTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + adc.return_value = (credentials.AnonymousCredentials(), None) + transport = transports.CloudTasksTransport() + adc.assert_called_once() + + def test_cloud_tasks_auth_adc(): # If no credentials are provided, we should use ADC credentials. with mock.patch.object(auth, "default") as adc: @@ -3929,7 +4053,7 @@ def test_cloud_tasks_host_no_port(): api_endpoint="cloudtasks.googleapis.com" ), ) - assert client._transport._host == "cloudtasks.googleapis.com:443" + assert client.transport._host == "cloudtasks.googleapis.com:443" def test_cloud_tasks_host_with_port(): @@ -3939,185 +4063,111 @@ def test_cloud_tasks_host_with_port(): api_endpoint="cloudtasks.googleapis.com:8000" ), ) - assert client._transport._host == "cloudtasks.googleapis.com:8000" + assert client.transport._host == "cloudtasks.googleapis.com:8000" def test_cloud_tasks_grpc_transport_channel(): channel = grpc.insecure_channel("http://localhost/") - # Check that if channel is provided, mtls endpoint and client_cert_source - # won't be used. - callback = mock.MagicMock() + # Check that channel is used if provided. transport = transports.CloudTasksGrpcTransport( - host="squid.clam.whelk", - channel=channel, - api_mtls_endpoint="mtls.squid.clam.whelk", - client_cert_source=callback, + host="squid.clam.whelk", channel=channel, ) assert transport.grpc_channel == channel assert transport._host == "squid.clam.whelk:443" - assert not callback.called + assert transport._ssl_channel_credentials == None def test_cloud_tasks_grpc_asyncio_transport_channel(): channel = aio.insecure_channel("http://localhost/") - # Check that if channel is provided, mtls endpoint and client_cert_source - # won't be used. - callback = mock.MagicMock() + # Check that channel is used if provided. transport = transports.CloudTasksGrpcAsyncIOTransport( - host="squid.clam.whelk", - channel=channel, - api_mtls_endpoint="mtls.squid.clam.whelk", - client_cert_source=callback, + host="squid.clam.whelk", channel=channel, ) assert transport.grpc_channel == channel assert transport._host == "squid.clam.whelk:443" - assert not callback.called - - -@mock.patch("grpc.ssl_channel_credentials", autospec=True) -@mock.patch("google.api_core.grpc_helpers.create_channel", autospec=True) -def test_cloud_tasks_grpc_transport_channel_mtls_with_client_cert_source( - grpc_create_channel, grpc_ssl_channel_cred -): - # Check that if channel is None, but api_mtls_endpoint and client_cert_source - # are provided, then a mTLS channel will be created. - mock_cred = mock.Mock() - - mock_ssl_cred = mock.Mock() - grpc_ssl_channel_cred.return_value = mock_ssl_cred - - mock_grpc_channel = mock.Mock() - grpc_create_channel.return_value = mock_grpc_channel - - transport = transports.CloudTasksGrpcTransport( - host="squid.clam.whelk", - credentials=mock_cred, - api_mtls_endpoint="mtls.squid.clam.whelk", - client_cert_source=client_cert_source_callback, - ) - grpc_ssl_channel_cred.assert_called_once_with( - certificate_chain=b"cert bytes", private_key=b"key bytes" - ) - grpc_create_channel.assert_called_once_with( - "mtls.squid.clam.whelk:443", - credentials=mock_cred, - credentials_file=None, - scopes=("https://www.googleapis.com/auth/cloud-platform",), - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - ) - assert transport.grpc_channel == mock_grpc_channel - - -@mock.patch("grpc.ssl_channel_credentials", autospec=True) -@mock.patch("google.api_core.grpc_helpers_async.create_channel", autospec=True) -def test_cloud_tasks_grpc_asyncio_transport_channel_mtls_with_client_cert_source( - grpc_create_channel, grpc_ssl_channel_cred -): - # Check that if channel is None, but api_mtls_endpoint and client_cert_source - # are provided, then a mTLS channel will be created. - mock_cred = mock.Mock() - - mock_ssl_cred = mock.Mock() - grpc_ssl_channel_cred.return_value = mock_ssl_cred - - mock_grpc_channel = mock.Mock() - grpc_create_channel.return_value = mock_grpc_channel - - transport = transports.CloudTasksGrpcAsyncIOTransport( - host="squid.clam.whelk", - credentials=mock_cred, - api_mtls_endpoint="mtls.squid.clam.whelk", - client_cert_source=client_cert_source_callback, - ) - grpc_ssl_channel_cred.assert_called_once_with( - certificate_chain=b"cert bytes", private_key=b"key bytes" - ) - grpc_create_channel.assert_called_once_with( - "mtls.squid.clam.whelk:443", - credentials=mock_cred, - credentials_file=None, - scopes=("https://www.googleapis.com/auth/cloud-platform",), - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - ) - assert transport.grpc_channel == mock_grpc_channel + assert transport._ssl_channel_credentials == None @pytest.mark.parametrize( - "api_mtls_endpoint", ["mtls.squid.clam.whelk", "mtls.squid.clam.whelk:443"] + "transport_class", + [transports.CloudTasksGrpcTransport, transports.CloudTasksGrpcAsyncIOTransport], ) -@mock.patch("google.api_core.grpc_helpers.create_channel", autospec=True) -def test_cloud_tasks_grpc_transport_channel_mtls_with_adc( - grpc_create_channel, api_mtls_endpoint -): - # Check that if channel and client_cert_source are None, but api_mtls_endpoint - # is provided, then a mTLS channel will be created with SSL ADC. - mock_grpc_channel = mock.Mock() - grpc_create_channel.return_value = mock_grpc_channel - - # Mock google.auth.transport.grpc.SslCredentials class. - mock_ssl_cred = mock.Mock() - with mock.patch.multiple( - "google.auth.transport.grpc.SslCredentials", - __init__=mock.Mock(return_value=None), - ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), - ): - mock_cred = mock.Mock() - transport = transports.CloudTasksGrpcTransport( - host="squid.clam.whelk", - credentials=mock_cred, - api_mtls_endpoint=api_mtls_endpoint, - client_cert_source=None, - ) - grpc_create_channel.assert_called_once_with( - "mtls.squid.clam.whelk:443", - credentials=mock_cred, - credentials_file=None, - scopes=("https://www.googleapis.com/auth/cloud-platform",), - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - ) - assert transport.grpc_channel == mock_grpc_channel +def test_cloud_tasks_transport_channel_mtls_with_client_cert_source(transport_class): + with mock.patch( + "grpc.ssl_channel_credentials", autospec=True + ) as grpc_ssl_channel_cred: + with mock.patch.object( + transport_class, "create_channel", autospec=True + ) as grpc_create_channel: + mock_ssl_cred = mock.Mock() + grpc_ssl_channel_cred.return_value = mock_ssl_cred + + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + + cred = credentials.AnonymousCredentials() + with pytest.warns(DeprecationWarning): + with mock.patch.object(auth, "default") as adc: + adc.return_value = (cred, None) + transport = transport_class( + host="squid.clam.whelk", + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=client_cert_source_callback, + ) + adc.assert_called_once() + + grpc_ssl_channel_cred.assert_called_once_with( + certificate_chain=b"cert bytes", private_key=b"key bytes" + ) + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=("https://www.googleapis.com/auth/cloud-platform",), + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + ) + assert transport.grpc_channel == mock_grpc_channel + assert transport._ssl_channel_credentials == mock_ssl_cred @pytest.mark.parametrize( - "api_mtls_endpoint", ["mtls.squid.clam.whelk", "mtls.squid.clam.whelk:443"] + "transport_class", + [transports.CloudTasksGrpcTransport, transports.CloudTasksGrpcAsyncIOTransport], ) -@mock.patch("google.api_core.grpc_helpers_async.create_channel", autospec=True) -def test_cloud_tasks_grpc_asyncio_transport_channel_mtls_with_adc( - grpc_create_channel, api_mtls_endpoint -): - # Check that if channel and client_cert_source are None, but api_mtls_endpoint - # is provided, then a mTLS channel will be created with SSL ADC. - mock_grpc_channel = mock.Mock() - grpc_create_channel.return_value = mock_grpc_channel - - # Mock google.auth.transport.grpc.SslCredentials class. +def test_cloud_tasks_transport_channel_mtls_with_adc(transport_class): mock_ssl_cred = mock.Mock() with mock.patch.multiple( "google.auth.transport.grpc.SslCredentials", __init__=mock.Mock(return_value=None), ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), ): - mock_cred = mock.Mock() - transport = transports.CloudTasksGrpcAsyncIOTransport( - host="squid.clam.whelk", - credentials=mock_cred, - api_mtls_endpoint=api_mtls_endpoint, - client_cert_source=None, - ) - grpc_create_channel.assert_called_once_with( - "mtls.squid.clam.whelk:443", - credentials=mock_cred, - credentials_file=None, - scopes=("https://www.googleapis.com/auth/cloud-platform",), - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - ) - assert transport.grpc_channel == mock_grpc_channel + with mock.patch.object( + transport_class, "create_channel", autospec=True + ) as grpc_create_channel: + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + mock_cred = mock.Mock() + + with pytest.warns(DeprecationWarning): + transport = transport_class( + host="squid.clam.whelk", + credentials=mock_cred, + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=None, + ) + + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=mock_cred, + credentials_file=None, + scopes=("https://www.googleapis.com/auth/cloud-platform",), + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + ) + assert transport.grpc_channel == mock_grpc_channel def test_queue_path(): @@ -4146,10 +4196,10 @@ def test_parse_queue_path(): def test_task_path(): - project = "squid" - location = "clam" - queue = "whelk" - task = "octopus" + project = "cuttlefish" + location = "mussel" + queue = "winkle" + task = "nautilus" expected = "projects/{project}/locations/{location}/queues/{queue}/tasks/{task}".format( project=project, location=location, queue=queue, task=task, @@ -4160,10 +4210,10 @@ def test_task_path(): def test_parse_task_path(): expected = { - "project": "oyster", - "location": "nudibranch", - "queue": "cuttlefish", - "task": "mussel", + "project": "scallop", + "location": "abalone", + "queue": "squid", + "task": "clam", } path = CloudTasksClient.task_path(**expected) @@ -4172,6 +4222,107 @@ def test_parse_task_path(): assert expected == actual +def test_common_billing_account_path(): + billing_account = "whelk" + + expected = "billingAccounts/{billing_account}".format( + billing_account=billing_account, + ) + actual = CloudTasksClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "octopus", + } + path = CloudTasksClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = CloudTasksClient.parse_common_billing_account_path(path) + assert expected == actual + + +def test_common_folder_path(): + folder = "oyster" + + expected = "folders/{folder}".format(folder=folder,) + actual = CloudTasksClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "nudibranch", + } + path = CloudTasksClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = CloudTasksClient.parse_common_folder_path(path) + assert expected == actual + + +def test_common_organization_path(): + organization = "cuttlefish" + + expected = "organizations/{organization}".format(organization=organization,) + actual = CloudTasksClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "mussel", + } + path = CloudTasksClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = CloudTasksClient.parse_common_organization_path(path) + assert expected == actual + + +def test_common_project_path(): + project = "winkle" + + expected = "projects/{project}".format(project=project,) + actual = CloudTasksClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "nautilus", + } + path = CloudTasksClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = CloudTasksClient.parse_common_project_path(path) + assert expected == actual + + +def test_common_location_path(): + project = "scallop" + location = "abalone" + + expected = "projects/{project}/locations/{location}".format( + project=project, location=location, + ) + actual = CloudTasksClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "squid", + "location": "clam", + } + path = CloudTasksClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = CloudTasksClient.parse_common_location_path(path) + assert expected == actual + + def test_client_withDEFAULT_CLIENT_INFO(): client_info = gapic_v1.client_info.ClientInfo() diff --git a/tests/unit/gapic/tasks_v2beta2/test_cloud_tasks.py b/tests/unit/gapic/tasks_v2beta2/test_cloud_tasks.py index ec78a0d1..f2825d18 100644 --- a/tests/unit/gapic/tasks_v2beta2/test_cloud_tasks.py +++ b/tests/unit/gapic/tasks_v2beta2/test_cloud_tasks.py @@ -46,7 +46,7 @@ from google.iam.v1 import options_pb2 as options # type: ignore from google.iam.v1 import policy_pb2 as policy # type: ignore from google.oauth2 import service_account -from google.protobuf import any_pb2 as any # type: ignore +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 @@ -103,12 +103,12 @@ def test_cloud_tasks_client_from_service_account_file(client_class): ) as factory: factory.return_value = creds client = client_class.from_service_account_file("dummy/file/path.json") - assert client._transport._credentials == creds + assert client.transport._credentials == creds client = client_class.from_service_account_json("dummy/file/path.json") - assert client._transport._credentials == creds + assert client.transport._credentials == creds - assert client._transport._host == "cloudtasks.googleapis.com:443" + assert client.transport._host == "cloudtasks.googleapis.com:443" def test_cloud_tasks_client_get_transport_class(): @@ -162,15 +162,14 @@ def test_cloud_tasks_client_client_options( credentials_file=None, host="squid.clam.whelk", scopes=None, - api_mtls_endpoint="squid.clam.whelk", - client_cert_source=None, + ssl_channel_credentials=None, quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, ) - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS is + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is # "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS": "never"}): + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): with mock.patch.object(transport_class, "__init__") as patched: patched.return_value = None client = client_class() @@ -179,15 +178,14 @@ def test_cloud_tasks_client_client_options( credentials_file=None, host=client.DEFAULT_ENDPOINT, scopes=None, - api_mtls_endpoint=client.DEFAULT_ENDPOINT, - client_cert_source=None, + ssl_channel_credentials=None, quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, ) - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS is + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is # "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS": "always"}): + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): with mock.patch.object(transport_class, "__init__") as patched: patched.return_value = None client = client_class() @@ -196,95 +194,173 @@ def test_cloud_tasks_client_client_options( credentials_file=None, host=client.DEFAULT_MTLS_ENDPOINT, scopes=None, - api_mtls_endpoint=client.DEFAULT_MTLS_ENDPOINT, - client_cert_source=None, + ssl_channel_credentials=None, quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, ) - # Check the case api_endpoint is not provided, GOOGLE_API_USE_MTLS is - # "auto", and client_cert_source is provided. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS": "auto"}): + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError): + client = client_class() + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"} + ): + with pytest.raises(ValueError): + client = client_class() + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + ssl_channel_credentials=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name,use_client_cert_env", + [ + (CloudTasksClient, transports.CloudTasksGrpcTransport, "grpc", "true"), + ( + CloudTasksAsyncClient, + transports.CloudTasksGrpcAsyncIOTransport, + "grpc_asyncio", + "true", + ), + (CloudTasksClient, transports.CloudTasksGrpcTransport, "grpc", "false"), + ( + CloudTasksAsyncClient, + transports.CloudTasksGrpcAsyncIOTransport, + "grpc_asyncio", + "false", + ), + ], +) +@mock.patch.object( + CloudTasksClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CloudTasksClient) +) +@mock.patch.object( + CloudTasksAsyncClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(CloudTasksAsyncClient), +) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_cloud_tasks_client_mtls_env_auto( + client_class, transport_class, transport_name, use_client_cert_env +): + # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default + # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. + + # Check the case client_cert_source is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} + ): options = client_options.ClientOptions( client_cert_source=client_cert_source_callback ) with mock.patch.object(transport_class, "__init__") as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_MTLS_ENDPOINT, - scopes=None, - api_mtls_endpoint=client.DEFAULT_MTLS_ENDPOINT, - client_cert_source=client_cert_source_callback, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - - # Check the case api_endpoint is not provided, GOOGLE_API_USE_MTLS is - # "auto", and default_client_cert_source is provided. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS": "auto"}): - with mock.patch.object(transport_class, "__init__") as patched: + ssl_channel_creds = mock.Mock() with mock.patch( - "google.auth.transport.mtls.has_default_client_cert_source", - return_value=True, + "grpc.ssl_channel_credentials", return_value=ssl_channel_creds ): patched.return_value = None - client = client_class() + client = client_class(client_options=options) + + if use_client_cert_env == "false": + expected_ssl_channel_creds = None + expected_host = client.DEFAULT_ENDPOINT + else: + expected_ssl_channel_creds = ssl_channel_creds + expected_host = client.DEFAULT_MTLS_ENDPOINT + patched.assert_called_once_with( credentials=None, credentials_file=None, - host=client.DEFAULT_MTLS_ENDPOINT, + host=expected_host, scopes=None, - api_mtls_endpoint=client.DEFAULT_MTLS_ENDPOINT, - client_cert_source=None, + ssl_channel_credentials=expected_ssl_channel_creds, quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, ) - # Check the case api_endpoint is not provided, GOOGLE_API_USE_MTLS is - # "auto", but client_cert_source and default_client_cert_source are None. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS": "auto"}): + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} + ): with mock.patch.object(transport_class, "__init__") as patched: with mock.patch( - "google.auth.transport.mtls.has_default_client_cert_source", - return_value=False, + "google.auth.transport.grpc.SslCredentials.__init__", return_value=None ): - patched.return_value = None - client = client_class() - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - api_mtls_endpoint=client.DEFAULT_ENDPOINT, - client_cert_source=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS has - # unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS": "Unsupported"}): - with pytest.raises(MutualTLSChannelError): - client = client_class() - - # Check the case quota_project_id is provided - options = client_options.ClientOptions(quota_project_id="octopus") - with mock.patch.object(transport_class, "__init__") as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - api_mtls_endpoint=client.DEFAULT_ENDPOINT, - client_cert_source=None, - quota_project_id="octopus", - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) + with mock.patch( + "google.auth.transport.grpc.SslCredentials.is_mtls", + new_callable=mock.PropertyMock, + ) as is_mtls_mock: + with mock.patch( + "google.auth.transport.grpc.SslCredentials.ssl_credentials", + new_callable=mock.PropertyMock, + ) as ssl_credentials_mock: + if use_client_cert_env == "false": + is_mtls_mock.return_value = False + ssl_credentials_mock.return_value = None + expected_host = client.DEFAULT_ENDPOINT + expected_ssl_channel_creds = None + else: + is_mtls_mock.return_value = True + ssl_credentials_mock.return_value = mock.Mock() + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_ssl_channel_creds = ( + ssl_credentials_mock.return_value + ) + + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + ssl_channel_credentials=expected_ssl_channel_creds, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} + ): + with mock.patch.object(transport_class, "__init__") as patched: + with mock.patch( + "google.auth.transport.grpc.SslCredentials.__init__", return_value=None + ): + with mock.patch( + "google.auth.transport.grpc.SslCredentials.is_mtls", + new_callable=mock.PropertyMock, + ) as is_mtls_mock: + is_mtls_mock.return_value = False + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + ssl_channel_credentials=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) @pytest.mark.parametrize( @@ -311,8 +387,7 @@ def test_cloud_tasks_client_client_options_scopes( credentials_file=None, host=client.DEFAULT_ENDPOINT, scopes=["1", "2"], - api_mtls_endpoint=client.DEFAULT_ENDPOINT, - client_cert_source=None, + ssl_channel_credentials=None, quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, ) @@ -342,8 +417,7 @@ def test_cloud_tasks_client_client_options_credentials_file( credentials_file="credentials.json", host=client.DEFAULT_ENDPOINT, scopes=None, - api_mtls_endpoint=client.DEFAULT_ENDPOINT, - client_cert_source=None, + ssl_channel_credentials=None, quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, ) @@ -360,8 +434,7 @@ def test_cloud_tasks_client_client_options_from_dict(): credentials_file=None, host="squid.clam.whelk", scopes=None, - api_mtls_endpoint="squid.clam.whelk", - client_cert_source=None, + ssl_channel_credentials=None, quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, ) @@ -379,7 +452,7 @@ def test_list_queues( request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client._transport.list_queues), "__call__") as call: + 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( next_page_token="next_page_token_value", @@ -394,6 +467,7 @@ def test_list_queues( 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" @@ -404,19 +478,19 @@ def test_list_queues_from_dict(): @pytest.mark.asyncio -async def test_list_queues_async(transport: str = "grpc_asyncio"): +async def test_list_queues_async( + transport: str = "grpc_asyncio", request_type=cloudtasks.ListQueuesRequest +): client = CloudTasksAsyncClient( credentials=credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, # and we are mocking out the actual API, so just send an empty request. - request = cloudtasks.ListQueuesRequest() + request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client._client._transport.list_queues), "__call__" - ) as call: + with mock.patch.object(type(client.transport.list_queues), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( cloudtasks.ListQueuesResponse(next_page_token="next_page_token_value",) @@ -428,7 +502,7 @@ async def test_list_queues_async(transport: str = "grpc_asyncio"): assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == request + assert args[0] == cloudtasks.ListQueuesRequest() # Establish that the response is the type that we expect. assert isinstance(response, pagers.ListQueuesAsyncPager) @@ -436,6 +510,11 @@ async def test_list_queues_async(transport: str = "grpc_asyncio"): assert response.next_page_token == "next_page_token_value" +@pytest.mark.asyncio +async def test_list_queues_async_from_dict(): + await test_list_queues_async(request_type=dict) + + def test_list_queues_field_headers(): client = CloudTasksClient(credentials=credentials.AnonymousCredentials(),) @@ -445,7 +524,7 @@ def test_list_queues_field_headers(): 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: + with mock.patch.object(type(client.transport.list_queues), "__call__") as call: call.return_value = cloudtasks.ListQueuesResponse() client.list_queues(request) @@ -470,9 +549,7 @@ async def test_list_queues_field_headers_async(): request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client._client._transport.list_queues), "__call__" - ) as call: + with mock.patch.object(type(client.transport.list_queues), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( cloudtasks.ListQueuesResponse() ) @@ -493,7 +570,7 @@ def test_list_queues_flattened(): client = CloudTasksClient(credentials=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: + 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() @@ -525,9 +602,7 @@ async def test_list_queues_flattened_async(): client = CloudTasksAsyncClient(credentials=credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client._client._transport.list_queues), "__call__" - ) as call: + 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() @@ -562,7 +637,7 @@ def test_list_queues_pager(): client = CloudTasksClient(credentials=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: + with mock.patch.object(type(client.transport.list_queues), "__call__") as call: # Set the response to a series of pages. call.side_effect = ( cloudtasks.ListQueuesResponse( @@ -594,7 +669,7 @@ def test_list_queues_pages(): client = CloudTasksClient(credentials=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: + with mock.patch.object(type(client.transport.list_queues), "__call__") as call: # Set the response to a series of pages. call.side_effect = ( cloudtasks.ListQueuesResponse( @@ -619,9 +694,7 @@ async def test_list_queues_async_pager(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client._client._transport.list_queues), - "__call__", - new_callable=mock.AsyncMock, + type(client.transport.list_queues), "__call__", new_callable=mock.AsyncMock ) as call: # Set the response to a series of pages. call.side_effect = ( @@ -652,9 +725,7 @@ async def test_list_queues_async_pages(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client._client._transport.list_queues), - "__call__", - new_callable=mock.AsyncMock, + type(client.transport.list_queues), "__call__", new_callable=mock.AsyncMock ) as call: # Set the response to a series of pages. call.side_effect = ( @@ -686,7 +757,7 @@ def test_get_queue(transport: str = "grpc", request_type=cloudtasks.GetQueueRequ request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client._transport.get_queue), "__call__") as call: + 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( name="name_value", @@ -707,6 +778,7 @@ def test_get_queue(transport: str = "grpc", request_type=cloudtasks.GetQueueRequ 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" @@ -719,19 +791,19 @@ def test_get_queue_from_dict(): @pytest.mark.asyncio -async def test_get_queue_async(transport: str = "grpc_asyncio"): +async def test_get_queue_async( + transport: str = "grpc_asyncio", request_type=cloudtasks.GetQueueRequest +): client = CloudTasksAsyncClient( credentials=credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, # and we are mocking out the actual API, so just send an empty request. - request = cloudtasks.GetQueueRequest() + request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client._client._transport.get_queue), "__call__" - ) as call: + with mock.patch.object(type(client.transport.get_queue), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( queue.Queue(name="name_value", state=queue.Queue.State.RUNNING,) @@ -743,7 +815,7 @@ async def test_get_queue_async(transport: str = "grpc_asyncio"): assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == request + assert args[0] == cloudtasks.GetQueueRequest() # Establish that the response is the type that we expect. assert isinstance(response, queue.Queue) @@ -753,6 +825,11 @@ async def test_get_queue_async(transport: str = "grpc_asyncio"): assert response.state == queue.Queue.State.RUNNING +@pytest.mark.asyncio +async def test_get_queue_async_from_dict(): + await test_get_queue_async(request_type=dict) + + def test_get_queue_field_headers(): client = CloudTasksClient(credentials=credentials.AnonymousCredentials(),) @@ -762,7 +839,7 @@ def test_get_queue_field_headers(): 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: + with mock.patch.object(type(client.transport.get_queue), "__call__") as call: call.return_value = queue.Queue() client.get_queue(request) @@ -787,9 +864,7 @@ async def test_get_queue_field_headers_async(): request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client._client._transport.get_queue), "__call__" - ) as call: + 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) @@ -808,7 +883,7 @@ def test_get_queue_flattened(): client = CloudTasksClient(credentials=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: + 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() @@ -840,9 +915,7 @@ async def test_get_queue_flattened_async(): client = CloudTasksAsyncClient(credentials=credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client._client._transport.get_queue), "__call__" - ) as call: + 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() @@ -883,7 +956,7 @@ def test_create_queue( request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client._transport.create_queue), "__call__") as call: + 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( name="name_value", @@ -904,6 +977,7 @@ def test_create_queue( 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" @@ -916,19 +990,19 @@ def test_create_queue_from_dict(): @pytest.mark.asyncio -async def test_create_queue_async(transport: str = "grpc_asyncio"): +async def test_create_queue_async( + transport: str = "grpc_asyncio", request_type=cloudtasks.CreateQueueRequest +): client = CloudTasksAsyncClient( credentials=credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, # and we are mocking out the actual API, so just send an empty request. - request = cloudtasks.CreateQueueRequest() + request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client._client._transport.create_queue), "__call__" - ) as call: + with mock.patch.object(type(client.transport.create_queue), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( gct_queue.Queue(name="name_value", state=gct_queue.Queue.State.RUNNING,) @@ -940,7 +1014,7 @@ async def test_create_queue_async(transport: str = "grpc_asyncio"): assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == request + assert args[0] == cloudtasks.CreateQueueRequest() # Establish that the response is the type that we expect. assert isinstance(response, gct_queue.Queue) @@ -950,6 +1024,11 @@ async def test_create_queue_async(transport: str = "grpc_asyncio"): assert response.state == gct_queue.Queue.State.RUNNING +@pytest.mark.asyncio +async def test_create_queue_async_from_dict(): + await test_create_queue_async(request_type=dict) + + def test_create_queue_field_headers(): client = CloudTasksClient(credentials=credentials.AnonymousCredentials(),) @@ -959,7 +1038,7 @@ def test_create_queue_field_headers(): 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: + with mock.patch.object(type(client.transport.create_queue), "__call__") as call: call.return_value = gct_queue.Queue() client.create_queue(request) @@ -984,9 +1063,7 @@ async def test_create_queue_field_headers_async(): request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client._client._transport.create_queue), "__call__" - ) as call: + 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) @@ -1005,7 +1082,7 @@ def test_create_queue_flattened(): client = CloudTasksClient(credentials=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: + 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() @@ -1043,9 +1120,7 @@ async def test_create_queue_flattened_async(): client = CloudTasksAsyncClient(credentials=credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client._client._transport.create_queue), "__call__" - ) as call: + 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() @@ -1092,7 +1167,7 @@ def test_update_queue( request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client._transport.update_queue), "__call__") as call: + 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( name="name_value", @@ -1113,6 +1188,7 @@ def test_update_queue( 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" @@ -1125,19 +1201,19 @@ def test_update_queue_from_dict(): @pytest.mark.asyncio -async def test_update_queue_async(transport: str = "grpc_asyncio"): +async def test_update_queue_async( + transport: str = "grpc_asyncio", request_type=cloudtasks.UpdateQueueRequest +): client = CloudTasksAsyncClient( credentials=credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, # and we are mocking out the actual API, so just send an empty request. - request = cloudtasks.UpdateQueueRequest() + request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client._client._transport.update_queue), "__call__" - ) as call: + with mock.patch.object(type(client.transport.update_queue), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( gct_queue.Queue(name="name_value", state=gct_queue.Queue.State.RUNNING,) @@ -1149,7 +1225,7 @@ async def test_update_queue_async(transport: str = "grpc_asyncio"): assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == request + assert args[0] == cloudtasks.UpdateQueueRequest() # Establish that the response is the type that we expect. assert isinstance(response, gct_queue.Queue) @@ -1159,6 +1235,11 @@ async def test_update_queue_async(transport: str = "grpc_asyncio"): assert response.state == gct_queue.Queue.State.RUNNING +@pytest.mark.asyncio +async def test_update_queue_async_from_dict(): + await test_update_queue_async(request_type=dict) + + def test_update_queue_field_headers(): client = CloudTasksClient(credentials=credentials.AnonymousCredentials(),) @@ -1168,7 +1249,7 @@ def test_update_queue_field_headers(): 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: + with mock.patch.object(type(client.transport.update_queue), "__call__") as call: call.return_value = gct_queue.Queue() client.update_queue(request) @@ -1193,9 +1274,7 @@ async def test_update_queue_field_headers_async(): request.queue.name = "queue.name/value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client._client._transport.update_queue), "__call__" - ) as call: + 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) @@ -1214,7 +1293,7 @@ def test_update_queue_flattened(): client = CloudTasksClient(credentials=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: + 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() @@ -1253,9 +1332,7 @@ async def test_update_queue_flattened_async(): client = CloudTasksAsyncClient(credentials=credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client._client._transport.update_queue), "__call__" - ) as call: + 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() @@ -1303,7 +1380,7 @@ def test_delete_queue( request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client._transport.delete_queue), "__call__") as call: + with mock.patch.object(type(client.transport.delete_queue), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = None @@ -1324,19 +1401,19 @@ def test_delete_queue_from_dict(): @pytest.mark.asyncio -async def test_delete_queue_async(transport: str = "grpc_asyncio"): +async def test_delete_queue_async( + transport: str = "grpc_asyncio", request_type=cloudtasks.DeleteQueueRequest +): client = CloudTasksAsyncClient( credentials=credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, # and we are mocking out the actual API, so just send an empty request. - request = cloudtasks.DeleteQueueRequest() + request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client._client._transport.delete_queue), "__call__" - ) as call: + 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) @@ -1346,12 +1423,17 @@ async def test_delete_queue_async(transport: str = "grpc_asyncio"): assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == request + assert args[0] == cloudtasks.DeleteQueueRequest() # Establish that the response is the type that we expect. assert response is None +@pytest.mark.asyncio +async def test_delete_queue_async_from_dict(): + await test_delete_queue_async(request_type=dict) + + def test_delete_queue_field_headers(): client = CloudTasksClient(credentials=credentials.AnonymousCredentials(),) @@ -1361,7 +1443,7 @@ def test_delete_queue_field_headers(): 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: + with mock.patch.object(type(client.transport.delete_queue), "__call__") as call: call.return_value = None client.delete_queue(request) @@ -1386,9 +1468,7 @@ async def test_delete_queue_field_headers_async(): request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client._client._transport.delete_queue), "__call__" - ) as call: + 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) @@ -1407,7 +1487,7 @@ def test_delete_queue_flattened(): client = CloudTasksClient(credentials=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: + with mock.patch.object(type(client.transport.delete_queue), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = None @@ -1439,9 +1519,7 @@ async def test_delete_queue_flattened_async(): client = CloudTasksAsyncClient(credentials=credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client._client._transport.delete_queue), "__call__" - ) as call: + with mock.patch.object(type(client.transport.delete_queue), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = None @@ -1482,7 +1560,7 @@ def test_purge_queue( request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client._transport.purge_queue), "__call__") as call: + 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( name="name_value", @@ -1503,6 +1581,7 @@ def test_purge_queue( 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" @@ -1515,19 +1594,19 @@ def test_purge_queue_from_dict(): @pytest.mark.asyncio -async def test_purge_queue_async(transport: str = "grpc_asyncio"): +async def test_purge_queue_async( + transport: str = "grpc_asyncio", request_type=cloudtasks.PurgeQueueRequest +): client = CloudTasksAsyncClient( credentials=credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, # and we are mocking out the actual API, so just send an empty request. - request = cloudtasks.PurgeQueueRequest() + request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client._client._transport.purge_queue), "__call__" - ) as call: + with mock.patch.object(type(client.transport.purge_queue), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( queue.Queue(name="name_value", state=queue.Queue.State.RUNNING,) @@ -1539,7 +1618,7 @@ async def test_purge_queue_async(transport: str = "grpc_asyncio"): assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == request + assert args[0] == cloudtasks.PurgeQueueRequest() # Establish that the response is the type that we expect. assert isinstance(response, queue.Queue) @@ -1549,6 +1628,11 @@ async def test_purge_queue_async(transport: str = "grpc_asyncio"): assert response.state == queue.Queue.State.RUNNING +@pytest.mark.asyncio +async def test_purge_queue_async_from_dict(): + await test_purge_queue_async(request_type=dict) + + def test_purge_queue_field_headers(): client = CloudTasksClient(credentials=credentials.AnonymousCredentials(),) @@ -1558,7 +1642,7 @@ def test_purge_queue_field_headers(): 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: + with mock.patch.object(type(client.transport.purge_queue), "__call__") as call: call.return_value = queue.Queue() client.purge_queue(request) @@ -1583,9 +1667,7 @@ async def test_purge_queue_field_headers_async(): request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client._client._transport.purge_queue), "__call__" - ) as call: + 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) @@ -1604,7 +1686,7 @@ def test_purge_queue_flattened(): client = CloudTasksClient(credentials=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: + 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() @@ -1636,9 +1718,7 @@ async def test_purge_queue_flattened_async(): client = CloudTasksAsyncClient(credentials=credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client._client._transport.purge_queue), "__call__" - ) as call: + 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() @@ -1679,7 +1759,7 @@ def test_pause_queue( request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client._transport.pause_queue), "__call__") as call: + 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( name="name_value", @@ -1700,6 +1780,7 @@ def test_pause_queue( 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" @@ -1712,19 +1793,19 @@ def test_pause_queue_from_dict(): @pytest.mark.asyncio -async def test_pause_queue_async(transport: str = "grpc_asyncio"): +async def test_pause_queue_async( + transport: str = "grpc_asyncio", request_type=cloudtasks.PauseQueueRequest +): client = CloudTasksAsyncClient( credentials=credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, # and we are mocking out the actual API, so just send an empty request. - request = cloudtasks.PauseQueueRequest() + request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client._client._transport.pause_queue), "__call__" - ) as call: + with mock.patch.object(type(client.transport.pause_queue), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( queue.Queue(name="name_value", state=queue.Queue.State.RUNNING,) @@ -1736,7 +1817,7 @@ async def test_pause_queue_async(transport: str = "grpc_asyncio"): assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == request + assert args[0] == cloudtasks.PauseQueueRequest() # Establish that the response is the type that we expect. assert isinstance(response, queue.Queue) @@ -1746,6 +1827,11 @@ async def test_pause_queue_async(transport: str = "grpc_asyncio"): assert response.state == queue.Queue.State.RUNNING +@pytest.mark.asyncio +async def test_pause_queue_async_from_dict(): + await test_pause_queue_async(request_type=dict) + + def test_pause_queue_field_headers(): client = CloudTasksClient(credentials=credentials.AnonymousCredentials(),) @@ -1755,7 +1841,7 @@ def test_pause_queue_field_headers(): 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: + with mock.patch.object(type(client.transport.pause_queue), "__call__") as call: call.return_value = queue.Queue() client.pause_queue(request) @@ -1780,9 +1866,7 @@ async def test_pause_queue_field_headers_async(): request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client._client._transport.pause_queue), "__call__" - ) as call: + 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) @@ -1801,7 +1885,7 @@ def test_pause_queue_flattened(): client = CloudTasksClient(credentials=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: + 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() @@ -1833,9 +1917,7 @@ async def test_pause_queue_flattened_async(): client = CloudTasksAsyncClient(credentials=credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client._client._transport.pause_queue), "__call__" - ) as call: + 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() @@ -1876,7 +1958,7 @@ def test_resume_queue( request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client._transport.resume_queue), "__call__") as call: + 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( name="name_value", @@ -1897,6 +1979,7 @@ def test_resume_queue( 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" @@ -1909,19 +1992,19 @@ def test_resume_queue_from_dict(): @pytest.mark.asyncio -async def test_resume_queue_async(transport: str = "grpc_asyncio"): +async def test_resume_queue_async( + transport: str = "grpc_asyncio", request_type=cloudtasks.ResumeQueueRequest +): client = CloudTasksAsyncClient( credentials=credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, # and we are mocking out the actual API, so just send an empty request. - request = cloudtasks.ResumeQueueRequest() + request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client._client._transport.resume_queue), "__call__" - ) as call: + with mock.patch.object(type(client.transport.resume_queue), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( queue.Queue(name="name_value", state=queue.Queue.State.RUNNING,) @@ -1933,7 +2016,7 @@ async def test_resume_queue_async(transport: str = "grpc_asyncio"): assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == request + assert args[0] == cloudtasks.ResumeQueueRequest() # Establish that the response is the type that we expect. assert isinstance(response, queue.Queue) @@ -1943,6 +2026,11 @@ async def test_resume_queue_async(transport: str = "grpc_asyncio"): assert response.state == queue.Queue.State.RUNNING +@pytest.mark.asyncio +async def test_resume_queue_async_from_dict(): + await test_resume_queue_async(request_type=dict) + + def test_resume_queue_field_headers(): client = CloudTasksClient(credentials=credentials.AnonymousCredentials(),) @@ -1952,7 +2040,7 @@ def test_resume_queue_field_headers(): 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: + with mock.patch.object(type(client.transport.resume_queue), "__call__") as call: call.return_value = queue.Queue() client.resume_queue(request) @@ -1977,9 +2065,7 @@ async def test_resume_queue_field_headers_async(): request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client._client._transport.resume_queue), "__call__" - ) as call: + 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) @@ -1998,7 +2084,7 @@ def test_resume_queue_flattened(): client = CloudTasksClient(credentials=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: + 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() @@ -2030,9 +2116,7 @@ async def test_resume_queue_flattened_async(): client = CloudTasksAsyncClient(credentials=credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client._client._transport.resume_queue), "__call__" - ) as call: + 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() @@ -2073,7 +2157,7 @@ def test_get_iam_policy( request = request_type() # 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: + 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",) @@ -2086,6 +2170,7 @@ def test_get_iam_policy( assert args[0] == iam_policy.GetIamPolicyRequest() # Establish that the response is the type that we expect. + assert isinstance(response, policy.Policy) assert response.version == 774 @@ -2098,19 +2183,19 @@ def test_get_iam_policy_from_dict(): @pytest.mark.asyncio -async def test_get_iam_policy_async(transport: str = "grpc_asyncio"): +async def test_get_iam_policy_async( + transport: str = "grpc_asyncio", request_type=iam_policy.GetIamPolicyRequest +): client = CloudTasksAsyncClient( credentials=credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, # and we are mocking out the actual API, so just send an empty request. - request = iam_policy.GetIamPolicyRequest() + request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client._client._transport.get_iam_policy), "__call__" - ) as call: + 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",) @@ -2122,7 +2207,7 @@ async def test_get_iam_policy_async(transport: str = "grpc_asyncio"): assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == request + assert args[0] == iam_policy.GetIamPolicyRequest() # Establish that the response is the type that we expect. assert isinstance(response, policy.Policy) @@ -2132,6 +2217,11 @@ async def test_get_iam_policy_async(transport: str = "grpc_asyncio"): assert response.etag == b"etag_blob" +@pytest.mark.asyncio +async def test_get_iam_policy_async_from_dict(): + await test_get_iam_policy_async(request_type=dict) + + def test_get_iam_policy_field_headers(): client = CloudTasksClient(credentials=credentials.AnonymousCredentials(),) @@ -2141,7 +2231,7 @@ def test_get_iam_policy_field_headers(): 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: + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: call.return_value = policy.Policy() client.get_iam_policy(request) @@ -2166,9 +2256,7 @@ async def test_get_iam_policy_field_headers_async(): request.resource = "resource/value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client._client._transport.get_iam_policy), "__call__" - ) as call: + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy.Policy()) await client.get_iam_policy(request) @@ -2183,10 +2271,10 @@ async def test_get_iam_policy_field_headers_async(): assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] -def test_get_iam_policy_from_dict(): +def test_get_iam_policy_from_dict_foreign(): client = CloudTasksClient(credentials=credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client._transport.get_iam_policy), "__call__") as call: + 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() @@ -2203,7 +2291,7 @@ def test_get_iam_policy_flattened(): client = CloudTasksClient(credentials=credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client._transport.get_iam_policy), "__call__") as call: + 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() @@ -2235,9 +2323,7 @@ async def test_get_iam_policy_flattened_async(): client = CloudTasksAsyncClient(credentials=credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client._client._transport.get_iam_policy), "__call__" - ) as call: + 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() @@ -2278,7 +2364,7 @@ def test_set_iam_policy( 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: + 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",) @@ -2291,6 +2377,7 @@ def test_set_iam_policy( assert args[0] == iam_policy.SetIamPolicyRequest() # Establish that the response is the type that we expect. + assert isinstance(response, policy.Policy) assert response.version == 774 @@ -2303,19 +2390,19 @@ def test_set_iam_policy_from_dict(): @pytest.mark.asyncio -async def test_set_iam_policy_async(transport: str = "grpc_asyncio"): +async def test_set_iam_policy_async( + transport: str = "grpc_asyncio", request_type=iam_policy.SetIamPolicyRequest +): client = CloudTasksAsyncClient( credentials=credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, # and we are mocking out the actual API, so just send an empty request. - request = iam_policy.SetIamPolicyRequest() + request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client._client._transport.set_iam_policy), "__call__" - ) as call: + 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",) @@ -2327,7 +2414,7 @@ async def test_set_iam_policy_async(transport: str = "grpc_asyncio"): assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == request + assert args[0] == iam_policy.SetIamPolicyRequest() # Establish that the response is the type that we expect. assert isinstance(response, policy.Policy) @@ -2337,6 +2424,11 @@ async def test_set_iam_policy_async(transport: str = "grpc_asyncio"): assert response.etag == b"etag_blob" +@pytest.mark.asyncio +async def test_set_iam_policy_async_from_dict(): + await test_set_iam_policy_async(request_type=dict) + + def test_set_iam_policy_field_headers(): client = CloudTasksClient(credentials=credentials.AnonymousCredentials(),) @@ -2346,7 +2438,7 @@ def test_set_iam_policy_field_headers(): 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: + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: call.return_value = policy.Policy() client.set_iam_policy(request) @@ -2371,9 +2463,7 @@ async def test_set_iam_policy_field_headers_async(): request.resource = "resource/value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client._client._transport.set_iam_policy), "__call__" - ) as call: + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy.Policy()) await client.set_iam_policy(request) @@ -2388,10 +2478,10 @@ async def test_set_iam_policy_field_headers_async(): assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] -def test_set_iam_policy_from_dict(): +def test_set_iam_policy_from_dict_foreign(): client = CloudTasksClient(credentials=credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client._transport.set_iam_policy), "__call__") as call: + 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() @@ -2408,7 +2498,7 @@ def test_set_iam_policy_flattened(): client = CloudTasksClient(credentials=credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client._transport.set_iam_policy), "__call__") as call: + 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() @@ -2440,9 +2530,7 @@ async def test_set_iam_policy_flattened_async(): client = CloudTasksAsyncClient(credentials=credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client._client._transport.set_iam_policy), "__call__" - ) as call: + 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() @@ -2484,7 +2572,7 @@ def test_test_iam_permissions( # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client._transport.test_iam_permissions), "__call__" + type(client.transport.test_iam_permissions), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = iam_policy.TestIamPermissionsResponse( @@ -2500,6 +2588,7 @@ def test_test_iam_permissions( assert args[0] == iam_policy.TestIamPermissionsRequest() # Establish that the response is the type that we expect. + assert isinstance(response, iam_policy.TestIamPermissionsResponse) assert response.permissions == ["permissions_value"] @@ -2510,18 +2599,20 @@ def test_test_iam_permissions_from_dict(): @pytest.mark.asyncio -async def test_test_iam_permissions_async(transport: str = "grpc_asyncio"): +async def test_test_iam_permissions_async( + transport: str = "grpc_asyncio", request_type=iam_policy.TestIamPermissionsRequest +): client = CloudTasksAsyncClient( credentials=credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, # and we are mocking out the actual API, so just send an empty request. - request = iam_policy.TestIamPermissionsRequest() + request = request_type() # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client._client._transport.test_iam_permissions), "__call__" + type(client.transport.test_iam_permissions), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( @@ -2534,7 +2625,7 @@ async def test_test_iam_permissions_async(transport: str = "grpc_asyncio"): assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == request + assert args[0] == iam_policy.TestIamPermissionsRequest() # Establish that the response is the type that we expect. assert isinstance(response, iam_policy.TestIamPermissionsResponse) @@ -2542,6 +2633,11 @@ async def test_test_iam_permissions_async(transport: str = "grpc_asyncio"): assert response.permissions == ["permissions_value"] +@pytest.mark.asyncio +async def test_test_iam_permissions_async_from_dict(): + await test_test_iam_permissions_async(request_type=dict) + + def test_test_iam_permissions_field_headers(): client = CloudTasksClient(credentials=credentials.AnonymousCredentials(),) @@ -2552,7 +2648,7 @@ def test_test_iam_permissions_field_headers(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client._transport.test_iam_permissions), "__call__" + type(client.transport.test_iam_permissions), "__call__" ) as call: call.return_value = iam_policy.TestIamPermissionsResponse() @@ -2579,7 +2675,7 @@ async def test_test_iam_permissions_field_headers_async(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client._client._transport.test_iam_permissions), "__call__" + type(client.transport.test_iam_permissions), "__call__" ) as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( iam_policy.TestIamPermissionsResponse() @@ -2597,11 +2693,11 @@ async def test_test_iam_permissions_field_headers_async(): assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] -def test_test_iam_permissions_from_dict(): +def test_test_iam_permissions_from_dict_foreign(): client = CloudTasksClient(credentials=credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client._transport.test_iam_permissions), "__call__" + type(client.transport.test_iam_permissions), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = iam_policy.TestIamPermissionsResponse() @@ -2620,7 +2716,7 @@ def test_test_iam_permissions_flattened(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client._transport.test_iam_permissions), "__call__" + type(client.transport.test_iam_permissions), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = iam_policy.TestIamPermissionsResponse() @@ -2660,7 +2756,7 @@ async def test_test_iam_permissions_flattened_async(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client._client._transport.test_iam_permissions), "__call__" + type(client.transport.test_iam_permissions), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = iam_policy.TestIamPermissionsResponse() @@ -2708,7 +2804,7 @@ def test_list_tasks(transport: str = "grpc", request_type=cloudtasks.ListTasksRe request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client._transport.list_tasks), "__call__") as call: + 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( next_page_token="next_page_token_value", @@ -2723,6 +2819,7 @@ def test_list_tasks(transport: str = "grpc", request_type=cloudtasks.ListTasksRe 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" @@ -2733,19 +2830,19 @@ def test_list_tasks_from_dict(): @pytest.mark.asyncio -async def test_list_tasks_async(transport: str = "grpc_asyncio"): +async def test_list_tasks_async( + transport: str = "grpc_asyncio", request_type=cloudtasks.ListTasksRequest +): client = CloudTasksAsyncClient( credentials=credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, # and we are mocking out the actual API, so just send an empty request. - request = cloudtasks.ListTasksRequest() + request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client._client._transport.list_tasks), "__call__" - ) as call: + with mock.patch.object(type(client.transport.list_tasks), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( cloudtasks.ListTasksResponse(next_page_token="next_page_token_value",) @@ -2757,7 +2854,7 @@ async def test_list_tasks_async(transport: str = "grpc_asyncio"): assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == request + assert args[0] == cloudtasks.ListTasksRequest() # Establish that the response is the type that we expect. assert isinstance(response, pagers.ListTasksAsyncPager) @@ -2765,6 +2862,11 @@ async def test_list_tasks_async(transport: str = "grpc_asyncio"): assert response.next_page_token == "next_page_token_value" +@pytest.mark.asyncio +async def test_list_tasks_async_from_dict(): + await test_list_tasks_async(request_type=dict) + + def test_list_tasks_field_headers(): client = CloudTasksClient(credentials=credentials.AnonymousCredentials(),) @@ -2774,7 +2876,7 @@ def test_list_tasks_field_headers(): 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: + with mock.patch.object(type(client.transport.list_tasks), "__call__") as call: call.return_value = cloudtasks.ListTasksResponse() client.list_tasks(request) @@ -2799,9 +2901,7 @@ async def test_list_tasks_field_headers_async(): request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client._client._transport.list_tasks), "__call__" - ) as call: + with mock.patch.object(type(client.transport.list_tasks), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( cloudtasks.ListTasksResponse() ) @@ -2822,7 +2922,7 @@ def test_list_tasks_flattened(): client = CloudTasksClient(credentials=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: + 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() @@ -2854,9 +2954,7 @@ async def test_list_tasks_flattened_async(): client = CloudTasksAsyncClient(credentials=credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client._client._transport.list_tasks), "__call__" - ) as call: + 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() @@ -2891,7 +2989,7 @@ def test_list_tasks_pager(): client = CloudTasksClient(credentials=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: + with mock.patch.object(type(client.transport.list_tasks), "__call__") as call: # Set the response to a series of pages. call.side_effect = ( cloudtasks.ListTasksResponse( @@ -2920,7 +3018,7 @@ def test_list_tasks_pages(): client = CloudTasksClient(credentials=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: + with mock.patch.object(type(client.transport.list_tasks), "__call__") as call: # Set the response to a series of pages. call.side_effect = ( cloudtasks.ListTasksResponse( @@ -2942,9 +3040,7 @@ async def test_list_tasks_async_pager(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client._client._transport.list_tasks), - "__call__", - new_callable=mock.AsyncMock, + type(client.transport.list_tasks), "__call__", new_callable=mock.AsyncMock ) as call: # Set the response to a series of pages. call.side_effect = ( @@ -2972,9 +3068,7 @@ async def test_list_tasks_async_pages(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client._client._transport.list_tasks), - "__call__", - new_callable=mock.AsyncMock, + type(client.transport.list_tasks), "__call__", new_callable=mock.AsyncMock ) as call: # Set the response to a series of pages. call.side_effect = ( @@ -3003,7 +3097,7 @@ def test_get_task(transport: str = "grpc", request_type=cloudtasks.GetTaskReques request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client._transport.get_task), "__call__") as call: + 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( name="name_value", @@ -3022,6 +3116,7 @@ def test_get_task(transport: str = "grpc", request_type=cloudtasks.GetTaskReques 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" @@ -3034,19 +3129,19 @@ def test_get_task_from_dict(): @pytest.mark.asyncio -async def test_get_task_async(transport: str = "grpc_asyncio"): +async def test_get_task_async( + transport: str = "grpc_asyncio", request_type=cloudtasks.GetTaskRequest +): client = CloudTasksAsyncClient( credentials=credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, # and we are mocking out the actual API, so just send an empty request. - request = cloudtasks.GetTaskRequest() + request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client._client._transport.get_task), "__call__" - ) as call: + with mock.patch.object(type(client.transport.get_task), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( task.Task(name="name_value", view=task.Task.View.BASIC,) @@ -3058,7 +3153,7 @@ async def test_get_task_async(transport: str = "grpc_asyncio"): assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == request + assert args[0] == cloudtasks.GetTaskRequest() # Establish that the response is the type that we expect. assert isinstance(response, task.Task) @@ -3068,6 +3163,11 @@ async def test_get_task_async(transport: str = "grpc_asyncio"): assert response.view == task.Task.View.BASIC +@pytest.mark.asyncio +async def test_get_task_async_from_dict(): + await test_get_task_async(request_type=dict) + + def test_get_task_field_headers(): client = CloudTasksClient(credentials=credentials.AnonymousCredentials(),) @@ -3077,7 +3177,7 @@ def test_get_task_field_headers(): 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: + with mock.patch.object(type(client.transport.get_task), "__call__") as call: call.return_value = task.Task() client.get_task(request) @@ -3102,9 +3202,7 @@ async def test_get_task_field_headers_async(): request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client._client._transport.get_task), "__call__" - ) as call: + 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) @@ -3123,7 +3221,7 @@ def test_get_task_flattened(): client = CloudTasksClient(credentials=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: + 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() @@ -3155,9 +3253,7 @@ async def test_get_task_flattened_async(): client = CloudTasksAsyncClient(credentials=credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client._client._transport.get_task), "__call__" - ) as call: + 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() @@ -3198,7 +3294,7 @@ def test_create_task( request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client._transport.create_task), "__call__") as call: + 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( name="name_value", @@ -3217,6 +3313,7 @@ def test_create_task( 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" @@ -3229,19 +3326,19 @@ def test_create_task_from_dict(): @pytest.mark.asyncio -async def test_create_task_async(transport: str = "grpc_asyncio"): +async def test_create_task_async( + transport: str = "grpc_asyncio", request_type=cloudtasks.CreateTaskRequest +): client = CloudTasksAsyncClient( credentials=credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, # and we are mocking out the actual API, so just send an empty request. - request = cloudtasks.CreateTaskRequest() + request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client._client._transport.create_task), "__call__" - ) as call: + with mock.patch.object(type(client.transport.create_task), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( gct_task.Task(name="name_value", view=gct_task.Task.View.BASIC,) @@ -3253,7 +3350,7 @@ async def test_create_task_async(transport: str = "grpc_asyncio"): assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == request + assert args[0] == cloudtasks.CreateTaskRequest() # Establish that the response is the type that we expect. assert isinstance(response, gct_task.Task) @@ -3263,6 +3360,11 @@ async def test_create_task_async(transport: str = "grpc_asyncio"): assert response.view == gct_task.Task.View.BASIC +@pytest.mark.asyncio +async def test_create_task_async_from_dict(): + await test_create_task_async(request_type=dict) + + def test_create_task_field_headers(): client = CloudTasksClient(credentials=credentials.AnonymousCredentials(),) @@ -3272,7 +3374,7 @@ def test_create_task_field_headers(): 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: + with mock.patch.object(type(client.transport.create_task), "__call__") as call: call.return_value = gct_task.Task() client.create_task(request) @@ -3297,9 +3399,7 @@ async def test_create_task_field_headers_async(): request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client._client._transport.create_task), "__call__" - ) as call: + 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) @@ -3318,7 +3418,7 @@ def test_create_task_flattened(): client = CloudTasksClient(credentials=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: + 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() @@ -3356,9 +3456,7 @@ async def test_create_task_flattened_async(): client = CloudTasksAsyncClient(credentials=credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client._client._transport.create_task), "__call__" - ) as call: + 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() @@ -3405,7 +3503,7 @@ def test_delete_task( request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client._transport.delete_task), "__call__") as call: + with mock.patch.object(type(client.transport.delete_task), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = None @@ -3426,19 +3524,19 @@ def test_delete_task_from_dict(): @pytest.mark.asyncio -async def test_delete_task_async(transport: str = "grpc_asyncio"): +async def test_delete_task_async( + transport: str = "grpc_asyncio", request_type=cloudtasks.DeleteTaskRequest +): client = CloudTasksAsyncClient( credentials=credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, # and we are mocking out the actual API, so just send an empty request. - request = cloudtasks.DeleteTaskRequest() + request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client._client._transport.delete_task), "__call__" - ) as call: + 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) @@ -3448,12 +3546,17 @@ async def test_delete_task_async(transport: str = "grpc_asyncio"): assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == request + assert args[0] == cloudtasks.DeleteTaskRequest() # Establish that the response is the type that we expect. assert response is None +@pytest.mark.asyncio +async def test_delete_task_async_from_dict(): + await test_delete_task_async(request_type=dict) + + def test_delete_task_field_headers(): client = CloudTasksClient(credentials=credentials.AnonymousCredentials(),) @@ -3463,7 +3566,7 @@ def test_delete_task_field_headers(): 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: + with mock.patch.object(type(client.transport.delete_task), "__call__") as call: call.return_value = None client.delete_task(request) @@ -3488,9 +3591,7 @@ async def test_delete_task_field_headers_async(): request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client._client._transport.delete_task), "__call__" - ) as call: + 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) @@ -3509,7 +3610,7 @@ def test_delete_task_flattened(): client = CloudTasksClient(credentials=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: + with mock.patch.object(type(client.transport.delete_task), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = None @@ -3541,9 +3642,7 @@ async def test_delete_task_flattened_async(): client = CloudTasksAsyncClient(credentials=credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client._client._transport.delete_task), "__call__" - ) as call: + with mock.patch.object(type(client.transport.delete_task), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = None @@ -3584,7 +3683,7 @@ def test_lease_tasks( request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client._transport.lease_tasks), "__call__") as call: + 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() @@ -3597,6 +3696,7 @@ def test_lease_tasks( assert args[0] == cloudtasks.LeaseTasksRequest() # Establish that the response is the type that we expect. + assert isinstance(response, cloudtasks.LeaseTasksResponse) @@ -3605,19 +3705,19 @@ def test_lease_tasks_from_dict(): @pytest.mark.asyncio -async def test_lease_tasks_async(transport: str = "grpc_asyncio"): +async def test_lease_tasks_async( + transport: str = "grpc_asyncio", request_type=cloudtasks.LeaseTasksRequest +): client = CloudTasksAsyncClient( credentials=credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, # and we are mocking out the actual API, so just send an empty request. - request = cloudtasks.LeaseTasksRequest() + request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client._client._transport.lease_tasks), "__call__" - ) as call: + with mock.patch.object(type(client.transport.lease_tasks), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( cloudtasks.LeaseTasksResponse() @@ -3629,12 +3729,17 @@ async def test_lease_tasks_async(transport: str = "grpc_asyncio"): assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == request + assert args[0] == cloudtasks.LeaseTasksRequest() # Establish that the response is the type that we expect. assert isinstance(response, cloudtasks.LeaseTasksResponse) +@pytest.mark.asyncio +async def test_lease_tasks_async_from_dict(): + await test_lease_tasks_async(request_type=dict) + + def test_lease_tasks_field_headers(): client = CloudTasksClient(credentials=credentials.AnonymousCredentials(),) @@ -3644,7 +3749,7 @@ def test_lease_tasks_field_headers(): 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: + with mock.patch.object(type(client.transport.lease_tasks), "__call__") as call: call.return_value = cloudtasks.LeaseTasksResponse() client.lease_tasks(request) @@ -3669,9 +3774,7 @@ async def test_lease_tasks_field_headers_async(): request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client._client._transport.lease_tasks), "__call__" - ) as call: + with mock.patch.object(type(client.transport.lease_tasks), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( cloudtasks.LeaseTasksResponse() ) @@ -3692,7 +3795,7 @@ def test_lease_tasks_flattened(): client = CloudTasksClient(credentials=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: + 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() @@ -3732,9 +3835,7 @@ async def test_lease_tasks_flattened_async(): client = CloudTasksAsyncClient(credentials=credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client._client._transport.lease_tasks), "__call__" - ) as call: + 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() @@ -3785,9 +3886,7 @@ def test_acknowledge_task( request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client._transport.acknowledge_task), "__call__" - ) as call: + with mock.patch.object(type(client.transport.acknowledge_task), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = None @@ -3808,19 +3907,19 @@ def test_acknowledge_task_from_dict(): @pytest.mark.asyncio -async def test_acknowledge_task_async(transport: str = "grpc_asyncio"): +async def test_acknowledge_task_async( + transport: str = "grpc_asyncio", request_type=cloudtasks.AcknowledgeTaskRequest +): client = CloudTasksAsyncClient( credentials=credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, # and we are mocking out the actual API, so just send an empty request. - request = cloudtasks.AcknowledgeTaskRequest() + request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client._client._transport.acknowledge_task), "__call__" - ) as call: + 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) @@ -3830,12 +3929,17 @@ async def test_acknowledge_task_async(transport: str = "grpc_asyncio"): assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == request + assert args[0] == cloudtasks.AcknowledgeTaskRequest() # Establish that the response is the type that we expect. assert response is None +@pytest.mark.asyncio +async def test_acknowledge_task_async_from_dict(): + await test_acknowledge_task_async(request_type=dict) + + def test_acknowledge_task_field_headers(): client = CloudTasksClient(credentials=credentials.AnonymousCredentials(),) @@ -3845,9 +3949,7 @@ def test_acknowledge_task_field_headers(): 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: + with mock.patch.object(type(client.transport.acknowledge_task), "__call__") as call: call.return_value = None client.acknowledge_task(request) @@ -3872,9 +3974,7 @@ async def test_acknowledge_task_field_headers_async(): request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client._client._transport.acknowledge_task), "__call__" - ) as call: + 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) @@ -3893,9 +3993,7 @@ def test_acknowledge_task_flattened(): client = CloudTasksClient(credentials=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: + with mock.patch.object(type(client.transport.acknowledge_task), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = None @@ -3935,9 +4033,7 @@ async def test_acknowledge_task_flattened_async(): client = CloudTasksAsyncClient(credentials=credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client._client._transport.acknowledge_task), "__call__" - ) as call: + with mock.patch.object(type(client.transport.acknowledge_task), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = None @@ -3986,7 +4082,7 @@ def test_renew_lease( request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client._transport.renew_lease), "__call__") as call: + 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( name="name_value", @@ -4005,6 +4101,7 @@ def test_renew_lease( 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" @@ -4017,19 +4114,19 @@ def test_renew_lease_from_dict(): @pytest.mark.asyncio -async def test_renew_lease_async(transport: str = "grpc_asyncio"): +async def test_renew_lease_async( + transport: str = "grpc_asyncio", request_type=cloudtasks.RenewLeaseRequest +): client = CloudTasksAsyncClient( credentials=credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, # and we are mocking out the actual API, so just send an empty request. - request = cloudtasks.RenewLeaseRequest() + request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client._client._transport.renew_lease), "__call__" - ) as call: + with mock.patch.object(type(client.transport.renew_lease), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( task.Task(name="name_value", view=task.Task.View.BASIC,) @@ -4041,7 +4138,7 @@ async def test_renew_lease_async(transport: str = "grpc_asyncio"): assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == request + assert args[0] == cloudtasks.RenewLeaseRequest() # Establish that the response is the type that we expect. assert isinstance(response, task.Task) @@ -4051,6 +4148,11 @@ async def test_renew_lease_async(transport: str = "grpc_asyncio"): assert response.view == task.Task.View.BASIC +@pytest.mark.asyncio +async def test_renew_lease_async_from_dict(): + await test_renew_lease_async(request_type=dict) + + def test_renew_lease_field_headers(): client = CloudTasksClient(credentials=credentials.AnonymousCredentials(),) @@ -4060,7 +4162,7 @@ def test_renew_lease_field_headers(): 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: + with mock.patch.object(type(client.transport.renew_lease), "__call__") as call: call.return_value = task.Task() client.renew_lease(request) @@ -4085,9 +4187,7 @@ async def test_renew_lease_field_headers_async(): request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client._client._transport.renew_lease), "__call__" - ) as call: + 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) @@ -4106,7 +4206,7 @@ def test_renew_lease_flattened(): client = CloudTasksClient(credentials=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: + 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() @@ -4153,9 +4253,7 @@ async def test_renew_lease_flattened_async(): client = CloudTasksAsyncClient(credentials=credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client._client._transport.renew_lease), "__call__" - ) as call: + 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() @@ -4211,7 +4309,7 @@ def test_cancel_lease( request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client._transport.cancel_lease), "__call__") as call: + 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( name="name_value", @@ -4230,6 +4328,7 @@ def test_cancel_lease( 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" @@ -4242,19 +4341,19 @@ def test_cancel_lease_from_dict(): @pytest.mark.asyncio -async def test_cancel_lease_async(transport: str = "grpc_asyncio"): +async def test_cancel_lease_async( + transport: str = "grpc_asyncio", request_type=cloudtasks.CancelLeaseRequest +): client = CloudTasksAsyncClient( credentials=credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, # and we are mocking out the actual API, so just send an empty request. - request = cloudtasks.CancelLeaseRequest() + request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client._client._transport.cancel_lease), "__call__" - ) as call: + with mock.patch.object(type(client.transport.cancel_lease), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( task.Task(name="name_value", view=task.Task.View.BASIC,) @@ -4266,7 +4365,7 @@ async def test_cancel_lease_async(transport: str = "grpc_asyncio"): assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == request + assert args[0] == cloudtasks.CancelLeaseRequest() # Establish that the response is the type that we expect. assert isinstance(response, task.Task) @@ -4276,6 +4375,11 @@ async def test_cancel_lease_async(transport: str = "grpc_asyncio"): assert response.view == task.Task.View.BASIC +@pytest.mark.asyncio +async def test_cancel_lease_async_from_dict(): + await test_cancel_lease_async(request_type=dict) + + def test_cancel_lease_field_headers(): client = CloudTasksClient(credentials=credentials.AnonymousCredentials(),) @@ -4285,7 +4389,7 @@ def test_cancel_lease_field_headers(): 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: + with mock.patch.object(type(client.transport.cancel_lease), "__call__") as call: call.return_value = task.Task() client.cancel_lease(request) @@ -4310,9 +4414,7 @@ async def test_cancel_lease_field_headers_async(): request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client._client._transport.cancel_lease), "__call__" - ) as call: + 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) @@ -4331,7 +4433,7 @@ def test_cancel_lease_flattened(): client = CloudTasksClient(credentials=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: + 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() @@ -4371,9 +4473,7 @@ async def test_cancel_lease_flattened_async(): client = CloudTasksAsyncClient(credentials=credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client._client._transport.cancel_lease), "__call__" - ) as call: + 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() @@ -4420,7 +4520,7 @@ def test_run_task(transport: str = "grpc", request_type=cloudtasks.RunTaskReques request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client._transport.run_task), "__call__") as call: + 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( name="name_value", @@ -4439,6 +4539,7 @@ def test_run_task(transport: str = "grpc", request_type=cloudtasks.RunTaskReques 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" @@ -4451,19 +4552,19 @@ def test_run_task_from_dict(): @pytest.mark.asyncio -async def test_run_task_async(transport: str = "grpc_asyncio"): +async def test_run_task_async( + transport: str = "grpc_asyncio", request_type=cloudtasks.RunTaskRequest +): client = CloudTasksAsyncClient( credentials=credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, # and we are mocking out the actual API, so just send an empty request. - request = cloudtasks.RunTaskRequest() + request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client._client._transport.run_task), "__call__" - ) as call: + with mock.patch.object(type(client.transport.run_task), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( task.Task(name="name_value", view=task.Task.View.BASIC,) @@ -4475,7 +4576,7 @@ async def test_run_task_async(transport: str = "grpc_asyncio"): assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == request + assert args[0] == cloudtasks.RunTaskRequest() # Establish that the response is the type that we expect. assert isinstance(response, task.Task) @@ -4485,6 +4586,11 @@ async def test_run_task_async(transport: str = "grpc_asyncio"): assert response.view == task.Task.View.BASIC +@pytest.mark.asyncio +async def test_run_task_async_from_dict(): + await test_run_task_async(request_type=dict) + + def test_run_task_field_headers(): client = CloudTasksClient(credentials=credentials.AnonymousCredentials(),) @@ -4494,7 +4600,7 @@ def test_run_task_field_headers(): 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: + with mock.patch.object(type(client.transport.run_task), "__call__") as call: call.return_value = task.Task() client.run_task(request) @@ -4519,9 +4625,7 @@ async def test_run_task_field_headers_async(): request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client._client._transport.run_task), "__call__" - ) as call: + 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) @@ -4540,7 +4644,7 @@ def test_run_task_flattened(): client = CloudTasksClient(credentials=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: + 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() @@ -4572,9 +4676,7 @@ async def test_run_task_flattened_async(): client = CloudTasksAsyncClient(credentials=credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client._client._transport.run_task), "__call__" - ) as call: + 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() @@ -4639,7 +4741,7 @@ def test_transport_instance(): credentials=credentials.AnonymousCredentials(), ) client = CloudTasksClient(transport=transport) - assert client._transport is transport + assert client.transport is transport def test_transport_get_channel(): @@ -4657,10 +4759,22 @@ def test_transport_get_channel(): assert channel +@pytest.mark.parametrize( + "transport_class", + [transports.CloudTasksGrpcTransport, transports.CloudTasksGrpcAsyncIOTransport], +) +def test_transport_adc(transport_class): + # Test default credentials are used if not provided. + with mock.patch.object(auth, "default") as adc: + adc.return_value = (credentials.AnonymousCredentials(), None) + transport_class() + adc.assert_called_once() + + def test_transport_grpc_default(): # A client should use the gRPC transport by default. client = CloudTasksClient(credentials=credentials.AnonymousCredentials(),) - assert isinstance(client._transport, transports.CloudTasksGrpcTransport,) + assert isinstance(client.transport, transports.CloudTasksGrpcTransport,) def test_cloud_tasks_base_transport_error(): @@ -4730,6 +4844,17 @@ 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( + "google.cloud.tasks_v2beta2.services.cloud_tasks.transports.CloudTasksTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + adc.return_value = (credentials.AnonymousCredentials(), None) + transport = transports.CloudTasksTransport() + adc.assert_called_once() + + def test_cloud_tasks_auth_adc(): # If no credentials are provided, we should use ADC credentials. with mock.patch.object(auth, "default") as adc: @@ -4762,7 +4887,7 @@ def test_cloud_tasks_host_no_port(): api_endpoint="cloudtasks.googleapis.com" ), ) - assert client._transport._host == "cloudtasks.googleapis.com:443" + assert client.transport._host == "cloudtasks.googleapis.com:443" def test_cloud_tasks_host_with_port(): @@ -4772,192 +4897,143 @@ def test_cloud_tasks_host_with_port(): api_endpoint="cloudtasks.googleapis.com:8000" ), ) - assert client._transport._host == "cloudtasks.googleapis.com:8000" + assert client.transport._host == "cloudtasks.googleapis.com:8000" def test_cloud_tasks_grpc_transport_channel(): channel = grpc.insecure_channel("http://localhost/") - # Check that if channel is provided, mtls endpoint and client_cert_source - # won't be used. - callback = mock.MagicMock() + # Check that channel is used if provided. transport = transports.CloudTasksGrpcTransport( - host="squid.clam.whelk", - channel=channel, - api_mtls_endpoint="mtls.squid.clam.whelk", - client_cert_source=callback, + host="squid.clam.whelk", channel=channel, ) assert transport.grpc_channel == channel assert transport._host == "squid.clam.whelk:443" - assert not callback.called + assert transport._ssl_channel_credentials == None def test_cloud_tasks_grpc_asyncio_transport_channel(): channel = aio.insecure_channel("http://localhost/") - # Check that if channel is provided, mtls endpoint and client_cert_source - # won't be used. - callback = mock.MagicMock() + # Check that channel is used if provided. transport = transports.CloudTasksGrpcAsyncIOTransport( - host="squid.clam.whelk", - channel=channel, - api_mtls_endpoint="mtls.squid.clam.whelk", - client_cert_source=callback, + host="squid.clam.whelk", channel=channel, ) assert transport.grpc_channel == channel assert transport._host == "squid.clam.whelk:443" - assert not callback.called - - -@mock.patch("grpc.ssl_channel_credentials", autospec=True) -@mock.patch("google.api_core.grpc_helpers.create_channel", autospec=True) -def test_cloud_tasks_grpc_transport_channel_mtls_with_client_cert_source( - grpc_create_channel, grpc_ssl_channel_cred -): - # Check that if channel is None, but api_mtls_endpoint and client_cert_source - # are provided, then a mTLS channel will be created. - mock_cred = mock.Mock() - - mock_ssl_cred = mock.Mock() - grpc_ssl_channel_cred.return_value = mock_ssl_cred - - mock_grpc_channel = mock.Mock() - grpc_create_channel.return_value = mock_grpc_channel - - transport = transports.CloudTasksGrpcTransport( - host="squid.clam.whelk", - credentials=mock_cred, - api_mtls_endpoint="mtls.squid.clam.whelk", - client_cert_source=client_cert_source_callback, - ) - grpc_ssl_channel_cred.assert_called_once_with( - certificate_chain=b"cert bytes", private_key=b"key bytes" - ) - grpc_create_channel.assert_called_once_with( - "mtls.squid.clam.whelk:443", - credentials=mock_cred, - credentials_file=None, - scopes=("https://www.googleapis.com/auth/cloud-platform",), - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - ) - assert transport.grpc_channel == mock_grpc_channel - - -@mock.patch("grpc.ssl_channel_credentials", autospec=True) -@mock.patch("google.api_core.grpc_helpers_async.create_channel", autospec=True) -def test_cloud_tasks_grpc_asyncio_transport_channel_mtls_with_client_cert_source( - grpc_create_channel, grpc_ssl_channel_cred -): - # Check that if channel is None, but api_mtls_endpoint and client_cert_source - # are provided, then a mTLS channel will be created. - mock_cred = mock.Mock() - - mock_ssl_cred = mock.Mock() - grpc_ssl_channel_cred.return_value = mock_ssl_cred - - mock_grpc_channel = mock.Mock() - grpc_create_channel.return_value = mock_grpc_channel - - transport = transports.CloudTasksGrpcAsyncIOTransport( - host="squid.clam.whelk", - credentials=mock_cred, - api_mtls_endpoint="mtls.squid.clam.whelk", - client_cert_source=client_cert_source_callback, - ) - grpc_ssl_channel_cred.assert_called_once_with( - certificate_chain=b"cert bytes", private_key=b"key bytes" - ) - grpc_create_channel.assert_called_once_with( - "mtls.squid.clam.whelk:443", - credentials=mock_cred, - credentials_file=None, - scopes=("https://www.googleapis.com/auth/cloud-platform",), - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - ) - assert transport.grpc_channel == mock_grpc_channel + assert transport._ssl_channel_credentials == None @pytest.mark.parametrize( - "api_mtls_endpoint", ["mtls.squid.clam.whelk", "mtls.squid.clam.whelk:443"] + "transport_class", + [transports.CloudTasksGrpcTransport, transports.CloudTasksGrpcAsyncIOTransport], ) -@mock.patch("google.api_core.grpc_helpers.create_channel", autospec=True) -def test_cloud_tasks_grpc_transport_channel_mtls_with_adc( - grpc_create_channel, api_mtls_endpoint -): - # Check that if channel and client_cert_source are None, but api_mtls_endpoint - # is provided, then a mTLS channel will be created with SSL ADC. - mock_grpc_channel = mock.Mock() - grpc_create_channel.return_value = mock_grpc_channel - - # Mock google.auth.transport.grpc.SslCredentials class. - mock_ssl_cred = mock.Mock() - with mock.patch.multiple( - "google.auth.transport.grpc.SslCredentials", - __init__=mock.Mock(return_value=None), - ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), - ): - mock_cred = mock.Mock() - transport = transports.CloudTasksGrpcTransport( - host="squid.clam.whelk", - credentials=mock_cred, - api_mtls_endpoint=api_mtls_endpoint, - client_cert_source=None, - ) - grpc_create_channel.assert_called_once_with( - "mtls.squid.clam.whelk:443", - credentials=mock_cred, - credentials_file=None, - scopes=("https://www.googleapis.com/auth/cloud-platform",), - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - ) - assert transport.grpc_channel == mock_grpc_channel +def test_cloud_tasks_transport_channel_mtls_with_client_cert_source(transport_class): + with mock.patch( + "grpc.ssl_channel_credentials", autospec=True + ) as grpc_ssl_channel_cred: + with mock.patch.object( + transport_class, "create_channel", autospec=True + ) as grpc_create_channel: + mock_ssl_cred = mock.Mock() + grpc_ssl_channel_cred.return_value = mock_ssl_cred + + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + + cred = credentials.AnonymousCredentials() + with pytest.warns(DeprecationWarning): + with mock.patch.object(auth, "default") as adc: + adc.return_value = (cred, None) + transport = transport_class( + host="squid.clam.whelk", + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=client_cert_source_callback, + ) + adc.assert_called_once() + + grpc_ssl_channel_cred.assert_called_once_with( + certificate_chain=b"cert bytes", private_key=b"key bytes" + ) + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=("https://www.googleapis.com/auth/cloud-platform",), + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + ) + assert transport.grpc_channel == mock_grpc_channel + assert transport._ssl_channel_credentials == mock_ssl_cred @pytest.mark.parametrize( - "api_mtls_endpoint", ["mtls.squid.clam.whelk", "mtls.squid.clam.whelk:443"] + "transport_class", + [transports.CloudTasksGrpcTransport, transports.CloudTasksGrpcAsyncIOTransport], ) -@mock.patch("google.api_core.grpc_helpers_async.create_channel", autospec=True) -def test_cloud_tasks_grpc_asyncio_transport_channel_mtls_with_adc( - grpc_create_channel, api_mtls_endpoint -): - # Check that if channel and client_cert_source are None, but api_mtls_endpoint - # is provided, then a mTLS channel will be created with SSL ADC. - mock_grpc_channel = mock.Mock() - grpc_create_channel.return_value = mock_grpc_channel - - # Mock google.auth.transport.grpc.SslCredentials class. +def test_cloud_tasks_transport_channel_mtls_with_adc(transport_class): mock_ssl_cred = mock.Mock() with mock.patch.multiple( "google.auth.transport.grpc.SslCredentials", __init__=mock.Mock(return_value=None), ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), ): - mock_cred = mock.Mock() - transport = transports.CloudTasksGrpcAsyncIOTransport( - host="squid.clam.whelk", - credentials=mock_cred, - api_mtls_endpoint=api_mtls_endpoint, - client_cert_source=None, - ) - grpc_create_channel.assert_called_once_with( - "mtls.squid.clam.whelk:443", - credentials=mock_cred, - credentials_file=None, - scopes=("https://www.googleapis.com/auth/cloud-platform",), - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - ) - assert transport.grpc_channel == mock_grpc_channel + with mock.patch.object( + transport_class, "create_channel", autospec=True + ) as grpc_create_channel: + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + mock_cred = mock.Mock() + + with pytest.warns(DeprecationWarning): + transport = transport_class( + host="squid.clam.whelk", + credentials=mock_cred, + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=None, + ) + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=mock_cred, + credentials_file=None, + scopes=("https://www.googleapis.com/auth/cloud-platform",), + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + ) + assert transport.grpc_channel == mock_grpc_channel -def test_task_path(): + +def test_queue_path(): project = "squid" location = "clam" queue = "whelk" - task = "octopus" + + expected = "projects/{project}/locations/{location}/queues/{queue}".format( + project=project, location=location, queue=queue, + ) + actual = CloudTasksClient.queue_path(project, location, queue) + assert expected == actual + + +def test_parse_queue_path(): + expected = { + "project": "octopus", + "location": "oyster", + "queue": "nudibranch", + } + path = CloudTasksClient.queue_path(**expected) + + # Check that the path construction is reversible. + actual = CloudTasksClient.parse_queue_path(path) + assert expected == actual + + +def test_task_path(): + project = "cuttlefish" + location = "mussel" + queue = "winkle" + task = "nautilus" expected = "projects/{project}/locations/{location}/queues/{queue}/tasks/{task}".format( project=project, location=location, queue=queue, task=task, @@ -4968,10 +5044,10 @@ def test_task_path(): def test_parse_task_path(): expected = { - "project": "oyster", - "location": "nudibranch", - "queue": "cuttlefish", - "task": "mussel", + "project": "scallop", + "location": "abalone", + "queue": "squid", + "task": "clam", } path = CloudTasksClient.task_path(**expected) @@ -4980,28 +5056,104 @@ def test_parse_task_path(): assert expected == actual -def test_queue_path(): - project = "squid" - location = "clam" - queue = "whelk" +def test_common_billing_account_path(): + billing_account = "whelk" - expected = "projects/{project}/locations/{location}/queues/{queue}".format( - project=project, location=location, queue=queue, + expected = "billingAccounts/{billing_account}".format( + billing_account=billing_account, ) - actual = CloudTasksClient.queue_path(project, location, queue) + actual = CloudTasksClient.common_billing_account_path(billing_account) assert expected == actual -def test_parse_queue_path(): +def test_parse_common_billing_account_path(): expected = { - "project": "octopus", - "location": "oyster", - "queue": "nudibranch", + "billing_account": "octopus", } - path = CloudTasksClient.queue_path(**expected) + path = CloudTasksClient.common_billing_account_path(**expected) # Check that the path construction is reversible. - actual = CloudTasksClient.parse_queue_path(path) + actual = CloudTasksClient.parse_common_billing_account_path(path) + assert expected == actual + + +def test_common_folder_path(): + folder = "oyster" + + expected = "folders/{folder}".format(folder=folder,) + actual = CloudTasksClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "nudibranch", + } + path = CloudTasksClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = CloudTasksClient.parse_common_folder_path(path) + assert expected == actual + + +def test_common_organization_path(): + organization = "cuttlefish" + + expected = "organizations/{organization}".format(organization=organization,) + actual = CloudTasksClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "mussel", + } + path = CloudTasksClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = CloudTasksClient.parse_common_organization_path(path) + assert expected == actual + + +def test_common_project_path(): + project = "winkle" + + expected = "projects/{project}".format(project=project,) + actual = CloudTasksClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "nautilus", + } + path = CloudTasksClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = CloudTasksClient.parse_common_project_path(path) + assert expected == actual + + +def test_common_location_path(): + project = "scallop" + location = "abalone" + + expected = "projects/{project}/locations/{location}".format( + project=project, location=location, + ) + actual = CloudTasksClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "squid", + "location": "clam", + } + path = CloudTasksClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = CloudTasksClient.parse_common_location_path(path) assert expected == actual diff --git a/tests/unit/gapic/tasks_v2beta3/test_cloud_tasks.py b/tests/unit/gapic/tasks_v2beta3/test_cloud_tasks.py index 933dba70..3d94928f 100644 --- a/tests/unit/gapic/tasks_v2beta3/test_cloud_tasks.py +++ b/tests/unit/gapic/tasks_v2beta3/test_cloud_tasks.py @@ -46,7 +46,7 @@ from google.iam.v1 import options_pb2 as options # type: ignore from google.iam.v1 import policy_pb2 as policy # type: ignore from google.oauth2 import service_account -from google.protobuf import any_pb2 as any # type: ignore +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 @@ -103,12 +103,12 @@ def test_cloud_tasks_client_from_service_account_file(client_class): ) as factory: factory.return_value = creds client = client_class.from_service_account_file("dummy/file/path.json") - assert client._transport._credentials == creds + assert client.transport._credentials == creds client = client_class.from_service_account_json("dummy/file/path.json") - assert client._transport._credentials == creds + assert client.transport._credentials == creds - assert client._transport._host == "cloudtasks.googleapis.com:443" + assert client.transport._host == "cloudtasks.googleapis.com:443" def test_cloud_tasks_client_get_transport_class(): @@ -162,15 +162,14 @@ def test_cloud_tasks_client_client_options( credentials_file=None, host="squid.clam.whelk", scopes=None, - api_mtls_endpoint="squid.clam.whelk", - client_cert_source=None, + ssl_channel_credentials=None, quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, ) - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS is + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is # "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS": "never"}): + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): with mock.patch.object(transport_class, "__init__") as patched: patched.return_value = None client = client_class() @@ -179,15 +178,14 @@ def test_cloud_tasks_client_client_options( credentials_file=None, host=client.DEFAULT_ENDPOINT, scopes=None, - api_mtls_endpoint=client.DEFAULT_ENDPOINT, - client_cert_source=None, + ssl_channel_credentials=None, quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, ) - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS is + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is # "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS": "always"}): + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): with mock.patch.object(transport_class, "__init__") as patched: patched.return_value = None client = client_class() @@ -196,95 +194,173 @@ def test_cloud_tasks_client_client_options( credentials_file=None, host=client.DEFAULT_MTLS_ENDPOINT, scopes=None, - api_mtls_endpoint=client.DEFAULT_MTLS_ENDPOINT, - client_cert_source=None, + ssl_channel_credentials=None, quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, ) - # Check the case api_endpoint is not provided, GOOGLE_API_USE_MTLS is - # "auto", and client_cert_source is provided. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS": "auto"}): + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError): + client = client_class() + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"} + ): + with pytest.raises(ValueError): + client = client_class() + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + ssl_channel_credentials=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name,use_client_cert_env", + [ + (CloudTasksClient, transports.CloudTasksGrpcTransport, "grpc", "true"), + ( + CloudTasksAsyncClient, + transports.CloudTasksGrpcAsyncIOTransport, + "grpc_asyncio", + "true", + ), + (CloudTasksClient, transports.CloudTasksGrpcTransport, "grpc", "false"), + ( + CloudTasksAsyncClient, + transports.CloudTasksGrpcAsyncIOTransport, + "grpc_asyncio", + "false", + ), + ], +) +@mock.patch.object( + CloudTasksClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CloudTasksClient) +) +@mock.patch.object( + CloudTasksAsyncClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(CloudTasksAsyncClient), +) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_cloud_tasks_client_mtls_env_auto( + client_class, transport_class, transport_name, use_client_cert_env +): + # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default + # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. + + # Check the case client_cert_source is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} + ): options = client_options.ClientOptions( client_cert_source=client_cert_source_callback ) with mock.patch.object(transport_class, "__init__") as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_MTLS_ENDPOINT, - scopes=None, - api_mtls_endpoint=client.DEFAULT_MTLS_ENDPOINT, - client_cert_source=client_cert_source_callback, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - - # Check the case api_endpoint is not provided, GOOGLE_API_USE_MTLS is - # "auto", and default_client_cert_source is provided. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS": "auto"}): - with mock.patch.object(transport_class, "__init__") as patched: + ssl_channel_creds = mock.Mock() with mock.patch( - "google.auth.transport.mtls.has_default_client_cert_source", - return_value=True, + "grpc.ssl_channel_credentials", return_value=ssl_channel_creds ): patched.return_value = None - client = client_class() + client = client_class(client_options=options) + + if use_client_cert_env == "false": + expected_ssl_channel_creds = None + expected_host = client.DEFAULT_ENDPOINT + else: + expected_ssl_channel_creds = ssl_channel_creds + expected_host = client.DEFAULT_MTLS_ENDPOINT + patched.assert_called_once_with( credentials=None, credentials_file=None, - host=client.DEFAULT_MTLS_ENDPOINT, + host=expected_host, scopes=None, - api_mtls_endpoint=client.DEFAULT_MTLS_ENDPOINT, - client_cert_source=None, + ssl_channel_credentials=expected_ssl_channel_creds, quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, ) - # Check the case api_endpoint is not provided, GOOGLE_API_USE_MTLS is - # "auto", but client_cert_source and default_client_cert_source are None. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS": "auto"}): + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} + ): with mock.patch.object(transport_class, "__init__") as patched: with mock.patch( - "google.auth.transport.mtls.has_default_client_cert_source", - return_value=False, + "google.auth.transport.grpc.SslCredentials.__init__", return_value=None ): - patched.return_value = None - client = client_class() - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - api_mtls_endpoint=client.DEFAULT_ENDPOINT, - client_cert_source=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS has - # unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS": "Unsupported"}): - with pytest.raises(MutualTLSChannelError): - client = client_class() - - # Check the case quota_project_id is provided - options = client_options.ClientOptions(quota_project_id="octopus") - with mock.patch.object(transport_class, "__init__") as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - api_mtls_endpoint=client.DEFAULT_ENDPOINT, - client_cert_source=None, - quota_project_id="octopus", - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) + with mock.patch( + "google.auth.transport.grpc.SslCredentials.is_mtls", + new_callable=mock.PropertyMock, + ) as is_mtls_mock: + with mock.patch( + "google.auth.transport.grpc.SslCredentials.ssl_credentials", + new_callable=mock.PropertyMock, + ) as ssl_credentials_mock: + if use_client_cert_env == "false": + is_mtls_mock.return_value = False + ssl_credentials_mock.return_value = None + expected_host = client.DEFAULT_ENDPOINT + expected_ssl_channel_creds = None + else: + is_mtls_mock.return_value = True + ssl_credentials_mock.return_value = mock.Mock() + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_ssl_channel_creds = ( + ssl_credentials_mock.return_value + ) + + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + ssl_channel_credentials=expected_ssl_channel_creds, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} + ): + with mock.patch.object(transport_class, "__init__") as patched: + with mock.patch( + "google.auth.transport.grpc.SslCredentials.__init__", return_value=None + ): + with mock.patch( + "google.auth.transport.grpc.SslCredentials.is_mtls", + new_callable=mock.PropertyMock, + ) as is_mtls_mock: + is_mtls_mock.return_value = False + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + ssl_channel_credentials=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) @pytest.mark.parametrize( @@ -311,8 +387,7 @@ def test_cloud_tasks_client_client_options_scopes( credentials_file=None, host=client.DEFAULT_ENDPOINT, scopes=["1", "2"], - api_mtls_endpoint=client.DEFAULT_ENDPOINT, - client_cert_source=None, + ssl_channel_credentials=None, quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, ) @@ -342,8 +417,7 @@ def test_cloud_tasks_client_client_options_credentials_file( credentials_file="credentials.json", host=client.DEFAULT_ENDPOINT, scopes=None, - api_mtls_endpoint=client.DEFAULT_ENDPOINT, - client_cert_source=None, + ssl_channel_credentials=None, quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, ) @@ -360,8 +434,7 @@ def test_cloud_tasks_client_client_options_from_dict(): credentials_file=None, host="squid.clam.whelk", scopes=None, - api_mtls_endpoint="squid.clam.whelk", - client_cert_source=None, + ssl_channel_credentials=None, quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, ) @@ -379,7 +452,7 @@ def test_list_queues( request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client._transport.list_queues), "__call__") as call: + 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( next_page_token="next_page_token_value", @@ -394,6 +467,7 @@ def test_list_queues( 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" @@ -404,19 +478,19 @@ def test_list_queues_from_dict(): @pytest.mark.asyncio -async def test_list_queues_async(transport: str = "grpc_asyncio"): +async def test_list_queues_async( + transport: str = "grpc_asyncio", request_type=cloudtasks.ListQueuesRequest +): client = CloudTasksAsyncClient( credentials=credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, # and we are mocking out the actual API, so just send an empty request. - request = cloudtasks.ListQueuesRequest() + request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client._client._transport.list_queues), "__call__" - ) as call: + with mock.patch.object(type(client.transport.list_queues), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( cloudtasks.ListQueuesResponse(next_page_token="next_page_token_value",) @@ -428,7 +502,7 @@ async def test_list_queues_async(transport: str = "grpc_asyncio"): assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == request + assert args[0] == cloudtasks.ListQueuesRequest() # Establish that the response is the type that we expect. assert isinstance(response, pagers.ListQueuesAsyncPager) @@ -436,6 +510,11 @@ async def test_list_queues_async(transport: str = "grpc_asyncio"): assert response.next_page_token == "next_page_token_value" +@pytest.mark.asyncio +async def test_list_queues_async_from_dict(): + await test_list_queues_async(request_type=dict) + + def test_list_queues_field_headers(): client = CloudTasksClient(credentials=credentials.AnonymousCredentials(),) @@ -445,7 +524,7 @@ def test_list_queues_field_headers(): 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: + with mock.patch.object(type(client.transport.list_queues), "__call__") as call: call.return_value = cloudtasks.ListQueuesResponse() client.list_queues(request) @@ -470,9 +549,7 @@ async def test_list_queues_field_headers_async(): request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client._client._transport.list_queues), "__call__" - ) as call: + with mock.patch.object(type(client.transport.list_queues), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( cloudtasks.ListQueuesResponse() ) @@ -493,7 +570,7 @@ def test_list_queues_flattened(): client = CloudTasksClient(credentials=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: + 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() @@ -525,9 +602,7 @@ async def test_list_queues_flattened_async(): client = CloudTasksAsyncClient(credentials=credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client._client._transport.list_queues), "__call__" - ) as call: + 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() @@ -562,7 +637,7 @@ def test_list_queues_pager(): client = CloudTasksClient(credentials=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: + with mock.patch.object(type(client.transport.list_queues), "__call__") as call: # Set the response to a series of pages. call.side_effect = ( cloudtasks.ListQueuesResponse( @@ -594,7 +669,7 @@ def test_list_queues_pages(): client = CloudTasksClient(credentials=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: + with mock.patch.object(type(client.transport.list_queues), "__call__") as call: # Set the response to a series of pages. call.side_effect = ( cloudtasks.ListQueuesResponse( @@ -619,9 +694,7 @@ async def test_list_queues_async_pager(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client._client._transport.list_queues), - "__call__", - new_callable=mock.AsyncMock, + type(client.transport.list_queues), "__call__", new_callable=mock.AsyncMock ) as call: # Set the response to a series of pages. call.side_effect = ( @@ -652,9 +725,7 @@ async def test_list_queues_async_pages(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client._client._transport.list_queues), - "__call__", - new_callable=mock.AsyncMock, + type(client.transport.list_queues), "__call__", new_callable=mock.AsyncMock ) as call: # Set the response to a series of pages. call.side_effect = ( @@ -686,12 +757,12 @@ def test_get_queue(transport: str = "grpc", request_type=cloudtasks.GetQueueRequ request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client._transport.get_queue), "__call__") as call: + 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( name="name_value", state=queue.Queue.State.RUNNING, - type=queue.Queue.Type.PULL, + type_=queue.Queue.Type.PULL, app_engine_http_queue=target.AppEngineHttpQueue( app_engine_routing_override=target.AppEngineRouting( service="service_value" @@ -708,13 +779,14 @@ def test_get_queue(transport: str = "grpc", request_type=cloudtasks.GetQueueRequ 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 + assert response.type_ == queue.Queue.Type.PULL def test_get_queue_from_dict(): @@ -722,25 +794,25 @@ def test_get_queue_from_dict(): @pytest.mark.asyncio -async def test_get_queue_async(transport: str = "grpc_asyncio"): +async def test_get_queue_async( + transport: str = "grpc_asyncio", request_type=cloudtasks.GetQueueRequest +): client = CloudTasksAsyncClient( credentials=credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, # and we are mocking out the actual API, so just send an empty request. - request = cloudtasks.GetQueueRequest() + request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client._client._transport.get_queue), "__call__" - ) as call: + with mock.patch.object(type(client.transport.get_queue), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( queue.Queue( name="name_value", state=queue.Queue.State.RUNNING, - type=queue.Queue.Type.PULL, + type_=queue.Queue.Type.PULL, ) ) @@ -750,7 +822,7 @@ async def test_get_queue_async(transport: str = "grpc_asyncio"): assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == request + assert args[0] == cloudtasks.GetQueueRequest() # Establish that the response is the type that we expect. assert isinstance(response, queue.Queue) @@ -759,7 +831,12 @@ async def test_get_queue_async(transport: str = "grpc_asyncio"): assert response.state == queue.Queue.State.RUNNING - assert response.type == queue.Queue.Type.PULL + assert response.type_ == queue.Queue.Type.PULL + + +@pytest.mark.asyncio +async def test_get_queue_async_from_dict(): + await test_get_queue_async(request_type=dict) def test_get_queue_field_headers(): @@ -771,7 +848,7 @@ def test_get_queue_field_headers(): 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: + with mock.patch.object(type(client.transport.get_queue), "__call__") as call: call.return_value = queue.Queue() client.get_queue(request) @@ -796,9 +873,7 @@ async def test_get_queue_field_headers_async(): request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client._client._transport.get_queue), "__call__" - ) as call: + 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) @@ -817,7 +892,7 @@ def test_get_queue_flattened(): client = CloudTasksClient(credentials=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: + 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() @@ -849,9 +924,7 @@ async def test_get_queue_flattened_async(): client = CloudTasksAsyncClient(credentials=credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client._client._transport.get_queue), "__call__" - ) as call: + 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() @@ -892,12 +965,12 @@ def test_create_queue( request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client._transport.create_queue), "__call__") as call: + 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( name="name_value", state=gct_queue.Queue.State.RUNNING, - type=gct_queue.Queue.Type.PULL, + type_=gct_queue.Queue.Type.PULL, app_engine_http_queue=target.AppEngineHttpQueue( app_engine_routing_override=target.AppEngineRouting( service="service_value" @@ -914,13 +987,14 @@ def test_create_queue( 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 + assert response.type_ == gct_queue.Queue.Type.PULL def test_create_queue_from_dict(): @@ -928,25 +1002,25 @@ def test_create_queue_from_dict(): @pytest.mark.asyncio -async def test_create_queue_async(transport: str = "grpc_asyncio"): +async def test_create_queue_async( + transport: str = "grpc_asyncio", request_type=cloudtasks.CreateQueueRequest +): client = CloudTasksAsyncClient( credentials=credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, # and we are mocking out the actual API, so just send an empty request. - request = cloudtasks.CreateQueueRequest() + request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client._client._transport.create_queue), "__call__" - ) as call: + with mock.patch.object(type(client.transport.create_queue), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( gct_queue.Queue( name="name_value", state=gct_queue.Queue.State.RUNNING, - type=gct_queue.Queue.Type.PULL, + type_=gct_queue.Queue.Type.PULL, ) ) @@ -956,7 +1030,7 @@ async def test_create_queue_async(transport: str = "grpc_asyncio"): assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == request + assert args[0] == cloudtasks.CreateQueueRequest() # Establish that the response is the type that we expect. assert isinstance(response, gct_queue.Queue) @@ -965,7 +1039,12 @@ async def test_create_queue_async(transport: str = "grpc_asyncio"): assert response.state == gct_queue.Queue.State.RUNNING - assert response.type == gct_queue.Queue.Type.PULL + assert response.type_ == gct_queue.Queue.Type.PULL + + +@pytest.mark.asyncio +async def test_create_queue_async_from_dict(): + await test_create_queue_async(request_type=dict) def test_create_queue_field_headers(): @@ -977,7 +1056,7 @@ def test_create_queue_field_headers(): 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: + with mock.patch.object(type(client.transport.create_queue), "__call__") as call: call.return_value = gct_queue.Queue() client.create_queue(request) @@ -1002,9 +1081,7 @@ async def test_create_queue_field_headers_async(): request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client._client._transport.create_queue), "__call__" - ) as call: + 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) @@ -1023,7 +1100,7 @@ def test_create_queue_flattened(): client = CloudTasksClient(credentials=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: + 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() @@ -1061,9 +1138,7 @@ async def test_create_queue_flattened_async(): client = CloudTasksAsyncClient(credentials=credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client._client._transport.create_queue), "__call__" - ) as call: + 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() @@ -1110,12 +1185,12 @@ def test_update_queue( request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client._transport.update_queue), "__call__") as call: + 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( name="name_value", state=gct_queue.Queue.State.RUNNING, - type=gct_queue.Queue.Type.PULL, + type_=gct_queue.Queue.Type.PULL, app_engine_http_queue=target.AppEngineHttpQueue( app_engine_routing_override=target.AppEngineRouting( service="service_value" @@ -1132,13 +1207,14 @@ def test_update_queue( 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 + assert response.type_ == gct_queue.Queue.Type.PULL def test_update_queue_from_dict(): @@ -1146,25 +1222,25 @@ def test_update_queue_from_dict(): @pytest.mark.asyncio -async def test_update_queue_async(transport: str = "grpc_asyncio"): +async def test_update_queue_async( + transport: str = "grpc_asyncio", request_type=cloudtasks.UpdateQueueRequest +): client = CloudTasksAsyncClient( credentials=credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, # and we are mocking out the actual API, so just send an empty request. - request = cloudtasks.UpdateQueueRequest() + request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client._client._transport.update_queue), "__call__" - ) as call: + with mock.patch.object(type(client.transport.update_queue), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( gct_queue.Queue( name="name_value", state=gct_queue.Queue.State.RUNNING, - type=gct_queue.Queue.Type.PULL, + type_=gct_queue.Queue.Type.PULL, ) ) @@ -1174,7 +1250,7 @@ async def test_update_queue_async(transport: str = "grpc_asyncio"): assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == request + assert args[0] == cloudtasks.UpdateQueueRequest() # Establish that the response is the type that we expect. assert isinstance(response, gct_queue.Queue) @@ -1183,7 +1259,12 @@ async def test_update_queue_async(transport: str = "grpc_asyncio"): assert response.state == gct_queue.Queue.State.RUNNING - assert response.type == gct_queue.Queue.Type.PULL + assert response.type_ == gct_queue.Queue.Type.PULL + + +@pytest.mark.asyncio +async def test_update_queue_async_from_dict(): + await test_update_queue_async(request_type=dict) def test_update_queue_field_headers(): @@ -1195,7 +1276,7 @@ def test_update_queue_field_headers(): 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: + with mock.patch.object(type(client.transport.update_queue), "__call__") as call: call.return_value = gct_queue.Queue() client.update_queue(request) @@ -1220,9 +1301,7 @@ async def test_update_queue_field_headers_async(): request.queue.name = "queue.name/value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client._client._transport.update_queue), "__call__" - ) as call: + 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) @@ -1241,7 +1320,7 @@ def test_update_queue_flattened(): client = CloudTasksClient(credentials=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: + 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() @@ -1280,9 +1359,7 @@ async def test_update_queue_flattened_async(): client = CloudTasksAsyncClient(credentials=credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client._client._transport.update_queue), "__call__" - ) as call: + 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() @@ -1330,7 +1407,7 @@ def test_delete_queue( request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client._transport.delete_queue), "__call__") as call: + with mock.patch.object(type(client.transport.delete_queue), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = None @@ -1351,19 +1428,19 @@ def test_delete_queue_from_dict(): @pytest.mark.asyncio -async def test_delete_queue_async(transport: str = "grpc_asyncio"): +async def test_delete_queue_async( + transport: str = "grpc_asyncio", request_type=cloudtasks.DeleteQueueRequest +): client = CloudTasksAsyncClient( credentials=credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, # and we are mocking out the actual API, so just send an empty request. - request = cloudtasks.DeleteQueueRequest() + request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client._client._transport.delete_queue), "__call__" - ) as call: + 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) @@ -1373,12 +1450,17 @@ async def test_delete_queue_async(transport: str = "grpc_asyncio"): assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == request + assert args[0] == cloudtasks.DeleteQueueRequest() # Establish that the response is the type that we expect. assert response is None +@pytest.mark.asyncio +async def test_delete_queue_async_from_dict(): + await test_delete_queue_async(request_type=dict) + + def test_delete_queue_field_headers(): client = CloudTasksClient(credentials=credentials.AnonymousCredentials(),) @@ -1388,7 +1470,7 @@ def test_delete_queue_field_headers(): 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: + with mock.patch.object(type(client.transport.delete_queue), "__call__") as call: call.return_value = None client.delete_queue(request) @@ -1413,9 +1495,7 @@ async def test_delete_queue_field_headers_async(): request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client._client._transport.delete_queue), "__call__" - ) as call: + 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) @@ -1434,7 +1514,7 @@ def test_delete_queue_flattened(): client = CloudTasksClient(credentials=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: + with mock.patch.object(type(client.transport.delete_queue), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = None @@ -1466,9 +1546,7 @@ async def test_delete_queue_flattened_async(): client = CloudTasksAsyncClient(credentials=credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client._client._transport.delete_queue), "__call__" - ) as call: + with mock.patch.object(type(client.transport.delete_queue), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = None @@ -1509,12 +1587,12 @@ def test_purge_queue( request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client._transport.purge_queue), "__call__") as call: + 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( name="name_value", state=queue.Queue.State.RUNNING, - type=queue.Queue.Type.PULL, + type_=queue.Queue.Type.PULL, app_engine_http_queue=target.AppEngineHttpQueue( app_engine_routing_override=target.AppEngineRouting( service="service_value" @@ -1531,13 +1609,14 @@ def test_purge_queue( 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 + assert response.type_ == queue.Queue.Type.PULL def test_purge_queue_from_dict(): @@ -1545,25 +1624,25 @@ def test_purge_queue_from_dict(): @pytest.mark.asyncio -async def test_purge_queue_async(transport: str = "grpc_asyncio"): +async def test_purge_queue_async( + transport: str = "grpc_asyncio", request_type=cloudtasks.PurgeQueueRequest +): client = CloudTasksAsyncClient( credentials=credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, # and we are mocking out the actual API, so just send an empty request. - request = cloudtasks.PurgeQueueRequest() + request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client._client._transport.purge_queue), "__call__" - ) as call: + with mock.patch.object(type(client.transport.purge_queue), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( queue.Queue( name="name_value", state=queue.Queue.State.RUNNING, - type=queue.Queue.Type.PULL, + type_=queue.Queue.Type.PULL, ) ) @@ -1573,7 +1652,7 @@ async def test_purge_queue_async(transport: str = "grpc_asyncio"): assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == request + assert args[0] == cloudtasks.PurgeQueueRequest() # Establish that the response is the type that we expect. assert isinstance(response, queue.Queue) @@ -1582,7 +1661,12 @@ async def test_purge_queue_async(transport: str = "grpc_asyncio"): assert response.state == queue.Queue.State.RUNNING - assert response.type == queue.Queue.Type.PULL + assert response.type_ == queue.Queue.Type.PULL + + +@pytest.mark.asyncio +async def test_purge_queue_async_from_dict(): + await test_purge_queue_async(request_type=dict) def test_purge_queue_field_headers(): @@ -1594,7 +1678,7 @@ def test_purge_queue_field_headers(): 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: + with mock.patch.object(type(client.transport.purge_queue), "__call__") as call: call.return_value = queue.Queue() client.purge_queue(request) @@ -1619,9 +1703,7 @@ async def test_purge_queue_field_headers_async(): request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client._client._transport.purge_queue), "__call__" - ) as call: + 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) @@ -1640,7 +1722,7 @@ def test_purge_queue_flattened(): client = CloudTasksClient(credentials=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: + 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() @@ -1672,9 +1754,7 @@ async def test_purge_queue_flattened_async(): client = CloudTasksAsyncClient(credentials=credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client._client._transport.purge_queue), "__call__" - ) as call: + 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() @@ -1715,12 +1795,12 @@ def test_pause_queue( request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client._transport.pause_queue), "__call__") as call: + 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( name="name_value", state=queue.Queue.State.RUNNING, - type=queue.Queue.Type.PULL, + type_=queue.Queue.Type.PULL, app_engine_http_queue=target.AppEngineHttpQueue( app_engine_routing_override=target.AppEngineRouting( service="service_value" @@ -1737,13 +1817,14 @@ def test_pause_queue( 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 + assert response.type_ == queue.Queue.Type.PULL def test_pause_queue_from_dict(): @@ -1751,25 +1832,25 @@ def test_pause_queue_from_dict(): @pytest.mark.asyncio -async def test_pause_queue_async(transport: str = "grpc_asyncio"): +async def test_pause_queue_async( + transport: str = "grpc_asyncio", request_type=cloudtasks.PauseQueueRequest +): client = CloudTasksAsyncClient( credentials=credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, # and we are mocking out the actual API, so just send an empty request. - request = cloudtasks.PauseQueueRequest() + request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client._client._transport.pause_queue), "__call__" - ) as call: + with mock.patch.object(type(client.transport.pause_queue), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( queue.Queue( name="name_value", state=queue.Queue.State.RUNNING, - type=queue.Queue.Type.PULL, + type_=queue.Queue.Type.PULL, ) ) @@ -1779,7 +1860,7 @@ async def test_pause_queue_async(transport: str = "grpc_asyncio"): assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == request + assert args[0] == cloudtasks.PauseQueueRequest() # Establish that the response is the type that we expect. assert isinstance(response, queue.Queue) @@ -1788,7 +1869,12 @@ async def test_pause_queue_async(transport: str = "grpc_asyncio"): assert response.state == queue.Queue.State.RUNNING - assert response.type == queue.Queue.Type.PULL + assert response.type_ == queue.Queue.Type.PULL + + +@pytest.mark.asyncio +async def test_pause_queue_async_from_dict(): + await test_pause_queue_async(request_type=dict) def test_pause_queue_field_headers(): @@ -1800,7 +1886,7 @@ def test_pause_queue_field_headers(): 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: + with mock.patch.object(type(client.transport.pause_queue), "__call__") as call: call.return_value = queue.Queue() client.pause_queue(request) @@ -1825,9 +1911,7 @@ async def test_pause_queue_field_headers_async(): request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client._client._transport.pause_queue), "__call__" - ) as call: + 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) @@ -1846,7 +1930,7 @@ def test_pause_queue_flattened(): client = CloudTasksClient(credentials=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: + 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() @@ -1878,9 +1962,7 @@ async def test_pause_queue_flattened_async(): client = CloudTasksAsyncClient(credentials=credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client._client._transport.pause_queue), "__call__" - ) as call: + 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() @@ -1921,12 +2003,12 @@ def test_resume_queue( request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client._transport.resume_queue), "__call__") as call: + 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( name="name_value", state=queue.Queue.State.RUNNING, - type=queue.Queue.Type.PULL, + type_=queue.Queue.Type.PULL, app_engine_http_queue=target.AppEngineHttpQueue( app_engine_routing_override=target.AppEngineRouting( service="service_value" @@ -1943,13 +2025,14 @@ def test_resume_queue( 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 + assert response.type_ == queue.Queue.Type.PULL def test_resume_queue_from_dict(): @@ -1957,25 +2040,25 @@ def test_resume_queue_from_dict(): @pytest.mark.asyncio -async def test_resume_queue_async(transport: str = "grpc_asyncio"): +async def test_resume_queue_async( + transport: str = "grpc_asyncio", request_type=cloudtasks.ResumeQueueRequest +): client = CloudTasksAsyncClient( credentials=credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, # and we are mocking out the actual API, so just send an empty request. - request = cloudtasks.ResumeQueueRequest() + request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client._client._transport.resume_queue), "__call__" - ) as call: + with mock.patch.object(type(client.transport.resume_queue), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( queue.Queue( name="name_value", state=queue.Queue.State.RUNNING, - type=queue.Queue.Type.PULL, + type_=queue.Queue.Type.PULL, ) ) @@ -1985,7 +2068,7 @@ async def test_resume_queue_async(transport: str = "grpc_asyncio"): assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == request + assert args[0] == cloudtasks.ResumeQueueRequest() # Establish that the response is the type that we expect. assert isinstance(response, queue.Queue) @@ -1994,7 +2077,12 @@ async def test_resume_queue_async(transport: str = "grpc_asyncio"): assert response.state == queue.Queue.State.RUNNING - assert response.type == queue.Queue.Type.PULL + assert response.type_ == queue.Queue.Type.PULL + + +@pytest.mark.asyncio +async def test_resume_queue_async_from_dict(): + await test_resume_queue_async(request_type=dict) def test_resume_queue_field_headers(): @@ -2006,7 +2094,7 @@ def test_resume_queue_field_headers(): 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: + with mock.patch.object(type(client.transport.resume_queue), "__call__") as call: call.return_value = queue.Queue() client.resume_queue(request) @@ -2031,9 +2119,7 @@ async def test_resume_queue_field_headers_async(): request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client._client._transport.resume_queue), "__call__" - ) as call: + 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) @@ -2052,7 +2138,7 @@ def test_resume_queue_flattened(): client = CloudTasksClient(credentials=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: + 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() @@ -2084,9 +2170,7 @@ async def test_resume_queue_flattened_async(): client = CloudTasksAsyncClient(credentials=credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client._client._transport.resume_queue), "__call__" - ) as call: + 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() @@ -2127,7 +2211,7 @@ def test_get_iam_policy( request = request_type() # 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: + 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",) @@ -2140,6 +2224,7 @@ def test_get_iam_policy( assert args[0] == iam_policy.GetIamPolicyRequest() # Establish that the response is the type that we expect. + assert isinstance(response, policy.Policy) assert response.version == 774 @@ -2152,19 +2237,19 @@ def test_get_iam_policy_from_dict(): @pytest.mark.asyncio -async def test_get_iam_policy_async(transport: str = "grpc_asyncio"): +async def test_get_iam_policy_async( + transport: str = "grpc_asyncio", request_type=iam_policy.GetIamPolicyRequest +): client = CloudTasksAsyncClient( credentials=credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, # and we are mocking out the actual API, so just send an empty request. - request = iam_policy.GetIamPolicyRequest() + request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client._client._transport.get_iam_policy), "__call__" - ) as call: + 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",) @@ -2176,7 +2261,7 @@ async def test_get_iam_policy_async(transport: str = "grpc_asyncio"): assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == request + assert args[0] == iam_policy.GetIamPolicyRequest() # Establish that the response is the type that we expect. assert isinstance(response, policy.Policy) @@ -2186,6 +2271,11 @@ async def test_get_iam_policy_async(transport: str = "grpc_asyncio"): assert response.etag == b"etag_blob" +@pytest.mark.asyncio +async def test_get_iam_policy_async_from_dict(): + await test_get_iam_policy_async(request_type=dict) + + def test_get_iam_policy_field_headers(): client = CloudTasksClient(credentials=credentials.AnonymousCredentials(),) @@ -2195,7 +2285,7 @@ def test_get_iam_policy_field_headers(): 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: + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: call.return_value = policy.Policy() client.get_iam_policy(request) @@ -2220,9 +2310,7 @@ async def test_get_iam_policy_field_headers_async(): request.resource = "resource/value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client._client._transport.get_iam_policy), "__call__" - ) as call: + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy.Policy()) await client.get_iam_policy(request) @@ -2237,10 +2325,10 @@ async def test_get_iam_policy_field_headers_async(): assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] -def test_get_iam_policy_from_dict(): +def test_get_iam_policy_from_dict_foreign(): client = CloudTasksClient(credentials=credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client._transport.get_iam_policy), "__call__") as call: + 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() @@ -2257,7 +2345,7 @@ def test_get_iam_policy_flattened(): client = CloudTasksClient(credentials=credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client._transport.get_iam_policy), "__call__") as call: + 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() @@ -2289,9 +2377,7 @@ async def test_get_iam_policy_flattened_async(): client = CloudTasksAsyncClient(credentials=credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client._client._transport.get_iam_policy), "__call__" - ) as call: + 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() @@ -2332,7 +2418,7 @@ def test_set_iam_policy( 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: + 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",) @@ -2345,6 +2431,7 @@ def test_set_iam_policy( assert args[0] == iam_policy.SetIamPolicyRequest() # Establish that the response is the type that we expect. + assert isinstance(response, policy.Policy) assert response.version == 774 @@ -2357,19 +2444,19 @@ def test_set_iam_policy_from_dict(): @pytest.mark.asyncio -async def test_set_iam_policy_async(transport: str = "grpc_asyncio"): +async def test_set_iam_policy_async( + transport: str = "grpc_asyncio", request_type=iam_policy.SetIamPolicyRequest +): client = CloudTasksAsyncClient( credentials=credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, # and we are mocking out the actual API, so just send an empty request. - request = iam_policy.SetIamPolicyRequest() + request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client._client._transport.set_iam_policy), "__call__" - ) as call: + 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",) @@ -2381,7 +2468,7 @@ async def test_set_iam_policy_async(transport: str = "grpc_asyncio"): assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == request + assert args[0] == iam_policy.SetIamPolicyRequest() # Establish that the response is the type that we expect. assert isinstance(response, policy.Policy) @@ -2391,6 +2478,11 @@ async def test_set_iam_policy_async(transport: str = "grpc_asyncio"): assert response.etag == b"etag_blob" +@pytest.mark.asyncio +async def test_set_iam_policy_async_from_dict(): + await test_set_iam_policy_async(request_type=dict) + + def test_set_iam_policy_field_headers(): client = CloudTasksClient(credentials=credentials.AnonymousCredentials(),) @@ -2400,7 +2492,7 @@ def test_set_iam_policy_field_headers(): 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: + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: call.return_value = policy.Policy() client.set_iam_policy(request) @@ -2425,9 +2517,7 @@ async def test_set_iam_policy_field_headers_async(): request.resource = "resource/value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client._client._transport.set_iam_policy), "__call__" - ) as call: + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy.Policy()) await client.set_iam_policy(request) @@ -2442,10 +2532,10 @@ async def test_set_iam_policy_field_headers_async(): assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] -def test_set_iam_policy_from_dict(): +def test_set_iam_policy_from_dict_foreign(): client = CloudTasksClient(credentials=credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client._transport.set_iam_policy), "__call__") as call: + 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() @@ -2462,7 +2552,7 @@ def test_set_iam_policy_flattened(): client = CloudTasksClient(credentials=credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client._transport.set_iam_policy), "__call__") as call: + 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() @@ -2494,9 +2584,7 @@ async def test_set_iam_policy_flattened_async(): client = CloudTasksAsyncClient(credentials=credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client._client._transport.set_iam_policy), "__call__" - ) as call: + 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() @@ -2538,7 +2626,7 @@ def test_test_iam_permissions( # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client._transport.test_iam_permissions), "__call__" + type(client.transport.test_iam_permissions), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = iam_policy.TestIamPermissionsResponse( @@ -2554,6 +2642,7 @@ def test_test_iam_permissions( assert args[0] == iam_policy.TestIamPermissionsRequest() # Establish that the response is the type that we expect. + assert isinstance(response, iam_policy.TestIamPermissionsResponse) assert response.permissions == ["permissions_value"] @@ -2564,18 +2653,20 @@ def test_test_iam_permissions_from_dict(): @pytest.mark.asyncio -async def test_test_iam_permissions_async(transport: str = "grpc_asyncio"): +async def test_test_iam_permissions_async( + transport: str = "grpc_asyncio", request_type=iam_policy.TestIamPermissionsRequest +): client = CloudTasksAsyncClient( credentials=credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, # and we are mocking out the actual API, so just send an empty request. - request = iam_policy.TestIamPermissionsRequest() + request = request_type() # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client._client._transport.test_iam_permissions), "__call__" + type(client.transport.test_iam_permissions), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( @@ -2588,7 +2679,7 @@ async def test_test_iam_permissions_async(transport: str = "grpc_asyncio"): assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == request + assert args[0] == iam_policy.TestIamPermissionsRequest() # Establish that the response is the type that we expect. assert isinstance(response, iam_policy.TestIamPermissionsResponse) @@ -2596,6 +2687,11 @@ async def test_test_iam_permissions_async(transport: str = "grpc_asyncio"): assert response.permissions == ["permissions_value"] +@pytest.mark.asyncio +async def test_test_iam_permissions_async_from_dict(): + await test_test_iam_permissions_async(request_type=dict) + + def test_test_iam_permissions_field_headers(): client = CloudTasksClient(credentials=credentials.AnonymousCredentials(),) @@ -2606,7 +2702,7 @@ def test_test_iam_permissions_field_headers(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client._transport.test_iam_permissions), "__call__" + type(client.transport.test_iam_permissions), "__call__" ) as call: call.return_value = iam_policy.TestIamPermissionsResponse() @@ -2633,7 +2729,7 @@ async def test_test_iam_permissions_field_headers_async(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client._client._transport.test_iam_permissions), "__call__" + type(client.transport.test_iam_permissions), "__call__" ) as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( iam_policy.TestIamPermissionsResponse() @@ -2651,11 +2747,11 @@ async def test_test_iam_permissions_field_headers_async(): assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] -def test_test_iam_permissions_from_dict(): +def test_test_iam_permissions_from_dict_foreign(): client = CloudTasksClient(credentials=credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client._transport.test_iam_permissions), "__call__" + type(client.transport.test_iam_permissions), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = iam_policy.TestIamPermissionsResponse() @@ -2674,7 +2770,7 @@ def test_test_iam_permissions_flattened(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client._transport.test_iam_permissions), "__call__" + type(client.transport.test_iam_permissions), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = iam_policy.TestIamPermissionsResponse() @@ -2714,7 +2810,7 @@ async def test_test_iam_permissions_flattened_async(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client._client._transport.test_iam_permissions), "__call__" + type(client.transport.test_iam_permissions), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = iam_policy.TestIamPermissionsResponse() @@ -2762,7 +2858,7 @@ def test_list_tasks(transport: str = "grpc", request_type=cloudtasks.ListTasksRe request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client._transport.list_tasks), "__call__") as call: + 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( next_page_token="next_page_token_value", @@ -2777,6 +2873,7 @@ def test_list_tasks(transport: str = "grpc", request_type=cloudtasks.ListTasksRe 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" @@ -2787,19 +2884,19 @@ def test_list_tasks_from_dict(): @pytest.mark.asyncio -async def test_list_tasks_async(transport: str = "grpc_asyncio"): +async def test_list_tasks_async( + transport: str = "grpc_asyncio", request_type=cloudtasks.ListTasksRequest +): client = CloudTasksAsyncClient( credentials=credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, # and we are mocking out the actual API, so just send an empty request. - request = cloudtasks.ListTasksRequest() + request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client._client._transport.list_tasks), "__call__" - ) as call: + with mock.patch.object(type(client.transport.list_tasks), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( cloudtasks.ListTasksResponse(next_page_token="next_page_token_value",) @@ -2811,7 +2908,7 @@ async def test_list_tasks_async(transport: str = "grpc_asyncio"): assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == request + assert args[0] == cloudtasks.ListTasksRequest() # Establish that the response is the type that we expect. assert isinstance(response, pagers.ListTasksAsyncPager) @@ -2819,6 +2916,11 @@ async def test_list_tasks_async(transport: str = "grpc_asyncio"): assert response.next_page_token == "next_page_token_value" +@pytest.mark.asyncio +async def test_list_tasks_async_from_dict(): + await test_list_tasks_async(request_type=dict) + + def test_list_tasks_field_headers(): client = CloudTasksClient(credentials=credentials.AnonymousCredentials(),) @@ -2828,7 +2930,7 @@ def test_list_tasks_field_headers(): 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: + with mock.patch.object(type(client.transport.list_tasks), "__call__") as call: call.return_value = cloudtasks.ListTasksResponse() client.list_tasks(request) @@ -2853,9 +2955,7 @@ async def test_list_tasks_field_headers_async(): request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client._client._transport.list_tasks), "__call__" - ) as call: + with mock.patch.object(type(client.transport.list_tasks), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( cloudtasks.ListTasksResponse() ) @@ -2876,7 +2976,7 @@ def test_list_tasks_flattened(): client = CloudTasksClient(credentials=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: + 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() @@ -2908,9 +3008,7 @@ async def test_list_tasks_flattened_async(): client = CloudTasksAsyncClient(credentials=credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client._client._transport.list_tasks), "__call__" - ) as call: + 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() @@ -2945,7 +3043,7 @@ def test_list_tasks_pager(): client = CloudTasksClient(credentials=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: + with mock.patch.object(type(client.transport.list_tasks), "__call__") as call: # Set the response to a series of pages. call.side_effect = ( cloudtasks.ListTasksResponse( @@ -2974,7 +3072,7 @@ def test_list_tasks_pages(): client = CloudTasksClient(credentials=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: + with mock.patch.object(type(client.transport.list_tasks), "__call__") as call: # Set the response to a series of pages. call.side_effect = ( cloudtasks.ListTasksResponse( @@ -2996,9 +3094,7 @@ async def test_list_tasks_async_pager(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client._client._transport.list_tasks), - "__call__", - new_callable=mock.AsyncMock, + type(client.transport.list_tasks), "__call__", new_callable=mock.AsyncMock ) as call: # Set the response to a series of pages. call.side_effect = ( @@ -3026,9 +3122,7 @@ async def test_list_tasks_async_pages(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client._client._transport.list_tasks), - "__call__", - new_callable=mock.AsyncMock, + type(client.transport.list_tasks), "__call__", new_callable=mock.AsyncMock ) as call: # Set the response to a series of pages. call.side_effect = ( @@ -3057,7 +3151,7 @@ def test_get_task(transport: str = "grpc", request_type=cloudtasks.GetTaskReques request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client._transport.get_task), "__call__") as call: + 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( name="name_value", @@ -3078,6 +3172,7 @@ def test_get_task(transport: str = "grpc", request_type=cloudtasks.GetTaskReques 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" @@ -3094,19 +3189,19 @@ def test_get_task_from_dict(): @pytest.mark.asyncio -async def test_get_task_async(transport: str = "grpc_asyncio"): +async def test_get_task_async( + transport: str = "grpc_asyncio", request_type=cloudtasks.GetTaskRequest +): client = CloudTasksAsyncClient( credentials=credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, # and we are mocking out the actual API, so just send an empty request. - request = cloudtasks.GetTaskRequest() + request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client._client._transport.get_task), "__call__" - ) as call: + with mock.patch.object(type(client.transport.get_task), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( task.Task( @@ -3123,7 +3218,7 @@ async def test_get_task_async(transport: str = "grpc_asyncio"): assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == request + assert args[0] == cloudtasks.GetTaskRequest() # Establish that the response is the type that we expect. assert isinstance(response, task.Task) @@ -3137,6 +3232,11 @@ async def test_get_task_async(transport: str = "grpc_asyncio"): assert response.view == task.Task.View.BASIC +@pytest.mark.asyncio +async def test_get_task_async_from_dict(): + await test_get_task_async(request_type=dict) + + def test_get_task_field_headers(): client = CloudTasksClient(credentials=credentials.AnonymousCredentials(),) @@ -3146,7 +3246,7 @@ def test_get_task_field_headers(): 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: + with mock.patch.object(type(client.transport.get_task), "__call__") as call: call.return_value = task.Task() client.get_task(request) @@ -3171,9 +3271,7 @@ async def test_get_task_field_headers_async(): request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client._client._transport.get_task), "__call__" - ) as call: + 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) @@ -3192,7 +3290,7 @@ def test_get_task_flattened(): client = CloudTasksClient(credentials=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: + 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() @@ -3224,9 +3322,7 @@ async def test_get_task_flattened_async(): client = CloudTasksAsyncClient(credentials=credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client._client._transport.get_task), "__call__" - ) as call: + 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() @@ -3267,7 +3363,7 @@ def test_create_task( request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client._transport.create_task), "__call__") as call: + 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( name="name_value", @@ -3288,6 +3384,7 @@ def test_create_task( 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" @@ -3304,19 +3401,19 @@ def test_create_task_from_dict(): @pytest.mark.asyncio -async def test_create_task_async(transport: str = "grpc_asyncio"): +async def test_create_task_async( + transport: str = "grpc_asyncio", request_type=cloudtasks.CreateTaskRequest +): client = CloudTasksAsyncClient( credentials=credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, # and we are mocking out the actual API, so just send an empty request. - request = cloudtasks.CreateTaskRequest() + request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client._client._transport.create_task), "__call__" - ) as call: + with mock.patch.object(type(client.transport.create_task), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( gct_task.Task( @@ -3333,7 +3430,7 @@ async def test_create_task_async(transport: str = "grpc_asyncio"): assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == request + assert args[0] == cloudtasks.CreateTaskRequest() # Establish that the response is the type that we expect. assert isinstance(response, gct_task.Task) @@ -3347,6 +3444,11 @@ async def test_create_task_async(transport: str = "grpc_asyncio"): assert response.view == gct_task.Task.View.BASIC +@pytest.mark.asyncio +async def test_create_task_async_from_dict(): + await test_create_task_async(request_type=dict) + + def test_create_task_field_headers(): client = CloudTasksClient(credentials=credentials.AnonymousCredentials(),) @@ -3356,7 +3458,7 @@ def test_create_task_field_headers(): 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: + with mock.patch.object(type(client.transport.create_task), "__call__") as call: call.return_value = gct_task.Task() client.create_task(request) @@ -3381,9 +3483,7 @@ async def test_create_task_field_headers_async(): request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client._client._transport.create_task), "__call__" - ) as call: + 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) @@ -3402,7 +3502,7 @@ def test_create_task_flattened(): client = CloudTasksClient(credentials=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: + 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() @@ -3440,9 +3540,7 @@ async def test_create_task_flattened_async(): client = CloudTasksAsyncClient(credentials=credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client._client._transport.create_task), "__call__" - ) as call: + 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() @@ -3489,7 +3587,7 @@ def test_delete_task( request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client._transport.delete_task), "__call__") as call: + with mock.patch.object(type(client.transport.delete_task), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = None @@ -3510,19 +3608,19 @@ def test_delete_task_from_dict(): @pytest.mark.asyncio -async def test_delete_task_async(transport: str = "grpc_asyncio"): +async def test_delete_task_async( + transport: str = "grpc_asyncio", request_type=cloudtasks.DeleteTaskRequest +): client = CloudTasksAsyncClient( credentials=credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, # and we are mocking out the actual API, so just send an empty request. - request = cloudtasks.DeleteTaskRequest() + request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client._client._transport.delete_task), "__call__" - ) as call: + 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) @@ -3532,12 +3630,17 @@ async def test_delete_task_async(transport: str = "grpc_asyncio"): assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == request + assert args[0] == cloudtasks.DeleteTaskRequest() # Establish that the response is the type that we expect. assert response is None +@pytest.mark.asyncio +async def test_delete_task_async_from_dict(): + await test_delete_task_async(request_type=dict) + + def test_delete_task_field_headers(): client = CloudTasksClient(credentials=credentials.AnonymousCredentials(),) @@ -3547,7 +3650,7 @@ def test_delete_task_field_headers(): 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: + with mock.patch.object(type(client.transport.delete_task), "__call__") as call: call.return_value = None client.delete_task(request) @@ -3572,9 +3675,7 @@ async def test_delete_task_field_headers_async(): request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client._client._transport.delete_task), "__call__" - ) as call: + 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) @@ -3593,7 +3694,7 @@ def test_delete_task_flattened(): client = CloudTasksClient(credentials=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: + with mock.patch.object(type(client.transport.delete_task), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = None @@ -3625,9 +3726,7 @@ async def test_delete_task_flattened_async(): client = CloudTasksAsyncClient(credentials=credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client._client._transport.delete_task), "__call__" - ) as call: + with mock.patch.object(type(client.transport.delete_task), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = None @@ -3666,7 +3765,7 @@ def test_run_task(transport: str = "grpc", request_type=cloudtasks.RunTaskReques request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client._transport.run_task), "__call__") as call: + 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( name="name_value", @@ -3687,6 +3786,7 @@ def test_run_task(transport: str = "grpc", request_type=cloudtasks.RunTaskReques 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" @@ -3703,19 +3803,19 @@ def test_run_task_from_dict(): @pytest.mark.asyncio -async def test_run_task_async(transport: str = "grpc_asyncio"): +async def test_run_task_async( + transport: str = "grpc_asyncio", request_type=cloudtasks.RunTaskRequest +): client = CloudTasksAsyncClient( credentials=credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, # and we are mocking out the actual API, so just send an empty request. - request = cloudtasks.RunTaskRequest() + request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client._client._transport.run_task), "__call__" - ) as call: + with mock.patch.object(type(client.transport.run_task), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( task.Task( @@ -3732,7 +3832,7 @@ async def test_run_task_async(transport: str = "grpc_asyncio"): assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == request + assert args[0] == cloudtasks.RunTaskRequest() # Establish that the response is the type that we expect. assert isinstance(response, task.Task) @@ -3746,6 +3846,11 @@ async def test_run_task_async(transport: str = "grpc_asyncio"): assert response.view == task.Task.View.BASIC +@pytest.mark.asyncio +async def test_run_task_async_from_dict(): + await test_run_task_async(request_type=dict) + + def test_run_task_field_headers(): client = CloudTasksClient(credentials=credentials.AnonymousCredentials(),) @@ -3755,7 +3860,7 @@ def test_run_task_field_headers(): 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: + with mock.patch.object(type(client.transport.run_task), "__call__") as call: call.return_value = task.Task() client.run_task(request) @@ -3780,9 +3885,7 @@ async def test_run_task_field_headers_async(): request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client._client._transport.run_task), "__call__" - ) as call: + 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) @@ -3801,7 +3904,7 @@ def test_run_task_flattened(): client = CloudTasksClient(credentials=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: + 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() @@ -3833,9 +3936,7 @@ async def test_run_task_flattened_async(): client = CloudTasksAsyncClient(credentials=credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client._client._transport.run_task), "__call__" - ) as call: + 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() @@ -3900,7 +4001,7 @@ def test_transport_instance(): credentials=credentials.AnonymousCredentials(), ) client = CloudTasksClient(transport=transport) - assert client._transport is transport + assert client.transport is transport def test_transport_get_channel(): @@ -3918,10 +4019,22 @@ def test_transport_get_channel(): assert channel +@pytest.mark.parametrize( + "transport_class", + [transports.CloudTasksGrpcTransport, transports.CloudTasksGrpcAsyncIOTransport], +) +def test_transport_adc(transport_class): + # Test default credentials are used if not provided. + with mock.patch.object(auth, "default") as adc: + adc.return_value = (credentials.AnonymousCredentials(), None) + transport_class() + adc.assert_called_once() + + def test_transport_grpc_default(): # A client should use the gRPC transport by default. client = CloudTasksClient(credentials=credentials.AnonymousCredentials(),) - assert isinstance(client._transport, transports.CloudTasksGrpcTransport,) + assert isinstance(client.transport, transports.CloudTasksGrpcTransport,) def test_cloud_tasks_base_transport_error(): @@ -3987,6 +4100,17 @@ 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( + "google.cloud.tasks_v2beta3.services.cloud_tasks.transports.CloudTasksTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + adc.return_value = (credentials.AnonymousCredentials(), None) + transport = transports.CloudTasksTransport() + adc.assert_called_once() + + def test_cloud_tasks_auth_adc(): # If no credentials are provided, we should use ADC credentials. with mock.patch.object(auth, "default") as adc: @@ -4019,7 +4143,7 @@ def test_cloud_tasks_host_no_port(): api_endpoint="cloudtasks.googleapis.com" ), ) - assert client._transport._host == "cloudtasks.googleapis.com:443" + assert client.transport._host == "cloudtasks.googleapis.com:443" def test_cloud_tasks_host_with_port(): @@ -4029,192 +4153,143 @@ def test_cloud_tasks_host_with_port(): api_endpoint="cloudtasks.googleapis.com:8000" ), ) - assert client._transport._host == "cloudtasks.googleapis.com:8000" + assert client.transport._host == "cloudtasks.googleapis.com:8000" def test_cloud_tasks_grpc_transport_channel(): channel = grpc.insecure_channel("http://localhost/") - # Check that if channel is provided, mtls endpoint and client_cert_source - # won't be used. - callback = mock.MagicMock() + # Check that channel is used if provided. transport = transports.CloudTasksGrpcTransport( - host="squid.clam.whelk", - channel=channel, - api_mtls_endpoint="mtls.squid.clam.whelk", - client_cert_source=callback, + host="squid.clam.whelk", channel=channel, ) assert transport.grpc_channel == channel assert transport._host == "squid.clam.whelk:443" - assert not callback.called + assert transport._ssl_channel_credentials == None def test_cloud_tasks_grpc_asyncio_transport_channel(): channel = aio.insecure_channel("http://localhost/") - # Check that if channel is provided, mtls endpoint and client_cert_source - # won't be used. - callback = mock.MagicMock() + # Check that channel is used if provided. transport = transports.CloudTasksGrpcAsyncIOTransport( - host="squid.clam.whelk", - channel=channel, - api_mtls_endpoint="mtls.squid.clam.whelk", - client_cert_source=callback, + host="squid.clam.whelk", channel=channel, ) assert transport.grpc_channel == channel assert transport._host == "squid.clam.whelk:443" - assert not callback.called - - -@mock.patch("grpc.ssl_channel_credentials", autospec=True) -@mock.patch("google.api_core.grpc_helpers.create_channel", autospec=True) -def test_cloud_tasks_grpc_transport_channel_mtls_with_client_cert_source( - grpc_create_channel, grpc_ssl_channel_cred -): - # Check that if channel is None, but api_mtls_endpoint and client_cert_source - # are provided, then a mTLS channel will be created. - mock_cred = mock.Mock() - - mock_ssl_cred = mock.Mock() - grpc_ssl_channel_cred.return_value = mock_ssl_cred - - mock_grpc_channel = mock.Mock() - grpc_create_channel.return_value = mock_grpc_channel - - transport = transports.CloudTasksGrpcTransport( - host="squid.clam.whelk", - credentials=mock_cred, - api_mtls_endpoint="mtls.squid.clam.whelk", - client_cert_source=client_cert_source_callback, - ) - grpc_ssl_channel_cred.assert_called_once_with( - certificate_chain=b"cert bytes", private_key=b"key bytes" - ) - grpc_create_channel.assert_called_once_with( - "mtls.squid.clam.whelk:443", - credentials=mock_cred, - credentials_file=None, - scopes=("https://www.googleapis.com/auth/cloud-platform",), - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - ) - assert transport.grpc_channel == mock_grpc_channel - - -@mock.patch("grpc.ssl_channel_credentials", autospec=True) -@mock.patch("google.api_core.grpc_helpers_async.create_channel", autospec=True) -def test_cloud_tasks_grpc_asyncio_transport_channel_mtls_with_client_cert_source( - grpc_create_channel, grpc_ssl_channel_cred -): - # Check that if channel is None, but api_mtls_endpoint and client_cert_source - # are provided, then a mTLS channel will be created. - mock_cred = mock.Mock() - - mock_ssl_cred = mock.Mock() - grpc_ssl_channel_cred.return_value = mock_ssl_cred - - mock_grpc_channel = mock.Mock() - grpc_create_channel.return_value = mock_grpc_channel - - transport = transports.CloudTasksGrpcAsyncIOTransport( - host="squid.clam.whelk", - credentials=mock_cred, - api_mtls_endpoint="mtls.squid.clam.whelk", - client_cert_source=client_cert_source_callback, - ) - grpc_ssl_channel_cred.assert_called_once_with( - certificate_chain=b"cert bytes", private_key=b"key bytes" - ) - grpc_create_channel.assert_called_once_with( - "mtls.squid.clam.whelk:443", - credentials=mock_cred, - credentials_file=None, - scopes=("https://www.googleapis.com/auth/cloud-platform",), - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - ) - assert transport.grpc_channel == mock_grpc_channel + assert transport._ssl_channel_credentials == None @pytest.mark.parametrize( - "api_mtls_endpoint", ["mtls.squid.clam.whelk", "mtls.squid.clam.whelk:443"] + "transport_class", + [transports.CloudTasksGrpcTransport, transports.CloudTasksGrpcAsyncIOTransport], ) -@mock.patch("google.api_core.grpc_helpers.create_channel", autospec=True) -def test_cloud_tasks_grpc_transport_channel_mtls_with_adc( - grpc_create_channel, api_mtls_endpoint -): - # Check that if channel and client_cert_source are None, but api_mtls_endpoint - # is provided, then a mTLS channel will be created with SSL ADC. - mock_grpc_channel = mock.Mock() - grpc_create_channel.return_value = mock_grpc_channel - - # Mock google.auth.transport.grpc.SslCredentials class. - mock_ssl_cred = mock.Mock() - with mock.patch.multiple( - "google.auth.transport.grpc.SslCredentials", - __init__=mock.Mock(return_value=None), - ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), - ): - mock_cred = mock.Mock() - transport = transports.CloudTasksGrpcTransport( - host="squid.clam.whelk", - credentials=mock_cred, - api_mtls_endpoint=api_mtls_endpoint, - client_cert_source=None, - ) - grpc_create_channel.assert_called_once_with( - "mtls.squid.clam.whelk:443", - credentials=mock_cred, - credentials_file=None, - scopes=("https://www.googleapis.com/auth/cloud-platform",), - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - ) - assert transport.grpc_channel == mock_grpc_channel +def test_cloud_tasks_transport_channel_mtls_with_client_cert_source(transport_class): + with mock.patch( + "grpc.ssl_channel_credentials", autospec=True + ) as grpc_ssl_channel_cred: + with mock.patch.object( + transport_class, "create_channel", autospec=True + ) as grpc_create_channel: + mock_ssl_cred = mock.Mock() + grpc_ssl_channel_cred.return_value = mock_ssl_cred + + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + + cred = credentials.AnonymousCredentials() + with pytest.warns(DeprecationWarning): + with mock.patch.object(auth, "default") as adc: + adc.return_value = (cred, None) + transport = transport_class( + host="squid.clam.whelk", + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=client_cert_source_callback, + ) + adc.assert_called_once() + + grpc_ssl_channel_cred.assert_called_once_with( + certificate_chain=b"cert bytes", private_key=b"key bytes" + ) + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=("https://www.googleapis.com/auth/cloud-platform",), + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + ) + assert transport.grpc_channel == mock_grpc_channel + assert transport._ssl_channel_credentials == mock_ssl_cred @pytest.mark.parametrize( - "api_mtls_endpoint", ["mtls.squid.clam.whelk", "mtls.squid.clam.whelk:443"] + "transport_class", + [transports.CloudTasksGrpcTransport, transports.CloudTasksGrpcAsyncIOTransport], ) -@mock.patch("google.api_core.grpc_helpers_async.create_channel", autospec=True) -def test_cloud_tasks_grpc_asyncio_transport_channel_mtls_with_adc( - grpc_create_channel, api_mtls_endpoint -): - # Check that if channel and client_cert_source are None, but api_mtls_endpoint - # is provided, then a mTLS channel will be created with SSL ADC. - mock_grpc_channel = mock.Mock() - grpc_create_channel.return_value = mock_grpc_channel - - # Mock google.auth.transport.grpc.SslCredentials class. +def test_cloud_tasks_transport_channel_mtls_with_adc(transport_class): mock_ssl_cred = mock.Mock() with mock.patch.multiple( "google.auth.transport.grpc.SslCredentials", __init__=mock.Mock(return_value=None), ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), ): - mock_cred = mock.Mock() - transport = transports.CloudTasksGrpcAsyncIOTransport( - host="squid.clam.whelk", - credentials=mock_cred, - api_mtls_endpoint=api_mtls_endpoint, - client_cert_source=None, - ) - grpc_create_channel.assert_called_once_with( - "mtls.squid.clam.whelk:443", - credentials=mock_cred, - credentials_file=None, - scopes=("https://www.googleapis.com/auth/cloud-platform",), - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - ) - assert transport.grpc_channel == mock_grpc_channel + with mock.patch.object( + transport_class, "create_channel", autospec=True + ) as grpc_create_channel: + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + mock_cred = mock.Mock() + + with pytest.warns(DeprecationWarning): + transport = transport_class( + host="squid.clam.whelk", + credentials=mock_cred, + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=None, + ) + + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=mock_cred, + credentials_file=None, + scopes=("https://www.googleapis.com/auth/cloud-platform",), + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + ) + assert transport.grpc_channel == mock_grpc_channel -def test_task_path(): +def test_queue_path(): project = "squid" location = "clam" queue = "whelk" - task = "octopus" + + expected = "projects/{project}/locations/{location}/queues/{queue}".format( + project=project, location=location, queue=queue, + ) + actual = CloudTasksClient.queue_path(project, location, queue) + assert expected == actual + + +def test_parse_queue_path(): + expected = { + "project": "octopus", + "location": "oyster", + "queue": "nudibranch", + } + path = CloudTasksClient.queue_path(**expected) + + # Check that the path construction is reversible. + actual = CloudTasksClient.parse_queue_path(path) + assert expected == actual + + +def test_task_path(): + project = "cuttlefish" + location = "mussel" + queue = "winkle" + task = "nautilus" expected = "projects/{project}/locations/{location}/queues/{queue}/tasks/{task}".format( project=project, location=location, queue=queue, task=task, @@ -4225,10 +4300,10 @@ def test_task_path(): def test_parse_task_path(): expected = { - "project": "oyster", - "location": "nudibranch", - "queue": "cuttlefish", - "task": "mussel", + "project": "scallop", + "location": "abalone", + "queue": "squid", + "task": "clam", } path = CloudTasksClient.task_path(**expected) @@ -4237,28 +4312,104 @@ def test_parse_task_path(): assert expected == actual -def test_queue_path(): - project = "squid" - location = "clam" - queue = "whelk" +def test_common_billing_account_path(): + billing_account = "whelk" - expected = "projects/{project}/locations/{location}/queues/{queue}".format( - project=project, location=location, queue=queue, + expected = "billingAccounts/{billing_account}".format( + billing_account=billing_account, ) - actual = CloudTasksClient.queue_path(project, location, queue) + actual = CloudTasksClient.common_billing_account_path(billing_account) assert expected == actual -def test_parse_queue_path(): +def test_parse_common_billing_account_path(): expected = { - "project": "octopus", - "location": "oyster", - "queue": "nudibranch", + "billing_account": "octopus", } - path = CloudTasksClient.queue_path(**expected) + path = CloudTasksClient.common_billing_account_path(**expected) # Check that the path construction is reversible. - actual = CloudTasksClient.parse_queue_path(path) + actual = CloudTasksClient.parse_common_billing_account_path(path) + assert expected == actual + + +def test_common_folder_path(): + folder = "oyster" + + expected = "folders/{folder}".format(folder=folder,) + actual = CloudTasksClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "nudibranch", + } + path = CloudTasksClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = CloudTasksClient.parse_common_folder_path(path) + assert expected == actual + + +def test_common_organization_path(): + organization = "cuttlefish" + + expected = "organizations/{organization}".format(organization=organization,) + actual = CloudTasksClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "mussel", + } + path = CloudTasksClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = CloudTasksClient.parse_common_organization_path(path) + assert expected == actual + + +def test_common_project_path(): + project = "winkle" + + expected = "projects/{project}".format(project=project,) + actual = CloudTasksClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "nautilus", + } + path = CloudTasksClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = CloudTasksClient.parse_common_project_path(path) + assert expected == actual + + +def test_common_location_path(): + project = "scallop" + location = "abalone" + + expected = "projects/{project}/locations/{location}".format( + project=project, location=location, + ) + actual = CloudTasksClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "squid", + "location": "clam", + } + path = CloudTasksClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = CloudTasksClient.parse_common_location_path(path) assert expected == actual