From e2367d0be19e5e8e353ad9757a5b2ba730168b4c Mon Sep 17 00:00:00 2001 From: Yoshi Automation Bot Date: Mon, 30 Nov 2020 16:50:02 -0800 Subject: [PATCH] feat: add common resource paths, expose client transport (#4) This PR was generated using Autosynth. :rainbow: Synth log will be available here: https://source.cloud.google.com/results/invocations/ae69e792-ad74-42fa-ada8-d5be248bc596/targets - [ ] To automatically regenerate this PR, check this box. Source-Link: https://github.com/googleapis/synthtool/commit/ffcee7952b74f647cbb3ef021d95422f10816fca Source-Link: https://github.com/googleapis/synthtool/commit/d302f93d7f47e2852e585ac35ab2d15585717ec0 --- .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/conf.py | 4 +- docs/tables_v1alpha1/types.rst | 1 + .../services/tables_service/async_client.py | 78 +- .../services/tables_service/client.py | 175 +++- .../tables_service/transports/grpc.py | 64 +- .../tables_service/transports/grpc_asyncio.py | 55 +- .../area120/tables_v1alpha1/types/tables.py | 4 +- noxfile.py | 10 +- scripts/decrypt-secrets.sh | 15 +- synth.metadata | 16 +- .../tables_v1alpha1/test_tables_service.py | 931 +++++++++++------- 21 files changed, 1054 insertions(+), 577 deletions(-) create mode 100755 .kokoro/populate-secrets.sh diff --git a/.kokoro/docs/common.cfg b/.kokoro/docs/common.cfg index 9049798..0f6e352 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 3d13d98..8a5fefa 100644 --- a/.kokoro/release/common.cfg +++ b/.kokoro/release/common.cfg @@ -23,42 +23,18 @@ env_vars: { value: "github/python-area120-tables/.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 a570af5..846fbd7 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-area120-tables/.kokoro/test-samples.sh" diff --git a/.kokoro/samples/python3.7/common.cfg b/.kokoro/samples/python3.7/common.cfg index fa5e5cb..b7444b5 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-area120-tables/.kokoro/test-samples.sh" diff --git a/.kokoro/samples/python3.8/common.cfg b/.kokoro/samples/python3.8/common.cfg index 864c949..ac84ade 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-area120-tables/.kokoro/test-samples.sh" diff --git a/.kokoro/test-samples.sh b/.kokoro/test-samples.sh index b7c23dc..2871e30 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 5432a12..6d6f376 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/conf.py b/docs/conf.py index 7301b05..577ad11 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/docs/tables_v1alpha1/types.rst b/docs/tables_v1alpha1/types.rst index 2e6bb87..9c77b6c 100644 --- a/docs/tables_v1alpha1/types.rst +++ b/docs/tables_v1alpha1/types.rst @@ -3,3 +3,4 @@ Types for Google Area120 Tables v1alpha1 API .. automodule:: google.area120.tables_v1alpha1.types :members: + :show-inheritance: diff --git a/google/area120/tables_v1alpha1/services/tables_service/async_client.py b/google/area120/tables_v1alpha1/services/tables_service/async_client.py index 57e5ddc..5b535d3 100644 --- a/google/area120/tables_v1alpha1/services/tables_service/async_client.py +++ b/google/area120/tables_v1alpha1/services/tables_service/async_client.py @@ -56,10 +56,51 @@ class TablesServiceAsyncClient: DEFAULT_MTLS_ENDPOINT = TablesServiceClient.DEFAULT_MTLS_ENDPOINT row_path = staticmethod(TablesServiceClient.row_path) + parse_row_path = staticmethod(TablesServiceClient.parse_row_path) + table_path = staticmethod(TablesServiceClient.table_path) + parse_table_path = staticmethod(TablesServiceClient.parse_table_path) + + common_billing_account_path = staticmethod( + TablesServiceClient.common_billing_account_path + ) + parse_common_billing_account_path = staticmethod( + TablesServiceClient.parse_common_billing_account_path + ) + + common_folder_path = staticmethod(TablesServiceClient.common_folder_path) + parse_common_folder_path = staticmethod( + TablesServiceClient.parse_common_folder_path + ) + + common_organization_path = staticmethod( + TablesServiceClient.common_organization_path + ) + parse_common_organization_path = staticmethod( + TablesServiceClient.parse_common_organization_path + ) + + common_project_path = staticmethod(TablesServiceClient.common_project_path) + parse_common_project_path = staticmethod( + TablesServiceClient.parse_common_project_path + ) + + common_location_path = staticmethod(TablesServiceClient.common_location_path) + parse_common_location_path = staticmethod( + TablesServiceClient.parse_common_location_path + ) from_service_account_file = TablesServiceClient.from_service_account_file from_service_account_json = from_service_account_file + @property + def transport(self) -> TablesServiceTransport: + """Return the transport used by the client instance. + + Returns: + TablesServiceTransport: The transport used by the client instance. + """ + return self._client.transport + get_transport_class = functools.partial( type(TablesServiceClient).get_transport_class, type(TablesServiceClient) ) @@ -86,16 +127,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 @@ -144,7 +188,8 @@ async def get_table( # 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." @@ -269,7 +314,8 @@ async def get_row( # 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." @@ -344,7 +390,8 @@ async def list_rows( # 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." @@ -426,7 +473,8 @@ async def create_row( # 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, row]): + has_flattened_params = any([parent, row]) + 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." @@ -553,7 +601,8 @@ async def update_row( # 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([row, update_mask]): + has_flattened_params = any([row, 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." @@ -672,7 +721,8 @@ async def delete_row( # Create or coerce a protobuf request object. # Sanity check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - if request is not None and any([name]): + has_flattened_params = any([name]) + if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " "the individual field arguments should be set." diff --git a/google/area120/tables_v1alpha1/services/tables_service/client.py b/google/area120/tables_v1alpha1/services/tables_service/client.py index a6ba3a3..b802231 100644 --- a/google/area120/tables_v1alpha1/services/tables_service/client.py +++ b/google/area120/tables_v1alpha1/services/tables_service/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 @@ -137,6 +139,15 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): from_service_account_json = from_service_account_file + @property + def transport(self) -> TablesServiceTransport: + """Return the transport used by the client instance. + + Returns: + TablesServiceTransport: The transport used by the client instance. + """ + return self._transport + @staticmethod def row_path(table: str, row: str,) -> str: """Return a fully-qualified row string.""" @@ -148,12 +159,82 @@ def parse_row_path(path: str) -> Dict[str, str]: m = re.match(r"^tables/(?P.+?)/rows/(?P.+?)$", path) return m.groupdict() if m else {} + @staticmethod + def table_path(table: str,) -> str: + """Return a fully-qualified table string.""" + return "tables/{table}".format(table=table,) + + @staticmethod + def parse_table_path(path: str) -> Dict[str, str]: + """Parse a table path into its component segments.""" + m = re.match(r"^tables/(?P
.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_billing_account_path(billing_account: str,) -> str: + """Return a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format( + billing_account=billing_account, + ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str, str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path(folder: str,) -> str: + """Return a fully-qualified folder string.""" + return "folders/{folder}".format(folder=folder,) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str, str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path(organization: str,) -> str: + """Return a fully-qualified organization string.""" + return "organizations/{organization}".format(organization=organization,) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str, str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path(project: str,) -> str: + """Return a fully-qualified project string.""" + return "projects/{project}".format(project=project,) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str, str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path(project: str, location: str,) -> str: + """Return a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format( + project=project, location=location, + ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str, str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + def __init__( self, *, - credentials: credentials.Credentials = None, - transport: Union[str, TablesServiceTransport] = None, - client_options: ClientOptions = None, + credentials: Optional[credentials.Credentials] = None, + transport: Union[str, TablesServiceTransport, None] = None, + client_options: Optional[client_options_lib.ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: """Instantiate the tables service client. @@ -167,23 +248,26 @@ def __init__( transport (Union[str, ~.TablesServiceTransport]): The transport to use. If set to None, a transport is chosen automatically. - client_options (ClientOptions): Custom options for the client. It - won't take effect if a ``transport`` instance is provided. + client_options (client_options_lib.ClientOptions): Custom options for the + client. It won't take effect if a ``transport`` instance is provided. (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT environment variable can also be used to override the endpoint: "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint, this is the default value for - the environment variable) and "auto" (auto switch to the default - mTLS endpoint if client SSL credentials is present). However, - the ``api_endpoint`` property takes precedence if provided. - (2) The ``client_cert_source`` property is used to provide client - SSL credentials for mutual TLS transport. If not provided, the - default SSL credentials will be used if present. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing your own client library. Raises: @@ -191,29 +275,47 @@ def __init__( creation failed for any reason. """ if isinstance(client_options, dict): - client_options = ClientOptions.from_dict(client_options) + client_options = client_options_lib.from_dict(client_options) if client_options is None: - client_options = ClientOptions.ClientOptions() + client_options = client_options_lib.ClientOptions() + + # Create SSL credentials for mutual TLS if needed. + use_client_cert = bool( + util.strtobool(os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false")) + ) + + ssl_credentials = None + is_mtls = False + if use_client_cert: + if client_options.client_cert_source: + import grpc # type: ignore - if client_options.api_endpoint is None: - use_mtls_env = os.getenv("GOOGLE_API_USE_MTLS", "never") + cert, key = client_options.client_cert_source() + ssl_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + is_mtls = True + else: + creds = SslCredentials() + is_mtls = creds.is_mtls + ssl_credentials = creds.ssl_credentials if is_mtls else None + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + else: + use_mtls_env = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") if use_mtls_env == "never": - client_options.api_endpoint = self.DEFAULT_ENDPOINT + api_endpoint = self.DEFAULT_ENDPOINT elif use_mtls_env == "always": - client_options.api_endpoint = self.DEFAULT_MTLS_ENDPOINT + api_endpoint = self.DEFAULT_MTLS_ENDPOINT elif use_mtls_env == "auto": - has_client_cert_source = ( - client_options.client_cert_source is not None - or mtls.has_default_client_cert_source() - ) - client_options.api_endpoint = ( - self.DEFAULT_MTLS_ENDPOINT - if has_client_cert_source - else self.DEFAULT_ENDPOINT + api_endpoint = ( + self.DEFAULT_MTLS_ENDPOINT if is_mtls else self.DEFAULT_ENDPOINT ) else: raise MutualTLSChannelError( - "Unsupported GOOGLE_API_USE_MTLS value. Accepted values: never, auto, always" + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted values: never, auto, always" ) # Save or instantiate the transport. @@ -237,10 +339,9 @@ def __init__( self._transport = Transport( credentials=credentials, credentials_file=client_options.credentials_file, - host=client_options.api_endpoint, + host=api_endpoint, scopes=client_options.scopes, - api_mtls_endpoint=client_options.api_endpoint, - client_cert_source=client_options.client_cert_source, + ssl_channel_credentials=ssl_credentials, quota_project_id=client_options.quota_project_id, client_info=client_info, ) diff --git a/google/area120/tables_v1alpha1/services/tables_service/transports/grpc.py b/google/area120/tables_v1alpha1/services/tables_service/transports/grpc.py index 368d7be..d91fb48 100644 --- a/google/area120/tables_v1alpha1/services/tables_service/transports/grpc.py +++ b/google/area120/tables_v1alpha1/services/tables_service/transports/grpc.py @@ -15,6 +15,7 @@ # limitations under the License. # +import warnings from typing import Callable, Dict, Optional, Sequence, Tuple from google.api_core import grpc_helpers # type: ignore @@ -23,7 +24,6 @@ from google.auth import credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore - import grpc # type: ignore from google.area120.tables_v1alpha1.types import tables @@ -66,6 +66,7 @@ def __init__( channel: grpc.Channel = None, api_mtls_endpoint: str = None, client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, quota_project_id: Optional[str] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: @@ -86,20 +87,22 @@ def __init__( ignored if ``channel`` is provided. channel (Optional[grpc.Channel]): A ``Channel`` instance through which to make calls. - api_mtls_endpoint (Optional[str]): The mutual TLS endpoint. If - provided, it overrides the ``host`` argument and tries to create + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create a mutual TLS channel with client SSL credentials from ``client_cert_source`` or applicatin default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): A - callback to provide client SSL certificate bytes and private key - bytes, both in PEM format. It is ignored if ``api_mtls_endpoint`` - is None. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for grpc channel. It is ignored if ``channel`` is provided. quota_project_id (Optional[str]): An optional project to use for billing and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing your own client library. Raises: @@ -108,6 +111,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. @@ -115,7 +120,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 @@ -146,6 +157,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] @@ -206,19 +235,8 @@ def create_channel( @property def grpc_channel(self) -> grpc.Channel: - """Create the channel designed to connect to this service. - - This property caches on the instance; repeated calls return - the same channel. + """Return the channel designed to connect to this service. """ - # Sanity check: Only create a new channel if we do not already - # have one. - if not hasattr(self, "_grpc_channel"): - self._grpc_channel = self.create_channel( - self._host, credentials=self._credentials, - ) - - # Return the channel from cache. return self._grpc_channel @property diff --git a/google/area120/tables_v1alpha1/services/tables_service/transports/grpc_asyncio.py b/google/area120/tables_v1alpha1/services/tables_service/transports/grpc_asyncio.py index eee9501..4f5b3b6 100644 --- a/google/area120/tables_v1alpha1/services/tables_service/transports/grpc_asyncio.py +++ b/google/area120/tables_v1alpha1/services/tables_service/transports/grpc_asyncio.py @@ -15,10 +15,12 @@ # limitations under the License. # +import warnings from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple from google.api_core import gapic_v1 # type: ignore from google.api_core import grpc_helpers_async # type: ignore +from google import auth # type: ignore from google.auth import credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore @@ -108,6 +110,7 @@ def __init__( channel: aio.Channel = None, api_mtls_endpoint: str = None, client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, quota_project_id=None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: @@ -129,14 +132,16 @@ def __init__( are passed to :func:`google.auth.default`. channel (Optional[aio.Channel]): A ``Channel`` instance through which to make calls. - api_mtls_endpoint (Optional[str]): The mutual TLS endpoint. If - provided, it overrides the ``host`` argument and tries to create + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create a mutual TLS channel with client SSL credentials from ``client_cert_source`` or applicatin default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): A - callback to provide client SSL certificate bytes and private key - bytes, both in PEM format. It is ignored if ``api_mtls_endpoint`` - is None. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for grpc channel. It is ignored if ``channel`` is provided. quota_project_id (Optional[str]): An optional project to use for billing and quota. client_info (google.api_core.gapic_v1.client_info.ClientInfo): @@ -151,6 +156,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. @@ -158,13 +165,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: @@ -184,6 +202,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__( @@ -204,13 +240,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/area120/tables_v1alpha1/types/tables.py b/google/area120/tables_v1alpha1/types/tables.py index e3cfcf5..c3381d5 100644 --- a/google/area120/tables_v1alpha1/types/tables.py +++ b/google/area120/tables_v1alpha1/types/tables.py @@ -220,7 +220,7 @@ class BatchCreateRowsRequest(proto.Message): parent = proto.Field(proto.STRING, number=1) - requests = proto.RepeatedField(proto.MESSAGE, number=2, message=CreateRowRequest,) + requests = proto.RepeatedField(proto.MESSAGE, number=2, message="CreateRowRequest",) class BatchCreateRowsResponse(proto.Message): @@ -270,7 +270,7 @@ class BatchUpdateRowsRequest(proto.Message): parent = proto.Field(proto.STRING, number=1) - requests = proto.RepeatedField(proto.MESSAGE, number=2, message=UpdateRowRequest,) + requests = proto.RepeatedField(proto.MESSAGE, number=2, message="UpdateRowRequest",) class BatchUpdateRowsResponse(proto.Message): diff --git a/noxfile.py b/noxfile.py index 998ee40..93a8cc2 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/synth.metadata b/synth.metadata index 7c1e449..46e3f07 100644 --- a/synth.metadata +++ b/synth.metadata @@ -3,22 +3,30 @@ { "git": { "name": ".", - "remote": "sso://devrel/cloud/libraries/python/python-area120-tables", - "sha": "7c9b3c552c3e99934c71bc64f6f6421343470875" + "remote": "git@github.com:googleapis/python-area120-tables", + "sha": "5522f040f009f2ffd8e11eaa21b9ca8fdc8591fa" + } + }, + { + "git": { + "name": "googleapis", + "remote": "https://github.com/googleapis/googleapis.git", + "sha": "6a69c750c3f01a69017662395f90515bbf1fe1ff", + "internalRef": "342721036" } }, { "git": { "name": "synthtool", "remote": "https://github.com/googleapis/synthtool.git", - "sha": "b2c32f1c8a4094f0f47fcf5d10f0b6f2bfb3387d" + "sha": "d5fc0bcf9ea9789c5b0e3154a9e3b29e5cea6116" } }, { "git": { "name": "synthtool", "remote": "https://github.com/googleapis/synthtool.git", - "sha": "b2c32f1c8a4094f0f47fcf5d10f0b6f2bfb3387d" + "sha": "d5fc0bcf9ea9789c5b0e3154a9e3b29e5cea6116" } } ], diff --git a/tests/unit/gapic/tables_v1alpha1/test_tables_service.py b/tests/unit/gapic/tables_v1alpha1/test_tables_service.py index 3e50d69..df44b4c 100644 --- a/tests/unit/gapic/tables_v1alpha1/test_tables_service.py +++ b/tests/unit/gapic/tables_v1alpha1/test_tables_service.py @@ -37,7 +37,6 @@ from google.area120.tables_v1alpha1.services.tables_service import pagers from google.area120.tables_v1alpha1.services.tables_service import transports from google.area120.tables_v1alpha1.types import tables -from google.area120.tables_v1alpha1.types import tables as gat_tables from google.auth import credentials from google.auth.exceptions import MutualTLSChannelError from google.oauth2 import service_account @@ -99,12 +98,12 @@ def test_tables_service_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 == "area120tables.googleapis.com:443" + assert client.transport._host == "area120tables.googleapis.com:443" def test_tables_service_client_get_transport_class(): @@ -160,15 +159,14 @@ def test_tables_service_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() @@ -177,15 +175,14 @@ def test_tables_service_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() @@ -194,95 +191,175 @@ def test_tables_service_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", + [ + (TablesServiceClient, transports.TablesServiceGrpcTransport, "grpc", "true"), + ( + TablesServiceAsyncClient, + transports.TablesServiceGrpcAsyncIOTransport, + "grpc_asyncio", + "true", + ), + (TablesServiceClient, transports.TablesServiceGrpcTransport, "grpc", "false"), + ( + TablesServiceAsyncClient, + transports.TablesServiceGrpcAsyncIOTransport, + "grpc_asyncio", + "false", + ), + ], +) +@mock.patch.object( + TablesServiceClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(TablesServiceClient), +) +@mock.patch.object( + TablesServiceAsyncClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(TablesServiceAsyncClient), +) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_tables_service_client_mtls_env_auto( + client_class, transport_class, transport_name, use_client_cert_env +): + # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default + # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. + + # Check the case client_cert_source is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} + ): options = client_options.ClientOptions( client_cert_source=client_cert_source_callback ) with mock.patch.object(transport_class, "__init__") as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_MTLS_ENDPOINT, - scopes=None, - api_mtls_endpoint=client.DEFAULT_MTLS_ENDPOINT, - client_cert_source=client_cert_source_callback, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - - # Check the case api_endpoint is not provided, GOOGLE_API_USE_MTLS is - # "auto", and default_client_cert_source is provided. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS": "auto"}): - with mock.patch.object(transport_class, "__init__") as patched: + ssl_channel_creds = mock.Mock() with mock.patch( - "google.auth.transport.mtls.has_default_client_cert_source", - return_value=True, + "grpc.ssl_channel_credentials", return_value=ssl_channel_creds ): patched.return_value = None - client = client_class() + client = client_class(client_options=options) + + if use_client_cert_env == "false": + expected_ssl_channel_creds = None + expected_host = client.DEFAULT_ENDPOINT + else: + expected_ssl_channel_creds = ssl_channel_creds + expected_host = client.DEFAULT_MTLS_ENDPOINT + patched.assert_called_once_with( credentials=None, credentials_file=None, - host=client.DEFAULT_MTLS_ENDPOINT, + host=expected_host, scopes=None, - api_mtls_endpoint=client.DEFAULT_MTLS_ENDPOINT, - client_cert_source=None, + ssl_channel_credentials=expected_ssl_channel_creds, quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, ) - # Check the case api_endpoint is not provided, GOOGLE_API_USE_MTLS is - # "auto", but client_cert_source and default_client_cert_source are None. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS": "auto"}): + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} + ): with mock.patch.object(transport_class, "__init__") as patched: with mock.patch( - "google.auth.transport.mtls.has_default_client_cert_source", - return_value=False, + "google.auth.transport.grpc.SslCredentials.__init__", return_value=None ): - patched.return_value = None - client = client_class() - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - api_mtls_endpoint=client.DEFAULT_ENDPOINT, - client_cert_source=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS has - # unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS": "Unsupported"}): - with pytest.raises(MutualTLSChannelError): - client = client_class() - - # Check the case quota_project_id is provided - options = client_options.ClientOptions(quota_project_id="octopus") - with mock.patch.object(transport_class, "__init__") as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - api_mtls_endpoint=client.DEFAULT_ENDPOINT, - client_cert_source=None, - quota_project_id="octopus", - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) + with mock.patch( + "google.auth.transport.grpc.SslCredentials.is_mtls", + new_callable=mock.PropertyMock, + ) as is_mtls_mock: + with mock.patch( + "google.auth.transport.grpc.SslCredentials.ssl_credentials", + new_callable=mock.PropertyMock, + ) as ssl_credentials_mock: + if use_client_cert_env == "false": + is_mtls_mock.return_value = False + ssl_credentials_mock.return_value = None + expected_host = client.DEFAULT_ENDPOINT + expected_ssl_channel_creds = None + else: + is_mtls_mock.return_value = True + ssl_credentials_mock.return_value = mock.Mock() + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_ssl_channel_creds = ( + ssl_credentials_mock.return_value + ) + + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + ssl_channel_credentials=expected_ssl_channel_creds, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} + ): + with mock.patch.object(transport_class, "__init__") as patched: + with mock.patch( + "google.auth.transport.grpc.SslCredentials.__init__", return_value=None + ): + with mock.patch( + "google.auth.transport.grpc.SslCredentials.is_mtls", + new_callable=mock.PropertyMock, + ) as is_mtls_mock: + is_mtls_mock.return_value = False + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + ssl_channel_credentials=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) @pytest.mark.parametrize( @@ -309,8 +386,7 @@ def test_tables_service_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, ) @@ -340,8 +416,7 @@ def test_tables_service_client_client_options_credentials_file( credentials_file="credentials.json", host=client.DEFAULT_ENDPOINT, scopes=None, - api_mtls_endpoint=client.DEFAULT_ENDPOINT, - client_cert_source=None, + ssl_channel_credentials=None, quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, ) @@ -360,8 +435,7 @@ def test_tables_service_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, ) @@ -377,7 +451,7 @@ def test_get_table(transport: str = "grpc", request_type=tables.GetTableRequest) request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client._transport.get_table), "__call__") as call: + with mock.patch.object(type(client.transport.get_table), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = tables.Table( name="name_value", display_name="display_name_value", @@ -392,6 +466,7 @@ def test_get_table(transport: str = "grpc", request_type=tables.GetTableRequest) assert args[0] == tables.GetTableRequest() # Establish that the response is the type that we expect. + assert isinstance(response, tables.Table) assert response.name == "name_value" @@ -404,19 +479,19 @@ def test_get_table_from_dict(): @pytest.mark.asyncio -async def test_get_table_async(transport: str = "grpc_asyncio"): +async def test_get_table_async( + transport: str = "grpc_asyncio", request_type=tables.GetTableRequest +): client = TablesServiceAsyncClient( 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 = tables.GetTableRequest() + request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client._client._transport.get_table), "__call__" - ) as call: + with mock.patch.object(type(client.transport.get_table), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( tables.Table(name="name_value", display_name="display_name_value",) @@ -428,7 +503,7 @@ async def test_get_table_async(transport: str = "grpc_asyncio"): assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == request + assert args[0] == tables.GetTableRequest() # Establish that the response is the type that we expect. assert isinstance(response, tables.Table) @@ -438,6 +513,11 @@ async def test_get_table_async(transport: str = "grpc_asyncio"): assert response.display_name == "display_name_value" +@pytest.mark.asyncio +async def test_get_table_async_from_dict(): + await test_get_table_async(request_type=dict) + + def test_get_table_field_headers(): client = TablesServiceClient(credentials=credentials.AnonymousCredentials(),) @@ -447,7 +527,7 @@ def test_get_table_field_headers(): request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client._transport.get_table), "__call__") as call: + with mock.patch.object(type(client.transport.get_table), "__call__") as call: call.return_value = tables.Table() client.get_table(request) @@ -472,9 +552,7 @@ async def test_get_table_field_headers_async(): request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client._client._transport.get_table), "__call__" - ) as call: + with mock.patch.object(type(client.transport.get_table), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(tables.Table()) await client.get_table(request) @@ -493,7 +571,7 @@ def test_get_table_flattened(): client = TablesServiceClient(credentials=credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client._transport.get_table), "__call__") as call: + with mock.patch.object(type(client.transport.get_table), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = tables.Table() @@ -525,9 +603,7 @@ async def test_get_table_flattened_async(): client = TablesServiceAsyncClient(credentials=credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client._client._transport.get_table), "__call__" - ) as call: + with mock.patch.object(type(client.transport.get_table), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = tables.Table() @@ -566,7 +642,7 @@ def test_list_tables(transport: str = "grpc", request_type=tables.ListTablesRequ request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client._transport.list_tables), "__call__") as call: + with mock.patch.object(type(client.transport.list_tables), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = tables.ListTablesResponse( next_page_token="next_page_token_value", @@ -581,6 +657,7 @@ def test_list_tables(transport: str = "grpc", request_type=tables.ListTablesRequ assert args[0] == tables.ListTablesRequest() # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListTablesPager) assert response.next_page_token == "next_page_token_value" @@ -591,19 +668,19 @@ def test_list_tables_from_dict(): @pytest.mark.asyncio -async def test_list_tables_async(transport: str = "grpc_asyncio"): +async def test_list_tables_async( + transport: str = "grpc_asyncio", request_type=tables.ListTablesRequest +): client = TablesServiceAsyncClient( 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 = tables.ListTablesRequest() + request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client._client._transport.list_tables), "__call__" - ) as call: + with mock.patch.object(type(client.transport.list_tables), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( tables.ListTablesResponse(next_page_token="next_page_token_value",) @@ -615,7 +692,7 @@ async def test_list_tables_async(transport: str = "grpc_asyncio"): assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == request + assert args[0] == tables.ListTablesRequest() # Establish that the response is the type that we expect. assert isinstance(response, pagers.ListTablesAsyncPager) @@ -623,11 +700,16 @@ async def test_list_tables_async(transport: str = "grpc_asyncio"): assert response.next_page_token == "next_page_token_value" +@pytest.mark.asyncio +async def test_list_tables_async_from_dict(): + await test_list_tables_async(request_type=dict) + + def test_list_tables_pager(): client = TablesServiceClient(credentials=credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client._transport.list_tables), "__call__") as call: + with mock.patch.object(type(client.transport.list_tables), "__call__") as call: # Set the response to a series of pages. call.side_effect = ( tables.ListTablesResponse( @@ -654,7 +736,7 @@ def test_list_tables_pages(): client = TablesServiceClient(credentials=credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client._transport.list_tables), "__call__") as call: + with mock.patch.object(type(client.transport.list_tables), "__call__") as call: # Set the response to a series of pages. call.side_effect = ( tables.ListTablesResponse( @@ -677,9 +759,7 @@ async def test_list_tables_async_pager(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client._client._transport.list_tables), - "__call__", - new_callable=mock.AsyncMock, + type(client.transport.list_tables), "__call__", new_callable=mock.AsyncMock ) as call: # Set the response to a series of pages. call.side_effect = ( @@ -708,9 +788,7 @@ async def test_list_tables_async_pages(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client._client._transport.list_tables), - "__call__", - new_callable=mock.AsyncMock, + type(client.transport.list_tables), "__call__", new_callable=mock.AsyncMock ) as call: # Set the response to a series of pages. call.side_effect = ( @@ -740,7 +818,7 @@ def test_get_row(transport: str = "grpc", request_type=tables.GetRowRequest): request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client._transport.get_row), "__call__") as call: + with mock.patch.object(type(client.transport.get_row), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = tables.Row(name="name_value",) @@ -753,6 +831,7 @@ def test_get_row(transport: str = "grpc", request_type=tables.GetRowRequest): assert args[0] == tables.GetRowRequest() # Establish that the response is the type that we expect. + assert isinstance(response, tables.Row) assert response.name == "name_value" @@ -763,17 +842,19 @@ def test_get_row_from_dict(): @pytest.mark.asyncio -async def test_get_row_async(transport: str = "grpc_asyncio"): +async def test_get_row_async( + transport: str = "grpc_asyncio", request_type=tables.GetRowRequest +): client = TablesServiceAsyncClient( 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 = tables.GetRowRequest() + request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client._client._transport.get_row), "__call__") as call: + with mock.patch.object(type(client.transport.get_row), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( tables.Row(name="name_value",) @@ -785,7 +866,7 @@ async def test_get_row_async(transport: str = "grpc_asyncio"): assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == request + assert args[0] == tables.GetRowRequest() # Establish that the response is the type that we expect. assert isinstance(response, tables.Row) @@ -793,6 +874,11 @@ async def test_get_row_async(transport: str = "grpc_asyncio"): assert response.name == "name_value" +@pytest.mark.asyncio +async def test_get_row_async_from_dict(): + await test_get_row_async(request_type=dict) + + def test_get_row_field_headers(): client = TablesServiceClient(credentials=credentials.AnonymousCredentials(),) @@ -802,7 +888,7 @@ def test_get_row_field_headers(): request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client._transport.get_row), "__call__") as call: + with mock.patch.object(type(client.transport.get_row), "__call__") as call: call.return_value = tables.Row() client.get_row(request) @@ -827,7 +913,7 @@ async def test_get_row_field_headers_async(): request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client._client._transport.get_row), "__call__") as call: + with mock.patch.object(type(client.transport.get_row), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(tables.Row()) await client.get_row(request) @@ -846,7 +932,7 @@ def test_get_row_flattened(): client = TablesServiceClient(credentials=credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client._transport.get_row), "__call__") as call: + with mock.patch.object(type(client.transport.get_row), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = tables.Row() @@ -878,7 +964,7 @@ async def test_get_row_flattened_async(): client = TablesServiceAsyncClient(credentials=credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client._client._transport.get_row), "__call__") as call: + with mock.patch.object(type(client.transport.get_row), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = tables.Row() @@ -917,7 +1003,7 @@ def test_list_rows(transport: str = "grpc", request_type=tables.ListRowsRequest) request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client._transport.list_rows), "__call__") as call: + with mock.patch.object(type(client.transport.list_rows), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = tables.ListRowsResponse( next_page_token="next_page_token_value", @@ -932,6 +1018,7 @@ def test_list_rows(transport: str = "grpc", request_type=tables.ListRowsRequest) assert args[0] == tables.ListRowsRequest() # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListRowsPager) assert response.next_page_token == "next_page_token_value" @@ -942,19 +1029,19 @@ def test_list_rows_from_dict(): @pytest.mark.asyncio -async def test_list_rows_async(transport: str = "grpc_asyncio"): +async def test_list_rows_async( + transport: str = "grpc_asyncio", request_type=tables.ListRowsRequest +): client = TablesServiceAsyncClient( 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 = tables.ListRowsRequest() + request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client._client._transport.list_rows), "__call__" - ) as call: + with mock.patch.object(type(client.transport.list_rows), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( tables.ListRowsResponse(next_page_token="next_page_token_value",) @@ -966,7 +1053,7 @@ async def test_list_rows_async(transport: str = "grpc_asyncio"): assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == request + assert args[0] == tables.ListRowsRequest() # Establish that the response is the type that we expect. assert isinstance(response, pagers.ListRowsAsyncPager) @@ -974,6 +1061,11 @@ async def test_list_rows_async(transport: str = "grpc_asyncio"): assert response.next_page_token == "next_page_token_value" +@pytest.mark.asyncio +async def test_list_rows_async_from_dict(): + await test_list_rows_async(request_type=dict) + + def test_list_rows_field_headers(): client = TablesServiceClient(credentials=credentials.AnonymousCredentials(),) @@ -983,7 +1075,7 @@ def test_list_rows_field_headers(): request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client._transport.list_rows), "__call__") as call: + with mock.patch.object(type(client.transport.list_rows), "__call__") as call: call.return_value = tables.ListRowsResponse() client.list_rows(request) @@ -1008,9 +1100,7 @@ async def test_list_rows_field_headers_async(): request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client._client._transport.list_rows), "__call__" - ) as call: + with mock.patch.object(type(client.transport.list_rows), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( tables.ListRowsResponse() ) @@ -1031,7 +1121,7 @@ def test_list_rows_flattened(): client = TablesServiceClient(credentials=credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client._transport.list_rows), "__call__") as call: + with mock.patch.object(type(client.transport.list_rows), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = tables.ListRowsResponse() @@ -1063,9 +1153,7 @@ async def test_list_rows_flattened_async(): client = TablesServiceAsyncClient(credentials=credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client._client._transport.list_rows), "__call__" - ) as call: + with mock.patch.object(type(client.transport.list_rows), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = tables.ListRowsResponse() @@ -1100,7 +1188,7 @@ def test_list_rows_pager(): client = TablesServiceClient(credentials=credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client._transport.list_rows), "__call__") as call: + with mock.patch.object(type(client.transport.list_rows), "__call__") as call: # Set the response to a series of pages. call.side_effect = ( tables.ListRowsResponse( @@ -1129,7 +1217,7 @@ def test_list_rows_pages(): client = TablesServiceClient(credentials=credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client._transport.list_rows), "__call__") as call: + with mock.patch.object(type(client.transport.list_rows), "__call__") as call: # Set the response to a series of pages. call.side_effect = ( tables.ListRowsResponse( @@ -1151,9 +1239,7 @@ async def test_list_rows_async_pager(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client._client._transport.list_rows), - "__call__", - new_callable=mock.AsyncMock, + type(client.transport.list_rows), "__call__", new_callable=mock.AsyncMock ) as call: # Set the response to a series of pages. call.side_effect = ( @@ -1181,9 +1267,7 @@ async def test_list_rows_async_pages(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client._client._transport.list_rows), - "__call__", - new_callable=mock.AsyncMock, + type(client.transport.list_rows), "__call__", new_callable=mock.AsyncMock ) as call: # Set the response to a series of pages. call.side_effect = ( @@ -1212,7 +1296,7 @@ def test_create_row(transport: str = "grpc", request_type=tables.CreateRowReques request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client._transport.create_row), "__call__") as call: + with mock.patch.object(type(client.transport.create_row), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = tables.Row(name="name_value",) @@ -1225,6 +1309,7 @@ def test_create_row(transport: str = "grpc", request_type=tables.CreateRowReques assert args[0] == tables.CreateRowRequest() # Establish that the response is the type that we expect. + assert isinstance(response, tables.Row) assert response.name == "name_value" @@ -1235,19 +1320,19 @@ def test_create_row_from_dict(): @pytest.mark.asyncio -async def test_create_row_async(transport: str = "grpc_asyncio"): +async def test_create_row_async( + transport: str = "grpc_asyncio", request_type=tables.CreateRowRequest +): client = TablesServiceAsyncClient( 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 = tables.CreateRowRequest() + request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client._client._transport.create_row), "__call__" - ) as call: + with mock.patch.object(type(client.transport.create_row), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( tables.Row(name="name_value",) @@ -1259,7 +1344,7 @@ async def test_create_row_async(transport: str = "grpc_asyncio"): assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == request + assert args[0] == tables.CreateRowRequest() # Establish that the response is the type that we expect. assert isinstance(response, tables.Row) @@ -1267,6 +1352,11 @@ async def test_create_row_async(transport: str = "grpc_asyncio"): assert response.name == "name_value" +@pytest.mark.asyncio +async def test_create_row_async_from_dict(): + await test_create_row_async(request_type=dict) + + def test_create_row_field_headers(): client = TablesServiceClient(credentials=credentials.AnonymousCredentials(),) @@ -1276,7 +1366,7 @@ def test_create_row_field_headers(): request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client._transport.create_row), "__call__") as call: + with mock.patch.object(type(client.transport.create_row), "__call__") as call: call.return_value = tables.Row() client.create_row(request) @@ -1301,9 +1391,7 @@ async def test_create_row_field_headers_async(): request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client._client._transport.create_row), "__call__" - ) as call: + with mock.patch.object(type(client.transport.create_row), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(tables.Row()) await client.create_row(request) @@ -1322,7 +1410,7 @@ def test_create_row_flattened(): client = TablesServiceClient(credentials=credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client._transport.create_row), "__call__") as call: + with mock.patch.object(type(client.transport.create_row), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = tables.Row() @@ -1360,9 +1448,7 @@ async def test_create_row_flattened_async(): client = TablesServiceAsyncClient(credentials=credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client._client._transport.create_row), "__call__" - ) as call: + with mock.patch.object(type(client.transport.create_row), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = tables.Row() @@ -1410,7 +1496,7 @@ def test_batch_create_rows( # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client._transport.batch_create_rows), "__call__" + type(client.transport.batch_create_rows), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = tables.BatchCreateRowsResponse() @@ -1424,6 +1510,7 @@ def test_batch_create_rows( assert args[0] == tables.BatchCreateRowsRequest() # Establish that the response is the type that we expect. + assert isinstance(response, tables.BatchCreateRowsResponse) @@ -1432,18 +1519,20 @@ def test_batch_create_rows_from_dict(): @pytest.mark.asyncio -async def test_batch_create_rows_async(transport: str = "grpc_asyncio"): +async def test_batch_create_rows_async( + transport: str = "grpc_asyncio", request_type=tables.BatchCreateRowsRequest +): client = TablesServiceAsyncClient( 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 = tables.BatchCreateRowsRequest() + request = request_type() # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client._client._transport.batch_create_rows), "__call__" + type(client.transport.batch_create_rows), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( @@ -1456,12 +1545,17 @@ async def test_batch_create_rows_async(transport: str = "grpc_asyncio"): assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == request + assert args[0] == tables.BatchCreateRowsRequest() # Establish that the response is the type that we expect. assert isinstance(response, tables.BatchCreateRowsResponse) +@pytest.mark.asyncio +async def test_batch_create_rows_async_from_dict(): + await test_batch_create_rows_async(request_type=dict) + + def test_batch_create_rows_field_headers(): client = TablesServiceClient(credentials=credentials.AnonymousCredentials(),) @@ -1472,7 +1566,7 @@ def test_batch_create_rows_field_headers(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client._transport.batch_create_rows), "__call__" + type(client.transport.batch_create_rows), "__call__" ) as call: call.return_value = tables.BatchCreateRowsResponse() @@ -1499,7 +1593,7 @@ async def test_batch_create_rows_field_headers_async(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client._client._transport.batch_create_rows), "__call__" + type(client.transport.batch_create_rows), "__call__" ) as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( tables.BatchCreateRowsResponse() @@ -1527,7 +1621,7 @@ def test_update_row(transport: str = "grpc", request_type=tables.UpdateRowReques request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client._transport.update_row), "__call__") as call: + with mock.patch.object(type(client.transport.update_row), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = tables.Row(name="name_value",) @@ -1540,6 +1634,7 @@ def test_update_row(transport: str = "grpc", request_type=tables.UpdateRowReques assert args[0] == tables.UpdateRowRequest() # Establish that the response is the type that we expect. + assert isinstance(response, tables.Row) assert response.name == "name_value" @@ -1550,19 +1645,19 @@ def test_update_row_from_dict(): @pytest.mark.asyncio -async def test_update_row_async(transport: str = "grpc_asyncio"): +async def test_update_row_async( + transport: str = "grpc_asyncio", request_type=tables.UpdateRowRequest +): client = TablesServiceAsyncClient( 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 = tables.UpdateRowRequest() + request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client._client._transport.update_row), "__call__" - ) as call: + with mock.patch.object(type(client.transport.update_row), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( tables.Row(name="name_value",) @@ -1574,7 +1669,7 @@ async def test_update_row_async(transport: str = "grpc_asyncio"): assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == request + assert args[0] == tables.UpdateRowRequest() # Establish that the response is the type that we expect. assert isinstance(response, tables.Row) @@ -1582,6 +1677,11 @@ async def test_update_row_async(transport: str = "grpc_asyncio"): assert response.name == "name_value" +@pytest.mark.asyncio +async def test_update_row_async_from_dict(): + await test_update_row_async(request_type=dict) + + def test_update_row_field_headers(): client = TablesServiceClient(credentials=credentials.AnonymousCredentials(),) @@ -1591,7 +1691,7 @@ def test_update_row_field_headers(): request.row.name = "row.name/value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client._transport.update_row), "__call__") as call: + with mock.patch.object(type(client.transport.update_row), "__call__") as call: call.return_value = tables.Row() client.update_row(request) @@ -1616,9 +1716,7 @@ async def test_update_row_field_headers_async(): request.row.name = "row.name/value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client._client._transport.update_row), "__call__" - ) as call: + with mock.patch.object(type(client.transport.update_row), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(tables.Row()) await client.update_row(request) @@ -1637,7 +1735,7 @@ def test_update_row_flattened(): client = TablesServiceClient(credentials=credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client._transport.update_row), "__call__") as call: + with mock.patch.object(type(client.transport.update_row), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = tables.Row() @@ -1676,9 +1774,7 @@ async def test_update_row_flattened_async(): client = TablesServiceAsyncClient(credentials=credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client._client._transport.update_row), "__call__" - ) as call: + with mock.patch.object(type(client.transport.update_row), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = tables.Row() @@ -1727,7 +1823,7 @@ def test_batch_update_rows( # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client._transport.batch_update_rows), "__call__" + type(client.transport.batch_update_rows), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = tables.BatchUpdateRowsResponse() @@ -1741,6 +1837,7 @@ def test_batch_update_rows( assert args[0] == tables.BatchUpdateRowsRequest() # Establish that the response is the type that we expect. + assert isinstance(response, tables.BatchUpdateRowsResponse) @@ -1749,18 +1846,20 @@ def test_batch_update_rows_from_dict(): @pytest.mark.asyncio -async def test_batch_update_rows_async(transport: str = "grpc_asyncio"): +async def test_batch_update_rows_async( + transport: str = "grpc_asyncio", request_type=tables.BatchUpdateRowsRequest +): client = TablesServiceAsyncClient( 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 = tables.BatchUpdateRowsRequest() + request = request_type() # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client._client._transport.batch_update_rows), "__call__" + type(client.transport.batch_update_rows), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( @@ -1773,12 +1872,17 @@ async def test_batch_update_rows_async(transport: str = "grpc_asyncio"): assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == request + assert args[0] == tables.BatchUpdateRowsRequest() # Establish that the response is the type that we expect. assert isinstance(response, tables.BatchUpdateRowsResponse) +@pytest.mark.asyncio +async def test_batch_update_rows_async_from_dict(): + await test_batch_update_rows_async(request_type=dict) + + def test_batch_update_rows_field_headers(): client = TablesServiceClient(credentials=credentials.AnonymousCredentials(),) @@ -1789,7 +1893,7 @@ def test_batch_update_rows_field_headers(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client._transport.batch_update_rows), "__call__" + type(client.transport.batch_update_rows), "__call__" ) as call: call.return_value = tables.BatchUpdateRowsResponse() @@ -1816,7 +1920,7 @@ async def test_batch_update_rows_field_headers_async(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client._client._transport.batch_update_rows), "__call__" + type(client.transport.batch_update_rows), "__call__" ) as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( tables.BatchUpdateRowsResponse() @@ -1844,7 +1948,7 @@ def test_delete_row(transport: str = "grpc", request_type=tables.DeleteRowReques request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client._transport.delete_row), "__call__") as call: + with mock.patch.object(type(client.transport.delete_row), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = None @@ -1865,19 +1969,19 @@ def test_delete_row_from_dict(): @pytest.mark.asyncio -async def test_delete_row_async(transport: str = "grpc_asyncio"): +async def test_delete_row_async( + transport: str = "grpc_asyncio", request_type=tables.DeleteRowRequest +): client = TablesServiceAsyncClient( 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 = tables.DeleteRowRequest() + request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client._client._transport.delete_row), "__call__" - ) as call: + with mock.patch.object(type(client.transport.delete_row), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) @@ -1887,12 +1991,17 @@ async def test_delete_row_async(transport: str = "grpc_asyncio"): assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == request + assert args[0] == tables.DeleteRowRequest() # Establish that the response is the type that we expect. assert response is None +@pytest.mark.asyncio +async def test_delete_row_async_from_dict(): + await test_delete_row_async(request_type=dict) + + def test_delete_row_field_headers(): client = TablesServiceClient(credentials=credentials.AnonymousCredentials(),) @@ -1902,7 +2011,7 @@ def test_delete_row_field_headers(): request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client._transport.delete_row), "__call__") as call: + with mock.patch.object(type(client.transport.delete_row), "__call__") as call: call.return_value = None client.delete_row(request) @@ -1927,9 +2036,7 @@ async def test_delete_row_field_headers_async(): request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client._client._transport.delete_row), "__call__" - ) as call: + with mock.patch.object(type(client.transport.delete_row), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) await client.delete_row(request) @@ -1948,7 +2055,7 @@ def test_delete_row_flattened(): client = TablesServiceClient(credentials=credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client._transport.delete_row), "__call__") as call: + with mock.patch.object(type(client.transport.delete_row), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = None @@ -1980,9 +2087,7 @@ async def test_delete_row_flattened_async(): client = TablesServiceAsyncClient(credentials=credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client._client._transport.delete_row), "__call__" - ) as call: + with mock.patch.object(type(client.transport.delete_row), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = None @@ -2047,7 +2152,7 @@ def test_transport_instance(): credentials=credentials.AnonymousCredentials(), ) client = TablesServiceClient(transport=transport) - assert client._transport is transport + assert client.transport is transport def test_transport_get_channel(): @@ -2065,10 +2170,25 @@ def test_transport_get_channel(): assert channel +@pytest.mark.parametrize( + "transport_class", + [ + transports.TablesServiceGrpcTransport, + transports.TablesServiceGrpcAsyncIOTransport, + ], +) +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 = TablesServiceClient(credentials=credentials.AnonymousCredentials(),) - assert isinstance(client._transport, transports.TablesServiceGrpcTransport,) + assert isinstance(client.transport, transports.TablesServiceGrpcTransport,) def test_tables_service_base_transport_error(): @@ -2133,6 +2253,17 @@ def test_tables_service_base_transport_with_credentials_file(): ) +def test_tables_service_base_transport_with_adc(): + # Test the default credentials are used if credentials and credentials_file are None. + with mock.patch.object(auth, "default") as adc, mock.patch( + "google.area120.tables_v1alpha1.services.tables_service.transports.TablesServiceTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + adc.return_value = (credentials.AnonymousCredentials(), None) + transport = transports.TablesServiceTransport() + adc.assert_called_once() + + def test_tables_service_auth_adc(): # If no credentials are provided, we should use ADC credentials. with mock.patch.object(auth, "default") as adc: @@ -2177,7 +2308,7 @@ def test_tables_service_host_no_port(): api_endpoint="area120tables.googleapis.com" ), ) - assert client._transport._host == "area120tables.googleapis.com:443" + assert client.transport._host == "area120tables.googleapis.com:443" def test_tables_service_host_with_port(): @@ -2187,209 +2318,129 @@ def test_tables_service_host_with_port(): api_endpoint="area120tables.googleapis.com:8000" ), ) - assert client._transport._host == "area120tables.googleapis.com:8000" + assert client.transport._host == "area120tables.googleapis.com:8000" def test_tables_service_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.TablesServiceGrpcTransport( - 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_tables_service_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.TablesServiceGrpcAsyncIOTransport( - host="squid.clam.whelk", - channel=channel, - api_mtls_endpoint="mtls.squid.clam.whelk", - client_cert_source=callback, + host="squid.clam.whelk", channel=channel, ) assert transport.grpc_channel == channel assert transport._host == "squid.clam.whelk:443" - assert not callback.called - - -@mock.patch("grpc.ssl_channel_credentials", autospec=True) -@mock.patch("google.api_core.grpc_helpers.create_channel", autospec=True) -def test_tables_service_grpc_transport_channel_mtls_with_client_cert_source( - grpc_create_channel, grpc_ssl_channel_cred -): - # Check that if channel is None, but api_mtls_endpoint and client_cert_source - # are provided, then a mTLS channel will be created. - mock_cred = mock.Mock() - - mock_ssl_cred = mock.Mock() - grpc_ssl_channel_cred.return_value = mock_ssl_cred - - mock_grpc_channel = mock.Mock() - grpc_create_channel.return_value = mock_grpc_channel - - transport = transports.TablesServiceGrpcTransport( - 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/drive", - "https://www.googleapis.com/auth/drive.file", - "https://www.googleapis.com/auth/drive.readonly", - "https://www.googleapis.com/auth/spreadsheets", - "https://www.googleapis.com/auth/spreadsheets.readonly", - ), - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - ) - assert transport.grpc_channel == mock_grpc_channel - - -@mock.patch("grpc.ssl_channel_credentials", autospec=True) -@mock.patch("google.api_core.grpc_helpers_async.create_channel", autospec=True) -def test_tables_service_grpc_asyncio_transport_channel_mtls_with_client_cert_source( - grpc_create_channel, grpc_ssl_channel_cred -): - # Check that if channel is None, but api_mtls_endpoint and client_cert_source - # are provided, then a mTLS channel will be created. - mock_cred = mock.Mock() - - mock_ssl_cred = mock.Mock() - grpc_ssl_channel_cred.return_value = mock_ssl_cred - - mock_grpc_channel = mock.Mock() - grpc_create_channel.return_value = mock_grpc_channel - - transport = transports.TablesServiceGrpcAsyncIOTransport( - 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/drive", - "https://www.googleapis.com/auth/drive.file", - "https://www.googleapis.com/auth/drive.readonly", - "https://www.googleapis.com/auth/spreadsheets", - "https://www.googleapis.com/auth/spreadsheets.readonly", - ), - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - ) - assert transport.grpc_channel == mock_grpc_channel + assert transport._ssl_channel_credentials == None @pytest.mark.parametrize( - "api_mtls_endpoint", ["mtls.squid.clam.whelk", "mtls.squid.clam.whelk:443"] + "transport_class", + [ + transports.TablesServiceGrpcTransport, + transports.TablesServiceGrpcAsyncIOTransport, + ], ) -@mock.patch("google.api_core.grpc_helpers.create_channel", autospec=True) -def test_tables_service_grpc_transport_channel_mtls_with_adc( - grpc_create_channel, api_mtls_endpoint -): - # Check that if channel and client_cert_source are None, but api_mtls_endpoint - # is provided, then a mTLS channel will be created with SSL ADC. - mock_grpc_channel = mock.Mock() - grpc_create_channel.return_value = mock_grpc_channel - - # Mock google.auth.transport.grpc.SslCredentials class. - mock_ssl_cred = mock.Mock() - with mock.patch.multiple( - "google.auth.transport.grpc.SslCredentials", - __init__=mock.Mock(return_value=None), - ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), - ): - mock_cred = mock.Mock() - transport = transports.TablesServiceGrpcTransport( - 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/drive", - "https://www.googleapis.com/auth/drive.file", - "https://www.googleapis.com/auth/drive.readonly", - "https://www.googleapis.com/auth/spreadsheets", - "https://www.googleapis.com/auth/spreadsheets.readonly", - ), - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - ) - assert transport.grpc_channel == mock_grpc_channel +def test_tables_service_transport_channel_mtls_with_client_cert_source(transport_class): + with mock.patch( + "grpc.ssl_channel_credentials", autospec=True + ) as grpc_ssl_channel_cred: + with mock.patch.object( + transport_class, "create_channel", 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/drive", + "https://www.googleapis.com/auth/drive.file", + "https://www.googleapis.com/auth/drive.readonly", + "https://www.googleapis.com/auth/spreadsheets", + "https://www.googleapis.com/auth/spreadsheets.readonly", + ), + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + ) + assert transport.grpc_channel == mock_grpc_channel + assert transport._ssl_channel_credentials == mock_ssl_cred @pytest.mark.parametrize( - "api_mtls_endpoint", ["mtls.squid.clam.whelk", "mtls.squid.clam.whelk:443"] + "transport_class", + [ + transports.TablesServiceGrpcTransport, + transports.TablesServiceGrpcAsyncIOTransport, + ], ) -@mock.patch("google.api_core.grpc_helpers_async.create_channel", autospec=True) -def test_tables_service_grpc_asyncio_transport_channel_mtls_with_adc( - grpc_create_channel, api_mtls_endpoint -): - # Check that if channel and client_cert_source are None, but api_mtls_endpoint - # is provided, then a mTLS channel will be created with SSL ADC. - mock_grpc_channel = mock.Mock() - grpc_create_channel.return_value = mock_grpc_channel - - # Mock google.auth.transport.grpc.SslCredentials class. +def test_tables_service_transport_channel_mtls_with_adc(transport_class): mock_ssl_cred = mock.Mock() with mock.patch.multiple( "google.auth.transport.grpc.SslCredentials", __init__=mock.Mock(return_value=None), ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), ): - mock_cred = mock.Mock() - transport = transports.TablesServiceGrpcAsyncIOTransport( - 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/drive", - "https://www.googleapis.com/auth/drive.file", - "https://www.googleapis.com/auth/drive.readonly", - "https://www.googleapis.com/auth/spreadsheets", - "https://www.googleapis.com/auth/spreadsheets.readonly", - ), - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - ) - assert transport.grpc_channel == mock_grpc_channel + with mock.patch.object( + transport_class, "create_channel", autospec=True + ) as grpc_create_channel: + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + mock_cred = mock.Mock() + + with pytest.warns(DeprecationWarning): + transport = transport_class( + host="squid.clam.whelk", + credentials=mock_cred, + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=None, + ) + + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=mock_cred, + credentials_file=None, + scopes=( + "https://www.googleapis.com/auth/drive", + "https://www.googleapis.com/auth/drive.file", + "https://www.googleapis.com/auth/drive.readonly", + "https://www.googleapis.com/auth/spreadsheets", + "https://www.googleapis.com/auth/spreadsheets.readonly", + ), + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + ) + assert transport.grpc_channel == mock_grpc_channel def test_row_path(): @@ -2413,6 +2464,126 @@ def test_parse_row_path(): assert expected == actual +def test_table_path(): + table = "oyster" + + expected = "tables/{table}".format(table=table,) + actual = TablesServiceClient.table_path(table) + assert expected == actual + + +def test_parse_table_path(): + expected = { + "table": "nudibranch", + } + path = TablesServiceClient.table_path(**expected) + + # Check that the path construction is reversible. + actual = TablesServiceClient.parse_table_path(path) + assert expected == actual + + +def test_common_billing_account_path(): + billing_account = "cuttlefish" + + expected = "billingAccounts/{billing_account}".format( + billing_account=billing_account, + ) + actual = TablesServiceClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "mussel", + } + path = TablesServiceClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = TablesServiceClient.parse_common_billing_account_path(path) + assert expected == actual + + +def test_common_folder_path(): + folder = "winkle" + + expected = "folders/{folder}".format(folder=folder,) + actual = TablesServiceClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "nautilus", + } + path = TablesServiceClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = TablesServiceClient.parse_common_folder_path(path) + assert expected == actual + + +def test_common_organization_path(): + organization = "scallop" + + expected = "organizations/{organization}".format(organization=organization,) + actual = TablesServiceClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "abalone", + } + path = TablesServiceClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = TablesServiceClient.parse_common_organization_path(path) + assert expected == actual + + +def test_common_project_path(): + project = "squid" + + expected = "projects/{project}".format(project=project,) + actual = TablesServiceClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "clam", + } + path = TablesServiceClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = TablesServiceClient.parse_common_project_path(path) + assert expected == actual + + +def test_common_location_path(): + project = "whelk" + location = "octopus" + + expected = "projects/{project}/locations/{location}".format( + project=project, location=location, + ) + actual = TablesServiceClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "oyster", + "location": "nudibranch", + } + path = TablesServiceClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = TablesServiceClient.parse_common_location_path(path) + assert expected == actual + + def test_client_withDEFAULT_CLIENT_INFO(): client_info = gapic_v1.client_info.ClientInfo()