From 2c0791682d0ca4f62f3649c5e408176346adc7a1 Mon Sep 17 00:00:00 2001 From: Yoshi Automation Bot Date: Mon, 16 Nov 2020 15:19:59 -0800 Subject: [PATCH] feat: add common resource helpers, expose client transport (#33) * changes without context autosynth cannot find the source of changes triggered by earlier changes in this repository, or by version upgrades to tools such as linters. * chore: regen Co-authored-by: Bu Sun Kim --- .github/snippet-bot.yml | 0 .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 +- CODE_OF_CONDUCT.md | 123 ++- CONTRIBUTING.rst | 19 - docs/accessapproval_v1/types.rst | 1 + docs/conf.py | 4 +- .../services/access_approval/async_client.py | 98 ++- .../services/access_approval/client.py | 169 +++- .../access_approval/transports/base.py | 30 +- .../access_approval/transports/grpc.py | 72 +- .../transports/grpc_asyncio.py | 65 +- .../accessapproval_v1/types/accessapproval.py | 22 +- noxfile.py | 10 +- scripts/decrypt-secrets.sh | 15 +- scripts/fixup_accessapproval_v1_keywords.py | 1 + synth.metadata | 12 +- .../accessapproval_v1/test_access_approval.py | 813 +++++++++++------- 24 files changed, 1069 insertions(+), 521 deletions(-) create mode 100644 .github/snippet-bot.yml create mode 100755 .kokoro/populate-secrets.sh diff --git a/.github/snippet-bot.yml b/.github/snippet-bot.yml new file mode 100644 index 0000000..e69de29 diff --git a/.kokoro/docs/common.cfg b/.kokoro/docs/common.cfg index 53a5af0..d3d407c 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 0000000..f525142 --- /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 5362b3d..925df83 100644 --- a/.kokoro/release/common.cfg +++ b/.kokoro/release/common.cfg @@ -23,42 +23,18 @@ env_vars: { value: "github/python-access-approval/.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 9785dd6..a066195 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-access-approval/.kokoro/test-samples.sh" diff --git a/.kokoro/samples/python3.7/common.cfg b/.kokoro/samples/python3.7/common.cfg index e10f42b..a80b8eb 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-access-approval/.kokoro/test-samples.sh" diff --git a/.kokoro/samples/python3.8/common.cfg b/.kokoro/samples/python3.8/common.cfg index 5e4328a..45627bc 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-access-approval/.kokoro/test-samples.sh" diff --git a/.kokoro/test-samples.sh b/.kokoro/test-samples.sh index 05f32d8..1f76184 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 e8c4251..f39236e 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/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md index b3d1f60..039f436 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 064c262..4aef11c 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? ***************************************** diff --git a/docs/accessapproval_v1/types.rst b/docs/accessapproval_v1/types.rst index a7a0abb..4876adf 100644 --- a/docs/accessapproval_v1/types.rst +++ b/docs/accessapproval_v1/types.rst @@ -3,3 +3,4 @@ Types for Google Cloud Accessapproval v1 API .. automodule:: google.cloud.accessapproval_v1.types :members: + :show-inheritance: diff --git a/docs/conf.py b/docs/conf.py index ba97aa4..ba0a683 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", @@ -348,6 +349,7 @@ "google-auth": ("https://google-auth.readthedocs.io/en/stable", None), "google.api_core": ("https://googleapis.dev/python/google-api-core/latest/", None,), "grpc": ("https://grpc.io/grpc/python/", None), + "proto-plus": ("https://proto-plus-python.readthedocs.io/en/latest/", None), } diff --git a/google/cloud/accessapproval_v1/services/access_approval/async_client.py b/google/cloud/accessapproval_v1/services/access_approval/async_client.py index 17d0fed..657df52 100644 --- a/google/cloud/accessapproval_v1/services/access_approval/async_client.py +++ b/google/cloud/accessapproval_v1/services/access_approval/async_client.py @@ -33,7 +33,7 @@ from google.protobuf import field_mask_pb2 as field_mask # type: ignore from google.protobuf import timestamp_pb2 as timestamp # type: ignore -from .transports.base import AccessApprovalTransport +from .transports.base import AccessApprovalTransport, DEFAULT_CLIENT_INFO from .transports.grpc_asyncio import AccessApprovalGrpcAsyncIOTransport from .client import AccessApprovalClient @@ -81,9 +81,47 @@ class AccessApprovalAsyncClient: DEFAULT_ENDPOINT = AccessApprovalClient.DEFAULT_ENDPOINT DEFAULT_MTLS_ENDPOINT = AccessApprovalClient.DEFAULT_MTLS_ENDPOINT + common_billing_account_path = staticmethod( + AccessApprovalClient.common_billing_account_path + ) + parse_common_billing_account_path = staticmethod( + AccessApprovalClient.parse_common_billing_account_path + ) + + common_folder_path = staticmethod(AccessApprovalClient.common_folder_path) + parse_common_folder_path = staticmethod( + AccessApprovalClient.parse_common_folder_path + ) + + common_organization_path = staticmethod( + AccessApprovalClient.common_organization_path + ) + parse_common_organization_path = staticmethod( + AccessApprovalClient.parse_common_organization_path + ) + + common_project_path = staticmethod(AccessApprovalClient.common_project_path) + parse_common_project_path = staticmethod( + AccessApprovalClient.parse_common_project_path + ) + + common_location_path = staticmethod(AccessApprovalClient.common_location_path) + parse_common_location_path = staticmethod( + AccessApprovalClient.parse_common_location_path + ) + from_service_account_file = AccessApprovalClient.from_service_account_file from_service_account_json = from_service_account_file + @property + def transport(self) -> AccessApprovalTransport: + """Return the transport used by the client instance. + + Returns: + AccessApprovalTransport: The transport used by the client instance. + """ + return self._client.transport + get_transport_class = functools.partial( type(AccessApprovalClient).get_transport_class, type(AccessApprovalClient) ) @@ -94,6 +132,7 @@ def __init__( credentials: credentials.Credentials = None, transport: Union[str, AccessApprovalTransport] = "grpc_asyncio", client_options: ClientOptions = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: """Instantiate the access approval client. @@ -109,16 +148,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 @@ -126,7 +168,10 @@ def __init__( """ self._client = AccessApprovalClient( - credentials=credentials, transport=transport, client_options=client_options, + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, ) async def list_approval_requests( @@ -172,7 +217,8 @@ async def list_approval_requests( # 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." @@ -197,7 +243,7 @@ async def list_approval_requests( predicate=retries.if_exception_type(exceptions.ServiceUnavailable,), ), default_timeout=600.0, - client_info=_client_info, + client_info=DEFAULT_CLIENT_INFO, ) # Certain fields should be provided within the metadata header; @@ -255,7 +301,8 @@ async def get_approval_request( # 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." @@ -280,7 +327,7 @@ async def get_approval_request( predicate=retries.if_exception_type(exceptions.ServiceUnavailable,), ), default_timeout=600.0, - client_info=_client_info, + client_info=DEFAULT_CLIENT_INFO, ) # Certain fields should be provided within the metadata header; @@ -335,7 +382,7 @@ async def approve_approval_request( rpc = gapic_v1.method_async.wrap_method( self._client._transport.approve_approval_request, default_timeout=600.0, - client_info=_client_info, + client_info=DEFAULT_CLIENT_INFO, ) # Certain fields should be provided within the metadata header; @@ -395,7 +442,7 @@ async def dismiss_approval_request( rpc = gapic_v1.method_async.wrap_method( self._client._transport.dismiss_approval_request, default_timeout=600.0, - client_info=_client_info, + client_info=DEFAULT_CLIENT_INFO, ) # Certain fields should be provided within the metadata header; @@ -449,7 +496,8 @@ async def get_access_approval_settings( # 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." @@ -474,7 +522,7 @@ async def get_access_approval_settings( predicate=retries.if_exception_type(exceptions.ServiceUnavailable,), ), default_timeout=600.0, - client_info=_client_info, + client_info=DEFAULT_CLIENT_INFO, ) # Certain fields should be provided within the metadata header; @@ -544,7 +592,8 @@ async def update_access_approval_settings( # 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([settings, update_mask]): + has_flattened_params = any([settings, 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." @@ -565,7 +614,7 @@ async def update_access_approval_settings( rpc = gapic_v1.method_async.wrap_method( self._client._transport.update_access_approval_settings, default_timeout=600.0, - client_info=_client_info, + client_info=DEFAULT_CLIENT_INFO, ) # Certain fields should be provided within the metadata header; @@ -620,7 +669,8 @@ async def delete_access_approval_settings( # 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." @@ -639,7 +689,7 @@ async def delete_access_approval_settings( rpc = gapic_v1.method_async.wrap_method( self._client._transport.delete_access_approval_settings, default_timeout=600.0, - client_info=_client_info, + client_info=DEFAULT_CLIENT_INFO, ) # Certain fields should be provided within the metadata header; @@ -655,13 +705,13 @@ async def delete_access_approval_settings( try: - _client_info = gapic_v1.client_info.ClientInfo( + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=pkg_resources.get_distribution( "google-cloud-access-approval", ).version, ) except pkg_resources.DistributionNotFound: - _client_info = gapic_v1.client_info.ClientInfo() + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() __all__ = ("AccessApprovalAsyncClient",) diff --git a/google/cloud/accessapproval_v1/services/access_approval/client.py b/google/cloud/accessapproval_v1/services/access_approval/client.py index e609682..6bac823 100644 --- a/google/cloud/accessapproval_v1/services/access_approval/client.py +++ b/google/cloud/accessapproval_v1/services/access_approval/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 @@ -35,7 +37,7 @@ from google.protobuf import field_mask_pb2 as field_mask # type: ignore from google.protobuf import timestamp_pb2 as timestamp # type: ignore -from .transports.base import AccessApprovalTransport +from .transports.base import AccessApprovalTransport, DEFAULT_CLIENT_INFO from .transports.grpc import AccessApprovalGrpcTransport from .transports.grpc_asyncio import AccessApprovalGrpcAsyncIOTransport @@ -165,12 +167,81 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): from_service_account_json = from_service_account_file + @property + def transport(self) -> AccessApprovalTransport: + """Return the transport used by the client instance. + + Returns: + AccessApprovalTransport: The transport used by the client instance. + """ + return self._transport + + @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, AccessApprovalTransport] = None, - client_options: ClientOptions = None, + credentials: Optional[credentials.Credentials] = None, + transport: Union[str, AccessApprovalTransport, None] = None, + client_options: Optional[client_options_lib.ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: """Instantiate the access approval client. @@ -183,48 +254,74 @@ def __init__( transport (Union[str, ~.AccessApprovalTransport]): 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. + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. Raises: google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport creation failed for any reason. """ if isinstance(client_options, dict): - client_options = 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() - if client_options.api_endpoint is None: - use_mtls_env = os.getenv("GOOGLE_API_USE_MTLS", "never") + # 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 + + 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. @@ -248,11 +345,11 @@ 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, ) def list_approval_requests( @@ -781,13 +878,13 @@ def delete_access_approval_settings( try: - _client_info = gapic_v1.client_info.ClientInfo( + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=pkg_resources.get_distribution( "google-cloud-access-approval", ).version, ) except pkg_resources.DistributionNotFound: - _client_info = gapic_v1.client_info.ClientInfo() + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() __all__ = ("AccessApprovalClient",) diff --git a/google/cloud/accessapproval_v1/services/access_approval/transports/base.py b/google/cloud/accessapproval_v1/services/access_approval/transports/base.py index 6efa2e1..fbe4576 100644 --- a/google/cloud/accessapproval_v1/services/access_approval/transports/base.py +++ b/google/cloud/accessapproval_v1/services/access_approval/transports/base.py @@ -19,7 +19,7 @@ import typing import pkg_resources -from google import auth +from google import auth # type: ignore from google.api_core import exceptions # type: ignore from google.api_core import gapic_v1 # type: ignore from google.api_core import retry as retries # type: ignore @@ -30,13 +30,13 @@ try: - _client_info = gapic_v1.client_info.ClientInfo( + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=pkg_resources.get_distribution( "google-cloud-access-approval", ).version, ) except pkg_resources.DistributionNotFound: - _client_info = gapic_v1.client_info.ClientInfo() + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() class AccessApprovalTransport(abc.ABC): @@ -52,6 +52,7 @@ def __init__( credentials_file: typing.Optional[str] = None, scopes: typing.Optional[typing.Sequence[str]] = AUTH_SCOPES, quota_project_id: typing.Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, **kwargs, ) -> None: """Instantiate the transport. @@ -69,6 +70,11 @@ def __init__( scope (Optional[Sequence[str]]): A list of scopes. quota_project_id (Optional[str]): An optional project to use for billing and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. """ # Save the hostname. Default to port 443 (HTTPS) if none is specified. if ":" not in host: @@ -96,9 +102,9 @@ def __init__( self._credentials = credentials # Lifted into its own function so it can be stubbed out during tests. - self._prep_wrapped_messages() + self._prep_wrapped_messages(client_info) - def _prep_wrapped_messages(self): + def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. self._wrapped_methods = { self.list_approval_requests: gapic_v1.method.wrap_method( @@ -110,7 +116,7 @@ def _prep_wrapped_messages(self): predicate=retries.if_exception_type(exceptions.ServiceUnavailable,), ), default_timeout=600.0, - client_info=_client_info, + client_info=client_info, ), self.get_approval_request: gapic_v1.method.wrap_method( self.get_approval_request, @@ -121,17 +127,17 @@ def _prep_wrapped_messages(self): predicate=retries.if_exception_type(exceptions.ServiceUnavailable,), ), default_timeout=600.0, - client_info=_client_info, + client_info=client_info, ), self.approve_approval_request: gapic_v1.method.wrap_method( self.approve_approval_request, default_timeout=600.0, - client_info=_client_info, + client_info=client_info, ), self.dismiss_approval_request: gapic_v1.method.wrap_method( self.dismiss_approval_request, default_timeout=600.0, - client_info=_client_info, + client_info=client_info, ), self.get_access_approval_settings: gapic_v1.method.wrap_method( self.get_access_approval_settings, @@ -142,17 +148,17 @@ def _prep_wrapped_messages(self): predicate=retries.if_exception_type(exceptions.ServiceUnavailable,), ), default_timeout=600.0, - client_info=_client_info, + client_info=client_info, ), self.update_access_approval_settings: gapic_v1.method.wrap_method( self.update_access_approval_settings, default_timeout=600.0, - client_info=_client_info, + client_info=client_info, ), self.delete_access_approval_settings: gapic_v1.method.wrap_method( self.delete_access_approval_settings, default_timeout=600.0, - client_info=_client_info, + client_info=client_info, ), } diff --git a/google/cloud/accessapproval_v1/services/access_approval/transports/grpc.py b/google/cloud/accessapproval_v1/services/access_approval/transports/grpc.py index bb6d23b..0123743 100644 --- a/google/cloud/accessapproval_v1/services/access_approval/transports/grpc.py +++ b/google/cloud/accessapproval_v1/services/access_approval/transports/grpc.py @@ -15,20 +15,21 @@ # limitations under the License. # +import warnings from typing import Callable, Dict, Optional, Sequence, Tuple from google.api_core import grpc_helpers # type: ignore +from google.api_core import gapic_v1 # type: ignore from google import auth # type: ignore from google.auth import credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore - import grpc # type: ignore from google.cloud.accessapproval_v1.types import accessapproval from google.protobuf import empty_pb2 as empty # type: ignore -from .base import AccessApprovalTransport +from .base import AccessApprovalTransport, DEFAULT_CLIENT_INFO class AccessApprovalGrpcTransport(AccessApprovalTransport): @@ -90,7 +91,9 @@ def __init__( channel: grpc.Channel = None, api_mtls_endpoint: str = None, client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - quota_project_id: Optional[str] = None + ssl_channel_credentials: grpc.ChannelCredentials = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: """Instantiate the transport. @@ -109,16 +112,23 @@ 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 + your own client library. Raises: google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport @@ -126,6 +136,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. @@ -133,7 +145,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 @@ -164,6 +182,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] @@ -174,6 +210,7 @@ def __init__( credentials_file=credentials_file, scopes=scopes or self.AUTH_SCOPES, quota_project_id=quota_project_id, + client_info=client_info, ) @classmethod @@ -184,7 +221,7 @@ def create_channel( credentials_file: str = None, scopes: Optional[Sequence[str]] = None, quota_project_id: Optional[str] = None, - **kwargs + **kwargs, ) -> grpc.Channel: """Create and return a gRPC channel object. Args: @@ -218,24 +255,13 @@ def create_channel( credentials_file=credentials_file, scopes=scopes, quota_project_id=quota_project_id, - **kwargs + **kwargs, ) @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/accessapproval_v1/services/access_approval/transports/grpc_asyncio.py b/google/cloud/accessapproval_v1/services/access_approval/transports/grpc_asyncio.py index 73435d5..e7b0412 100644 --- a/google/cloud/accessapproval_v1/services/access_approval/transports/grpc_asyncio.py +++ b/google/cloud/accessapproval_v1/services/access_approval/transports/grpc_asyncio.py @@ -15,9 +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 @@ -27,7 +30,7 @@ from google.cloud.accessapproval_v1.types import accessapproval from google.protobuf import empty_pb2 as empty # type: ignore -from .base import AccessApprovalTransport +from .base import AccessApprovalTransport, DEFAULT_CLIENT_INFO from .grpc import AccessApprovalGrpcTransport @@ -132,7 +135,9 @@ 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: """Instantiate the transport. @@ -152,16 +157,23 @@ 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): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. Raises: google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport @@ -169,6 +181,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. @@ -176,13 +190,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: @@ -202,6 +227,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__( @@ -210,6 +253,7 @@ def __init__( credentials_file=credentials_file, scopes=scopes or self.AUTH_SCOPES, quota_project_id=quota_project_id, + client_info=client_info, ) self._stubs = {} @@ -221,13 +265,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/accessapproval_v1/types/accessapproval.py b/google/cloud/accessapproval_v1/types/accessapproval.py index 78f8c88..a0d5441 100644 --- a/google/cloud/accessapproval_v1/types/accessapproval.py +++ b/google/cloud/accessapproval_v1/types/accessapproval.py @@ -103,7 +103,7 @@ class AccessReason(proto.Message): r""" Attributes: - type (~.accessapproval.AccessReason.Type): + type_ (~.accessapproval.AccessReason.Type): Type of access justification. detail (str): More detail about certain reason types. See @@ -117,7 +117,7 @@ class Type(proto.Enum): GOOGLE_INITIATED_SERVICE = 2 GOOGLE_INITIATED_REVIEW = 3 - type = proto.Field(proto.ENUM, number=1, enum=Type,) + type_ = proto.Field(proto.ENUM, number=1, enum=Type,) detail = proto.Field(proto.STRING, number=2) @@ -205,12 +205,14 @@ class ApprovalRequest(proto.Message): requested_resource_name = proto.Field(proto.STRING, number=2) requested_resource_properties = proto.Field( - proto.MESSAGE, number=9, message=ResourceProperties, + proto.MESSAGE, number=9, message="ResourceProperties", ) - requested_reason = proto.Field(proto.MESSAGE, number=3, message=AccessReason,) + requested_reason = proto.Field(proto.MESSAGE, number=3, message="AccessReason",) - requested_locations = proto.Field(proto.MESSAGE, number=4, message=AccessLocations,) + requested_locations = proto.Field( + proto.MESSAGE, number=4, message="AccessLocations", + ) request_time = proto.Field(proto.MESSAGE, number=5, message=timestamp.Timestamp,) @@ -219,11 +221,11 @@ class ApprovalRequest(proto.Message): ) approve = proto.Field( - proto.MESSAGE, number=7, oneof="decision", message=ApproveDecision, + proto.MESSAGE, number=7, oneof="decision", message="ApproveDecision", ) dismiss = proto.Field( - proto.MESSAGE, number=8, oneof="decision", message=DismissDecision, + proto.MESSAGE, number=8, oneof="decision", message="DismissDecision", ) @@ -303,7 +305,7 @@ class AccessApprovalSettings(proto.Message): notification_emails = proto.RepeatedField(proto.STRING, number=2) enrolled_services = proto.RepeatedField( - proto.MESSAGE, number=3, message=EnrolledService, + proto.MESSAGE, number=3, message="EnrolledService", ) enrolled_ancestor = proto.Field(proto.BOOL, number=4) @@ -358,7 +360,7 @@ def raw_page(self): return self approval_requests = proto.RepeatedField( - proto.MESSAGE, number=1, message=ApprovalRequest, + proto.MESSAGE, number=1, message="ApprovalRequest", ) next_page_token = proto.Field(proto.STRING, number=2) @@ -433,7 +435,7 @@ class UpdateAccessApprovalSettingsMessage(proto.Message): field will be updated. """ - settings = proto.Field(proto.MESSAGE, number=1, message=AccessApprovalSettings,) + settings = proto.Field(proto.MESSAGE, number=1, message="AccessApprovalSettings",) update_mask = proto.Field(proto.MESSAGE, number=2, message=field_mask.FieldMask,) diff --git a/noxfile.py b/noxfile.py index 0a93cf7..3acdf8f 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,7 +72,9 @@ 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. @@ -173,7 +175,9 @@ def docfx(session): """Build the docfx yaml files for this library.""" session.install("-e", ".") - session.install("sphinx", "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/scripts/decrypt-secrets.sh b/scripts/decrypt-secrets.sh index ff599eb..21f6d2a 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_accessapproval_v1_keywords.py b/scripts/fixup_accessapproval_v1_keywords.py index 498591f..883d4a9 100644 --- a/scripts/fixup_accessapproval_v1_keywords.py +++ b/scripts/fixup_accessapproval_v1_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 1405d62..28248bf 100644 --- a/synth.metadata +++ b/synth.metadata @@ -3,30 +3,30 @@ { "git": { "name": ".", - "remote": "https://github.com/googleapis/python-access-approval.git", - "sha": "d9f8d2b37a041b49bad095f9d7c455226fb6251c" + "remote": "git@github.com:googleapis/python-access-approval", + "sha": "7fcae2b8e23e9a64016ad758a9e14a78ed02374e" } }, { "git": { "name": "googleapis", "remote": "https://github.com/googleapis/googleapis.git", - "sha": "43a62a87b70010d9cf9be31e99ea230a535e1b47", - "internalRef": "326109811" + "sha": "6a69c750c3f01a69017662395f90515bbf1fe1ff", + "internalRef": "342721036" } }, { "git": { "name": "synthtool", "remote": "https://github.com/googleapis/synthtool.git", - "sha": "4f8f5dc24af79694887385015294e4dbb214c352" + "sha": "d5fc0bcf9ea9789c5b0e3154a9e3b29e5cea6116" } }, { "git": { "name": "synthtool", "remote": "https://github.com/googleapis/synthtool.git", - "sha": "4f8f5dc24af79694887385015294e4dbb214c352" + "sha": "d5fc0bcf9ea9789c5b0e3154a9e3b29e5cea6116" } } ], diff --git a/tests/unit/gapic/accessapproval_v1/test_access_approval.py b/tests/unit/gapic/accessapproval_v1/test_access_approval.py index 795cc55..895aa75 100644 --- a/tests/unit/gapic/accessapproval_v1/test_access_approval.py +++ b/tests/unit/gapic/accessapproval_v1/test_access_approval.py @@ -98,12 +98,12 @@ def test_access_approval_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 == "accessapproval.googleapis.com:443" + assert client.transport._host == "accessapproval.googleapis.com:443" def test_access_approval_client_get_transport_class(): @@ -159,14 +159,14 @@ def test_access_approval_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() @@ -175,14 +175,14 @@ def test_access_approval_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() @@ -191,90 +191,175 @@ def test_access_approval_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", + [ + (AccessApprovalClient, transports.AccessApprovalGrpcTransport, "grpc", "true"), + ( + AccessApprovalAsyncClient, + transports.AccessApprovalGrpcAsyncIOTransport, + "grpc_asyncio", + "true", + ), + (AccessApprovalClient, transports.AccessApprovalGrpcTransport, "grpc", "false"), + ( + AccessApprovalAsyncClient, + transports.AccessApprovalGrpcAsyncIOTransport, + "grpc_asyncio", + "false", + ), + ], +) +@mock.patch.object( + AccessApprovalClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(AccessApprovalClient), +) +@mock.patch.object( + AccessApprovalAsyncClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(AccessApprovalAsyncClient), +) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_access_approval_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, - ) - - # 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, - ) - - # 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", - ) + 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( @@ -301,9 +386,9 @@ def test_access_approval_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, ) @@ -331,9 +416,9 @@ def test_access_approval_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, ) @@ -350,9 +435,9 @@ def test_access_approval_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, ) @@ -369,7 +454,7 @@ def test_list_approval_requests( # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client._transport.list_approval_requests), "__call__" + type(client.transport.list_approval_requests), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = accessapproval.ListApprovalRequestsResponse( @@ -385,6 +470,7 @@ def test_list_approval_requests( assert args[0] == accessapproval.ListApprovalRequestsMessage() # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListApprovalRequestsPager) assert response.next_page_token == "next_page_token_value" @@ -395,18 +481,21 @@ def test_list_approval_requests_from_dict(): @pytest.mark.asyncio -async def test_list_approval_requests_async(transport: str = "grpc_asyncio"): +async def test_list_approval_requests_async( + transport: str = "grpc_asyncio", + request_type=accessapproval.ListApprovalRequestsMessage, +): client = AccessApprovalAsyncClient( 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 = accessapproval.ListApprovalRequestsMessage() + request = request_type() # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client._client._transport.list_approval_requests), "__call__" + type(client.transport.list_approval_requests), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( @@ -421,7 +510,7 @@ async def test_list_approval_requests_async(transport: str = "grpc_asyncio"): assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == request + assert args[0] == accessapproval.ListApprovalRequestsMessage() # Establish that the response is the type that we expect. assert isinstance(response, pagers.ListApprovalRequestsAsyncPager) @@ -429,6 +518,11 @@ async def test_list_approval_requests_async(transport: str = "grpc_asyncio"): assert response.next_page_token == "next_page_token_value" +@pytest.mark.asyncio +async def test_list_approval_requests_async_from_dict(): + await test_list_approval_requests_async(request_type=dict) + + def test_list_approval_requests_field_headers(): client = AccessApprovalClient(credentials=credentials.AnonymousCredentials(),) @@ -439,7 +533,7 @@ def test_list_approval_requests_field_headers(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client._transport.list_approval_requests), "__call__" + type(client.transport.list_approval_requests), "__call__" ) as call: call.return_value = accessapproval.ListApprovalRequestsResponse() @@ -466,7 +560,7 @@ async def test_list_approval_requests_field_headers_async(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client._client._transport.list_approval_requests), "__call__" + type(client.transport.list_approval_requests), "__call__" ) as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( accessapproval.ListApprovalRequestsResponse() @@ -489,7 +583,7 @@ def test_list_approval_requests_flattened(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client._transport.list_approval_requests), "__call__" + type(client.transport.list_approval_requests), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = accessapproval.ListApprovalRequestsResponse() @@ -523,7 +617,7 @@ async def test_list_approval_requests_flattened_async(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client._client._transport.list_approval_requests), "__call__" + type(client.transport.list_approval_requests), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = accessapproval.ListApprovalRequestsResponse() @@ -560,7 +654,7 @@ def test_list_approval_requests_pager(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client._transport.list_approval_requests), "__call__" + type(client.transport.list_approval_requests), "__call__" ) as call: # Set the response to a series of pages. call.side_effect = ( @@ -606,7 +700,7 @@ def test_list_approval_requests_pages(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client._transport.list_approval_requests), "__call__" + type(client.transport.list_approval_requests), "__call__" ) as call: # Set the response to a series of pages. call.side_effect = ( @@ -634,8 +728,8 @@ def test_list_approval_requests_pages(): RuntimeError, ) pages = list(client.list_approval_requests(request={}).pages) - for page, token in zip(pages, ["abc", "def", "ghi", ""]): - assert page.raw_page.next_page_token == token + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token @pytest.mark.asyncio @@ -644,7 +738,7 @@ async def test_list_approval_requests_async_pager(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client._client._transport.list_approval_requests), + type(client.transport.list_approval_requests), "__call__", new_callable=mock.AsyncMock, ) as call: @@ -689,7 +783,7 @@ async def test_list_approval_requests_async_pages(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client._client._transport.list_approval_requests), + type(client.transport.list_approval_requests), "__call__", new_callable=mock.AsyncMock, ) as call: @@ -719,10 +813,10 @@ async def test_list_approval_requests_async_pages(): RuntimeError, ) pages = [] - async for page in (await client.list_approval_requests(request={})).pages: - pages.append(page) - for page, token in zip(pages, ["abc", "def", "ghi", ""]): - assert page.raw_page.next_page_token == token + async for page_ in (await client.list_approval_requests(request={})).pages: + pages.append(page_) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token def test_get_approval_request( @@ -738,7 +832,7 @@ def test_get_approval_request( # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client._transport.get_approval_request), "__call__" + type(client.transport.get_approval_request), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = accessapproval.ApprovalRequest( @@ -758,6 +852,7 @@ def test_get_approval_request( assert args[0] == accessapproval.GetApprovalRequestMessage() # Establish that the response is the type that we expect. + assert isinstance(response, accessapproval.ApprovalRequest) assert response.name == "name_value" @@ -770,18 +865,21 @@ def test_get_approval_request_from_dict(): @pytest.mark.asyncio -async def test_get_approval_request_async(transport: str = "grpc_asyncio"): +async def test_get_approval_request_async( + transport: str = "grpc_asyncio", + request_type=accessapproval.GetApprovalRequestMessage, +): client = AccessApprovalAsyncClient( 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 = accessapproval.GetApprovalRequestMessage() + request = request_type() # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client._client._transport.get_approval_request), "__call__" + type(client.transport.get_approval_request), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( @@ -797,7 +895,7 @@ async def test_get_approval_request_async(transport: str = "grpc_asyncio"): assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == request + assert args[0] == accessapproval.GetApprovalRequestMessage() # Establish that the response is the type that we expect. assert isinstance(response, accessapproval.ApprovalRequest) @@ -807,6 +905,11 @@ async def test_get_approval_request_async(transport: str = "grpc_asyncio"): assert response.requested_resource_name == "requested_resource_name_value" +@pytest.mark.asyncio +async def test_get_approval_request_async_from_dict(): + await test_get_approval_request_async(request_type=dict) + + def test_get_approval_request_field_headers(): client = AccessApprovalClient(credentials=credentials.AnonymousCredentials(),) @@ -817,7 +920,7 @@ def test_get_approval_request_field_headers(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client._transport.get_approval_request), "__call__" + type(client.transport.get_approval_request), "__call__" ) as call: call.return_value = accessapproval.ApprovalRequest() @@ -844,7 +947,7 @@ async def test_get_approval_request_field_headers_async(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client._client._transport.get_approval_request), "__call__" + type(client.transport.get_approval_request), "__call__" ) as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( accessapproval.ApprovalRequest() @@ -867,7 +970,7 @@ def test_get_approval_request_flattened(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client._transport.get_approval_request), "__call__" + type(client.transport.get_approval_request), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = accessapproval.ApprovalRequest() @@ -901,7 +1004,7 @@ async def test_get_approval_request_flattened_async(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client._client._transport.get_approval_request), "__call__" + type(client.transport.get_approval_request), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = accessapproval.ApprovalRequest() @@ -946,7 +1049,7 @@ def test_approve_approval_request( # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client._transport.approve_approval_request), "__call__" + type(client.transport.approve_approval_request), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = accessapproval.ApprovalRequest( @@ -966,6 +1069,7 @@ def test_approve_approval_request( assert args[0] == accessapproval.ApproveApprovalRequestMessage() # Establish that the response is the type that we expect. + assert isinstance(response, accessapproval.ApprovalRequest) assert response.name == "name_value" @@ -978,18 +1082,21 @@ def test_approve_approval_request_from_dict(): @pytest.mark.asyncio -async def test_approve_approval_request_async(transport: str = "grpc_asyncio"): +async def test_approve_approval_request_async( + transport: str = "grpc_asyncio", + request_type=accessapproval.ApproveApprovalRequestMessage, +): client = AccessApprovalAsyncClient( 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 = accessapproval.ApproveApprovalRequestMessage() + request = request_type() # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client._client._transport.approve_approval_request), "__call__" + type(client.transport.approve_approval_request), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( @@ -1005,7 +1112,7 @@ async def test_approve_approval_request_async(transport: str = "grpc_asyncio"): assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == request + assert args[0] == accessapproval.ApproveApprovalRequestMessage() # Establish that the response is the type that we expect. assert isinstance(response, accessapproval.ApprovalRequest) @@ -1015,6 +1122,11 @@ async def test_approve_approval_request_async(transport: str = "grpc_asyncio"): assert response.requested_resource_name == "requested_resource_name_value" +@pytest.mark.asyncio +async def test_approve_approval_request_async_from_dict(): + await test_approve_approval_request_async(request_type=dict) + + def test_approve_approval_request_field_headers(): client = AccessApprovalClient(credentials=credentials.AnonymousCredentials(),) @@ -1025,7 +1137,7 @@ def test_approve_approval_request_field_headers(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client._transport.approve_approval_request), "__call__" + type(client.transport.approve_approval_request), "__call__" ) as call: call.return_value = accessapproval.ApprovalRequest() @@ -1052,7 +1164,7 @@ async def test_approve_approval_request_field_headers_async(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client._client._transport.approve_approval_request), "__call__" + type(client.transport.approve_approval_request), "__call__" ) as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( accessapproval.ApprovalRequest() @@ -1083,7 +1195,7 @@ def test_dismiss_approval_request( # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client._transport.dismiss_approval_request), "__call__" + type(client.transport.dismiss_approval_request), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = accessapproval.ApprovalRequest( @@ -1103,6 +1215,7 @@ def test_dismiss_approval_request( assert args[0] == accessapproval.DismissApprovalRequestMessage() # Establish that the response is the type that we expect. + assert isinstance(response, accessapproval.ApprovalRequest) assert response.name == "name_value" @@ -1115,18 +1228,21 @@ def test_dismiss_approval_request_from_dict(): @pytest.mark.asyncio -async def test_dismiss_approval_request_async(transport: str = "grpc_asyncio"): +async def test_dismiss_approval_request_async( + transport: str = "grpc_asyncio", + request_type=accessapproval.DismissApprovalRequestMessage, +): client = AccessApprovalAsyncClient( 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 = accessapproval.DismissApprovalRequestMessage() + request = request_type() # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client._client._transport.dismiss_approval_request), "__call__" + type(client.transport.dismiss_approval_request), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( @@ -1142,7 +1258,7 @@ async def test_dismiss_approval_request_async(transport: str = "grpc_asyncio"): assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == request + assert args[0] == accessapproval.DismissApprovalRequestMessage() # Establish that the response is the type that we expect. assert isinstance(response, accessapproval.ApprovalRequest) @@ -1152,6 +1268,11 @@ async def test_dismiss_approval_request_async(transport: str = "grpc_asyncio"): assert response.requested_resource_name == "requested_resource_name_value" +@pytest.mark.asyncio +async def test_dismiss_approval_request_async_from_dict(): + await test_dismiss_approval_request_async(request_type=dict) + + def test_dismiss_approval_request_field_headers(): client = AccessApprovalClient(credentials=credentials.AnonymousCredentials(),) @@ -1162,7 +1283,7 @@ def test_dismiss_approval_request_field_headers(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client._transport.dismiss_approval_request), "__call__" + type(client.transport.dismiss_approval_request), "__call__" ) as call: call.return_value = accessapproval.ApprovalRequest() @@ -1189,7 +1310,7 @@ async def test_dismiss_approval_request_field_headers_async(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client._client._transport.dismiss_approval_request), "__call__" + type(client.transport.dismiss_approval_request), "__call__" ) as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( accessapproval.ApprovalRequest() @@ -1221,7 +1342,7 @@ def test_get_access_approval_settings( # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client._transport.get_access_approval_settings), "__call__" + type(client.transport.get_access_approval_settings), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = accessapproval.AccessApprovalSettings( @@ -1239,6 +1360,7 @@ def test_get_access_approval_settings( assert args[0] == accessapproval.GetAccessApprovalSettingsMessage() # Establish that the response is the type that we expect. + assert isinstance(response, accessapproval.AccessApprovalSettings) assert response.name == "name_value" @@ -1253,18 +1375,21 @@ def test_get_access_approval_settings_from_dict(): @pytest.mark.asyncio -async def test_get_access_approval_settings_async(transport: str = "grpc_asyncio"): +async def test_get_access_approval_settings_async( + transport: str = "grpc_asyncio", + request_type=accessapproval.GetAccessApprovalSettingsMessage, +): client = AccessApprovalAsyncClient( 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 = accessapproval.GetAccessApprovalSettingsMessage() + request = request_type() # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client._client._transport.get_access_approval_settings), "__call__" + type(client.transport.get_access_approval_settings), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( @@ -1281,7 +1406,7 @@ async def test_get_access_approval_settings_async(transport: str = "grpc_asyncio assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == request + assert args[0] == accessapproval.GetAccessApprovalSettingsMessage() # Establish that the response is the type that we expect. assert isinstance(response, accessapproval.AccessApprovalSettings) @@ -1293,6 +1418,11 @@ async def test_get_access_approval_settings_async(transport: str = "grpc_asyncio assert response.enrolled_ancestor is True +@pytest.mark.asyncio +async def test_get_access_approval_settings_async_from_dict(): + await test_get_access_approval_settings_async(request_type=dict) + + def test_get_access_approval_settings_field_headers(): client = AccessApprovalClient(credentials=credentials.AnonymousCredentials(),) @@ -1303,7 +1433,7 @@ def test_get_access_approval_settings_field_headers(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client._transport.get_access_approval_settings), "__call__" + type(client.transport.get_access_approval_settings), "__call__" ) as call: call.return_value = accessapproval.AccessApprovalSettings() @@ -1330,7 +1460,7 @@ async def test_get_access_approval_settings_field_headers_async(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client._client._transport.get_access_approval_settings), "__call__" + type(client.transport.get_access_approval_settings), "__call__" ) as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( accessapproval.AccessApprovalSettings() @@ -1353,7 +1483,7 @@ def test_get_access_approval_settings_flattened(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client._transport.get_access_approval_settings), "__call__" + type(client.transport.get_access_approval_settings), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = accessapproval.AccessApprovalSettings() @@ -1387,7 +1517,7 @@ async def test_get_access_approval_settings_flattened_async(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client._client._transport.get_access_approval_settings), "__call__" + type(client.transport.get_access_approval_settings), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = accessapproval.AccessApprovalSettings() @@ -1433,7 +1563,7 @@ def test_update_access_approval_settings( # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client._transport.update_access_approval_settings), "__call__" + type(client.transport.update_access_approval_settings), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = accessapproval.AccessApprovalSettings( @@ -1451,6 +1581,7 @@ def test_update_access_approval_settings( assert args[0] == accessapproval.UpdateAccessApprovalSettingsMessage() # Establish that the response is the type that we expect. + assert isinstance(response, accessapproval.AccessApprovalSettings) assert response.name == "name_value" @@ -1465,18 +1596,21 @@ def test_update_access_approval_settings_from_dict(): @pytest.mark.asyncio -async def test_update_access_approval_settings_async(transport: str = "grpc_asyncio"): +async def test_update_access_approval_settings_async( + transport: str = "grpc_asyncio", + request_type=accessapproval.UpdateAccessApprovalSettingsMessage, +): client = AccessApprovalAsyncClient( 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 = accessapproval.UpdateAccessApprovalSettingsMessage() + request = request_type() # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client._client._transport.update_access_approval_settings), "__call__" + type(client.transport.update_access_approval_settings), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( @@ -1493,7 +1627,7 @@ async def test_update_access_approval_settings_async(transport: str = "grpc_asyn assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == request + assert args[0] == accessapproval.UpdateAccessApprovalSettingsMessage() # Establish that the response is the type that we expect. assert isinstance(response, accessapproval.AccessApprovalSettings) @@ -1505,6 +1639,11 @@ async def test_update_access_approval_settings_async(transport: str = "grpc_asyn assert response.enrolled_ancestor is True +@pytest.mark.asyncio +async def test_update_access_approval_settings_async_from_dict(): + await test_update_access_approval_settings_async(request_type=dict) + + def test_update_access_approval_settings_field_headers(): client = AccessApprovalClient(credentials=credentials.AnonymousCredentials(),) @@ -1515,7 +1654,7 @@ def test_update_access_approval_settings_field_headers(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client._transport.update_access_approval_settings), "__call__" + type(client.transport.update_access_approval_settings), "__call__" ) as call: call.return_value = accessapproval.AccessApprovalSettings() @@ -1544,7 +1683,7 @@ async def test_update_access_approval_settings_field_headers_async(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client._client._transport.update_access_approval_settings), "__call__" + type(client.transport.update_access_approval_settings), "__call__" ) as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( accessapproval.AccessApprovalSettings() @@ -1569,7 +1708,7 @@ def test_update_access_approval_settings_flattened(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client._transport.update_access_approval_settings), "__call__" + type(client.transport.update_access_approval_settings), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = accessapproval.AccessApprovalSettings() @@ -1612,7 +1751,7 @@ async def test_update_access_approval_settings_flattened_async(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client._client._transport.update_access_approval_settings), "__call__" + type(client.transport.update_access_approval_settings), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = accessapproval.AccessApprovalSettings() @@ -1667,7 +1806,7 @@ def test_delete_access_approval_settings( # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client._transport.delete_access_approval_settings), "__call__" + type(client.transport.delete_access_approval_settings), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = None @@ -1689,18 +1828,21 @@ def test_delete_access_approval_settings_from_dict(): @pytest.mark.asyncio -async def test_delete_access_approval_settings_async(transport: str = "grpc_asyncio"): +async def test_delete_access_approval_settings_async( + transport: str = "grpc_asyncio", + request_type=accessapproval.DeleteAccessApprovalSettingsMessage, +): client = AccessApprovalAsyncClient( 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 = accessapproval.DeleteAccessApprovalSettingsMessage() + request = request_type() # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client._client._transport.delete_access_approval_settings), "__call__" + type(client.transport.delete_access_approval_settings), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) @@ -1711,12 +1853,17 @@ async def test_delete_access_approval_settings_async(transport: str = "grpc_asyn assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == request + assert args[0] == accessapproval.DeleteAccessApprovalSettingsMessage() # Establish that the response is the type that we expect. assert response is None +@pytest.mark.asyncio +async def test_delete_access_approval_settings_async_from_dict(): + await test_delete_access_approval_settings_async(request_type=dict) + + def test_delete_access_approval_settings_field_headers(): client = AccessApprovalClient(credentials=credentials.AnonymousCredentials(),) @@ -1727,7 +1874,7 @@ def test_delete_access_approval_settings_field_headers(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client._transport.delete_access_approval_settings), "__call__" + type(client.transport.delete_access_approval_settings), "__call__" ) as call: call.return_value = None @@ -1754,7 +1901,7 @@ async def test_delete_access_approval_settings_field_headers_async(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client._client._transport.delete_access_approval_settings), "__call__" + type(client.transport.delete_access_approval_settings), "__call__" ) as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) @@ -1775,7 +1922,7 @@ def test_delete_access_approval_settings_flattened(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client._transport.delete_access_approval_settings), "__call__" + type(client.transport.delete_access_approval_settings), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = None @@ -1809,7 +1956,7 @@ async def test_delete_access_approval_settings_flattened_async(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client._client._transport.delete_access_approval_settings), "__call__" + type(client.transport.delete_access_approval_settings), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = None @@ -1875,7 +2022,7 @@ def test_transport_instance(): credentials=credentials.AnonymousCredentials(), ) client = AccessApprovalClient(transport=transport) - assert client._transport is transport + assert client.transport is transport def test_transport_get_channel(): @@ -1893,10 +2040,25 @@ def test_transport_get_channel(): assert channel +@pytest.mark.parametrize( + "transport_class", + [ + transports.AccessApprovalGrpcTransport, + transports.AccessApprovalGrpcAsyncIOTransport, + ], +) +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 = AccessApprovalClient(credentials=credentials.AnonymousCredentials(),) - assert isinstance(client._transport, transports.AccessApprovalGrpcTransport,) + assert isinstance(client.transport, transports.AccessApprovalGrpcTransport,) def test_access_approval_base_transport_error(): @@ -1953,6 +2115,17 @@ def test_access_approval_base_transport_with_credentials_file(): ) +def test_access_approval_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.accessapproval_v1.services.access_approval.transports.AccessApprovalTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + adc.return_value = (credentials.AnonymousCredentials(), None) + transport = transports.AccessApprovalTransport() + adc.assert_called_once() + + def test_access_approval_auth_adc(): # If no credentials are provided, we should use ADC credentials. with mock.patch.object(auth, "default") as adc: @@ -1985,7 +2158,7 @@ def test_access_approval_host_no_port(): api_endpoint="accessapproval.googleapis.com" ), ) - assert client._transport._host == "accessapproval.googleapis.com:443" + assert client.transport._host == "accessapproval.googleapis.com:443" def test_access_approval_host_with_port(): @@ -1995,182 +2168,238 @@ def test_access_approval_host_with_port(): api_endpoint="accessapproval.googleapis.com:8000" ), ) - assert client._transport._host == "accessapproval.googleapis.com:8000" + assert client.transport._host == "accessapproval.googleapis.com:8000" def test_access_approval_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.AccessApprovalGrpcTransport( - 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_access_approval_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.AccessApprovalGrpcAsyncIOTransport( - 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 -@mock.patch("grpc.ssl_channel_credentials", autospec=True) -@mock.patch("google.api_core.grpc_helpers.create_channel", autospec=True) -def test_access_approval_grpc_transport_channel_mtls_with_client_cert_source( - grpc_create_channel, grpc_ssl_channel_cred +@pytest.mark.parametrize( + "transport_class", + [ + transports.AccessApprovalGrpcTransport, + transports.AccessApprovalGrpcAsyncIOTransport, + ], +) +def test_access_approval_transport_channel_mtls_with_client_cert_source( + transport_class, ): - # 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() + 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( + "transport_class", + [ + transports.AccessApprovalGrpcTransport, + transports.AccessApprovalGrpcAsyncIOTransport, + ], +) +def test_access_approval_transport_channel_mtls_with_adc(transport_class): mock_ssl_cred = mock.Mock() - grpc_ssl_channel_cred.return_value = mock_ssl_cred + with mock.patch.multiple( + "google.auth.transport.grpc.SslCredentials", + __init__=mock.Mock(return_value=None), + ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), + ): + with mock.patch.object( + transport_class, "create_channel", 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, + ) - mock_grpc_channel = mock.Mock() - grpc_create_channel.return_value = mock_grpc_channel + 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 - transport = transports.AccessApprovalGrpcTransport( - 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, + +def test_common_billing_account_path(): + billing_account = "squid" + + expected = "billingAccounts/{billing_account}".format( + billing_account=billing_account, ) - assert transport.grpc_channel == mock_grpc_channel + actual = AccessApprovalClient.common_billing_account_path(billing_account) + assert expected == actual -@mock.patch("grpc.ssl_channel_credentials", autospec=True) -@mock.patch("google.api_core.grpc_helpers_async.create_channel", autospec=True) -def test_access_approval_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() +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "clam", + } + path = AccessApprovalClient.common_billing_account_path(**expected) - mock_ssl_cred = mock.Mock() - grpc_ssl_channel_cred.return_value = mock_ssl_cred + # Check that the path construction is reversible. + actual = AccessApprovalClient.parse_common_billing_account_path(path) + assert expected == actual - mock_grpc_channel = mock.Mock() - grpc_create_channel.return_value = mock_grpc_channel - transport = transports.AccessApprovalGrpcAsyncIOTransport( - 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, +def test_common_folder_path(): + folder = "whelk" + + expected = "folders/{folder}".format(folder=folder,) + actual = AccessApprovalClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "octopus", + } + path = AccessApprovalClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = AccessApprovalClient.parse_common_folder_path(path) + assert expected == actual + + +def test_common_organization_path(): + organization = "oyster" + + expected = "organizations/{organization}".format(organization=organization,) + actual = AccessApprovalClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "nudibranch", + } + path = AccessApprovalClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = AccessApprovalClient.parse_common_organization_path(path) + assert expected == actual + + +def test_common_project_path(): + project = "cuttlefish" + + expected = "projects/{project}".format(project=project,) + actual = AccessApprovalClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "mussel", + } + path = AccessApprovalClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = AccessApprovalClient.parse_common_project_path(path) + assert expected == actual + + +def test_common_location_path(): + project = "winkle" + location = "nautilus" + + expected = "projects/{project}/locations/{location}".format( + project=project, location=location, ) - assert transport.grpc_channel == mock_grpc_channel + actual = AccessApprovalClient.common_location_path(project, location) + assert expected == actual -@pytest.mark.parametrize( - "api_mtls_endpoint", ["mtls.squid.clam.whelk", "mtls.squid.clam.whelk:443"] -) -@mock.patch("google.api_core.grpc_helpers.create_channel", autospec=True) -def test_access_approval_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 +def test_parse_common_location_path(): + expected = { + "project": "scallop", + "location": "abalone", + } + path = AccessApprovalClient.common_location_path(**expected) - # 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.AccessApprovalGrpcTransport( - 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 + # Check that the path construction is reversible. + actual = AccessApprovalClient.parse_common_location_path(path) + assert expected == actual -@pytest.mark.parametrize( - "api_mtls_endpoint", ["mtls.squid.clam.whelk", "mtls.squid.clam.whelk:443"] -) -@mock.patch("google.api_core.grpc_helpers_async.create_channel", autospec=True) -def test_access_approval_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 +def test_client_withDEFAULT_CLIENT_INFO(): + client_info = gapic_v1.client_info.ClientInfo() - # 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.AccessApprovalGrpcAsyncIOTransport( - host="squid.clam.whelk", - credentials=mock_cred, - api_mtls_endpoint=api_mtls_endpoint, - client_cert_source=None, + with mock.patch.object( + transports.AccessApprovalTransport, "_prep_wrapped_messages" + ) as prep: + client = AccessApprovalClient( + credentials=credentials.AnonymousCredentials(), client_info=client_info, ) - 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, + prep.assert_called_once_with(client_info) + + with mock.patch.object( + transports.AccessApprovalTransport, "_prep_wrapped_messages" + ) as prep: + transport_class = AccessApprovalClient.get_transport_class() + transport = transport_class( + credentials=credentials.AnonymousCredentials(), client_info=client_info, ) - assert transport.grpc_channel == mock_grpc_channel + prep.assert_called_once_with(client_info)