diff --git a/.github/ISSUE_TEMPLATE/bug_report.md b/.github/ISSUE_TEMPLATE/bug_report.md index 802e875..c510027 100644 --- a/.github/ISSUE_TEMPLATE/bug_report.md +++ b/.github/ISSUE_TEMPLATE/bug_report.md @@ -20,7 +20,7 @@ If you are still having issues, please be sure to include as much information as - OS type and version: - Python version: `python --version` - pip version: `pip --version` - - `google-cloud-recpatcha-enterprise` version: `pip show google-cloud-recpatcha-enterprise` + - `google-cloud-recpatchaenterprise` version: `pip show google-cloud-recpatchaenterprise` #### Steps to reproduce diff --git a/.kokoro/build.sh b/.kokoro/build.sh index aa02f76..6782ff1 100755 --- a/.kokoro/build.sh +++ b/.kokoro/build.sh @@ -15,7 +15,11 @@ set -eo pipefail -cd github/python-recaptcha-enterprise +if [[ -z "${PROJECT_ROOT:-}" ]]; then + PROJECT_ROOT="github/python-recaptcha-enterprise" +fi + +cd "${PROJECT_ROOT}" # Disable buffering, so that the logs stream through. export PYTHONUNBUFFERED=1 @@ -30,16 +34,16 @@ export GOOGLE_APPLICATION_CREDENTIALS=${KOKORO_GFILE_DIR}/service-account.json export PROJECT_ID=$(cat "${KOKORO_GFILE_DIR}/project-id.json") # Remove old nox -python3.6 -m pip uninstall --yes --quiet nox-automation +python3 -m pip uninstall --yes --quiet nox-automation # Install nox -python3.6 -m pip install --upgrade --quiet nox -python3.6 -m nox --version +python3 -m pip install --upgrade --quiet nox +python3 -m nox --version # If NOX_SESSION is set, it only runs the specified session, # otherwise run all the sessions. if [[ -n "${NOX_SESSION:-}" ]]; then - python3.6 -m nox -s "${NOX_SESSION:-}" + python3 -m nox -s ${NOX_SESSION:-} else - python3.6 -m nox + python3 -m nox fi diff --git a/.kokoro/docs/docs-presubmit.cfg b/.kokoro/docs/docs-presubmit.cfg index 1118107..0a65e6a 100644 --- a/.kokoro/docs/docs-presubmit.cfg +++ b/.kokoro/docs/docs-presubmit.cfg @@ -15,3 +15,14 @@ env_vars: { key: "TRAMPOLINE_IMAGE_UPLOAD" value: "false" } + +env_vars: { + key: "TRAMPOLINE_BUILD_FILE" + value: "github/python-recaptcha-enterprise/.kokoro/build.sh" +} + +# Only run this nox session. +env_vars: { + key: "NOX_SESSION" + value: "docs docfx" +} diff --git a/.trampolinerc b/.trampolinerc index 995ee29..c7d663a 100644 --- a/.trampolinerc +++ b/.trampolinerc @@ -18,12 +18,14 @@ required_envvars+=( "STAGING_BUCKET" "V2_STAGING_BUCKET" + "NOX_SESSION" ) # Add env vars which are passed down into the container here. pass_down_envvars+=( "STAGING_BUCKET" "V2_STAGING_BUCKET" + "NOX_SESSION" ) # Prevent unintentional override on the default image. diff --git a/CONTRIBUTING.rst b/CONTRIBUTING.rst index 8f3926d..8744d6d 100644 --- a/CONTRIBUTING.rst +++ b/CONTRIBUTING.rst @@ -193,7 +193,7 @@ instead of ``https://github.com/googleapis/python-recaptcha-enterprise/blob/master/CONTRIBUTING.rst``) may cause problems creating links or rendering the description. -.. _description on PyPI: https://pypi.org/project/google-cloud-recpatcha-enterprise +.. _description on PyPI: https://pypi.org/project/google-cloud-recpatchaenterprise ************************* diff --git a/LICENSE b/LICENSE index a8ee855..d645695 100644 --- a/LICENSE +++ b/LICENSE @@ -1,6 +1,7 @@ - Apache License + + Apache License Version 2.0, January 2004 - https://www.apache.org/licenses/ + http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION @@ -192,7 +193,7 @@ you may not use this file except in compliance with the License. You may obtain a copy of the License at - https://www.apache.org/licenses/LICENSE-2.0 + 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, diff --git a/docs/_static/custom.css b/docs/_static/custom.css index 0abaf22..bcd37bb 100644 --- a/docs/_static/custom.css +++ b/docs/_static/custom.css @@ -1,4 +1,9 @@ div#python2-eol { border-color: red; border-width: medium; -} \ No newline at end of file +} + +/* Ensure minimum width for 'Parameters' / 'Returns' column */ +dl.field-list > dt { + min-width: 100px +} diff --git a/docs/conf.py b/docs/conf.py index 7ad73c5..6ef98c8 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -1,6 +1,6 @@ # -*- coding: utf-8 -*- # -# google-cloud-recpatcha-enterprise documentation build configuration file +# google-cloud-recpatchaenterprise documentation build configuration file # # This file is execfile()d with the current directory set to its # containing dir. @@ -67,7 +67,7 @@ master_doc = "index" # General information about the project. -project = u"google-cloud-recpatcha-enterprise" +project = u"google-cloud-recpatchaenterprise" copyright = u"2019, Google" author = u"Google APIs" @@ -140,7 +140,7 @@ # further. For a list of options available for each theme, see the # documentation. html_theme_options = { - "description": "Google Cloud Client Libraries for google-cloud-recpatcha-enterprise", + "description": "Google Cloud Client Libraries for google-cloud-recpatchaenterprise", "github_user": "googleapis", "github_repo": "python-recaptcha-enterprise", "github_banner": True, @@ -234,7 +234,7 @@ # html_search_scorer = 'scorer.js' # Output file base name for HTML help builder. -htmlhelp_basename = "google-cloud-recpatcha-enterprise-doc" +htmlhelp_basename = "google-cloud-recpatchaenterprise-doc" # -- Options for warnings ------------------------------------------------------ @@ -267,8 +267,8 @@ latex_documents = [ ( master_doc, - "google-cloud-recpatcha-enterprise.tex", - u"google-cloud-recpatcha-enterprise Documentation", + "google-cloud-recpatchaenterprise.tex", + u"google-cloud-recpatchaenterprise Documentation", author, "manual", ) @@ -302,8 +302,8 @@ man_pages = [ ( master_doc, - "google-cloud-recpatcha-enterprise", - u"google-cloud-recpatcha-enterprise Documentation", + "google-cloud-recpatchaenterprise", + u"google-cloud-recpatchaenterprise Documentation", [author], 1, ) @@ -321,11 +321,11 @@ texinfo_documents = [ ( master_doc, - "google-cloud-recpatcha-enterprise", - u"google-cloud-recpatcha-enterprise Documentation", + "google-cloud-recpatchaenterprise", + u"google-cloud-recpatchaenterprise Documentation", author, - "google-cloud-recpatcha-enterprise", - "google-cloud-recpatcha-enterprise Library", + "google-cloud-recpatchaenterprise", + "google-cloud-recpatchaenterprise Library", "APIs", ) ] diff --git a/docs/recaptchaenterprise_v1/recaptcha_enterprise_service.rst b/docs/recaptchaenterprise_v1/recaptcha_enterprise_service.rst new file mode 100644 index 0000000..dcf5173 --- /dev/null +++ b/docs/recaptchaenterprise_v1/recaptcha_enterprise_service.rst @@ -0,0 +1,11 @@ +RecaptchaEnterpriseService +-------------------------------------------- + +.. automodule:: google.cloud.recaptchaenterprise_v1.services.recaptcha_enterprise_service + :members: + :inherited-members: + + +.. automodule:: google.cloud.recaptchaenterprise_v1.services.recaptcha_enterprise_service.pagers + :members: + :inherited-members: diff --git a/docs/recaptchaenterprise_v1/services.rst b/docs/recaptchaenterprise_v1/services.rst index 2398132..4211502 100644 --- a/docs/recaptchaenterprise_v1/services.rst +++ b/docs/recaptchaenterprise_v1/services.rst @@ -1,6 +1,6 @@ -Client for Google Cloud Recaptchaenterprise API -=============================================== +Services for Google Cloud Recaptchaenterprise v1 API +==================================================== +.. toctree:: + :maxdepth: 2 -.. automodule:: google.cloud.recaptchaenterprise_v1 - :members: - :inherited-members: + recaptcha_enterprise_service diff --git a/docs/recaptchaenterprise_v1/types.rst b/docs/recaptchaenterprise_v1/types.rst index 3a726c3..a3967e8 100644 --- a/docs/recaptchaenterprise_v1/types.rst +++ b/docs/recaptchaenterprise_v1/types.rst @@ -1,5 +1,7 @@ -Types for Google Cloud Recaptchaenterprise API -============================================== +Types for Google Cloud Recaptchaenterprise v1 API +================================================= .. automodule:: google.cloud.recaptchaenterprise_v1.types :members: + :undoc-members: + :show-inheritance: diff --git a/google/cloud/recaptchaenterprise/__init__.py b/google/cloud/recaptchaenterprise/__init__.py index 5080fb0..2946999 100644 --- a/google/cloud/recaptchaenterprise/__init__.py +++ b/google/cloud/recaptchaenterprise/__init__.py @@ -15,7 +15,9 @@ # limitations under the License. # - +from google.cloud.recaptchaenterprise_v1.services.recaptcha_enterprise_service.async_client import ( + RecaptchaEnterpriseServiceAsyncClient, +) from google.cloud.recaptchaenterprise_v1.services.recaptcha_enterprise_service.client import ( RecaptchaEnterpriseServiceClient, ) @@ -71,6 +73,7 @@ "Key", "ListKeysRequest", "ListKeysResponse", + "RecaptchaEnterpriseServiceAsyncClient", "RecaptchaEnterpriseServiceClient", "RiskAnalysis", "TokenProperties", diff --git a/google/cloud/recaptchaenterprise_v1/__init__.py b/google/cloud/recaptchaenterprise_v1/__init__.py index 8d71e73..2cfa8bf 100644 --- a/google/cloud/recaptchaenterprise_v1/__init__.py +++ b/google/cloud/recaptchaenterprise_v1/__init__.py @@ -15,7 +15,6 @@ # limitations under the License. # - from .services.recaptcha_enterprise_service import RecaptchaEnterpriseServiceClient from .types.recaptchaenterprise import AndroidKeySettings from .types.recaptchaenterprise import AnnotateAssessmentRequest diff --git a/google/cloud/recaptchaenterprise_v1/services/recaptcha_enterprise_service/__init__.py b/google/cloud/recaptchaenterprise_v1/services/recaptcha_enterprise_service/__init__.py index 264a786..cadcdec 100644 --- a/google/cloud/recaptchaenterprise_v1/services/recaptcha_enterprise_service/__init__.py +++ b/google/cloud/recaptchaenterprise_v1/services/recaptcha_enterprise_service/__init__.py @@ -16,5 +16,9 @@ # from .client import RecaptchaEnterpriseServiceClient +from .async_client import RecaptchaEnterpriseServiceAsyncClient -__all__ = ("RecaptchaEnterpriseServiceClient",) +__all__ = ( + "RecaptchaEnterpriseServiceClient", + "RecaptchaEnterpriseServiceAsyncClient", +) diff --git a/google/cloud/recaptchaenterprise_v1/services/recaptcha_enterprise_service/async_client.py b/google/cloud/recaptchaenterprise_v1/services/recaptcha_enterprise_service/async_client.py new file mode 100644 index 0000000..032d88d --- /dev/null +++ b/google/cloud/recaptchaenterprise_v1/services/recaptcha_enterprise_service/async_client.py @@ -0,0 +1,596 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from collections import OrderedDict +import functools +import re +from typing import Dict, Sequence, Tuple, Type, Union +import pkg_resources + +import google.api_core.client_options as ClientOptions # type: ignore +from google.api_core import exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.recaptchaenterprise_v1.services.recaptcha_enterprise_service import ( + pagers, +) +from google.cloud.recaptchaenterprise_v1.types import recaptchaenterprise +from google.protobuf import timestamp_pb2 as timestamp # type: ignore + +from .transports.base import RecaptchaEnterpriseServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import RecaptchaEnterpriseServiceGrpcAsyncIOTransport +from .client import RecaptchaEnterpriseServiceClient + + +class RecaptchaEnterpriseServiceAsyncClient: + """Service to determine the likelihood an event is legitimate.""" + + _client: RecaptchaEnterpriseServiceClient + + DEFAULT_ENDPOINT = RecaptchaEnterpriseServiceClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = RecaptchaEnterpriseServiceClient.DEFAULT_MTLS_ENDPOINT + + assessment_path = staticmethod(RecaptchaEnterpriseServiceClient.assessment_path) + parse_assessment_path = staticmethod( + RecaptchaEnterpriseServiceClient.parse_assessment_path + ) + key_path = staticmethod(RecaptchaEnterpriseServiceClient.key_path) + parse_key_path = staticmethod(RecaptchaEnterpriseServiceClient.parse_key_path) + + common_billing_account_path = staticmethod( + RecaptchaEnterpriseServiceClient.common_billing_account_path + ) + parse_common_billing_account_path = staticmethod( + RecaptchaEnterpriseServiceClient.parse_common_billing_account_path + ) + + common_folder_path = staticmethod( + RecaptchaEnterpriseServiceClient.common_folder_path + ) + parse_common_folder_path = staticmethod( + RecaptchaEnterpriseServiceClient.parse_common_folder_path + ) + + common_organization_path = staticmethod( + RecaptchaEnterpriseServiceClient.common_organization_path + ) + parse_common_organization_path = staticmethod( + RecaptchaEnterpriseServiceClient.parse_common_organization_path + ) + + common_project_path = staticmethod( + RecaptchaEnterpriseServiceClient.common_project_path + ) + parse_common_project_path = staticmethod( + RecaptchaEnterpriseServiceClient.parse_common_project_path + ) + + common_location_path = staticmethod( + RecaptchaEnterpriseServiceClient.common_location_path + ) + parse_common_location_path = staticmethod( + RecaptchaEnterpriseServiceClient.parse_common_location_path + ) + + from_service_account_info = ( + RecaptchaEnterpriseServiceClient.from_service_account_info + ) + from_service_account_file = ( + RecaptchaEnterpriseServiceClient.from_service_account_file + ) + from_service_account_json = from_service_account_file + + @property + def transport(self) -> RecaptchaEnterpriseServiceTransport: + """Return the transport used by the client instance. + + Returns: + RecaptchaEnterpriseServiceTransport: The transport used by the client instance. + """ + return self._client.transport + + get_transport_class = functools.partial( + type(RecaptchaEnterpriseServiceClient).get_transport_class, + type(RecaptchaEnterpriseServiceClient), + ) + + def __init__( + self, + *, + credentials: credentials.Credentials = None, + transport: Union[str, RecaptchaEnterpriseServiceTransport] = "grpc_asyncio", + client_options: ClientOptions = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiate the recaptcha enterprise service client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, ~.RecaptchaEnterpriseServiceTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (ClientOptions): Custom options for the client. It + won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + """ + + self._client = RecaptchaEnterpriseServiceClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + ) + + async def create_assessment( + self, + request: recaptchaenterprise.CreateAssessmentRequest = None, + *, + parent: str = None, + assessment: recaptchaenterprise.Assessment = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> recaptchaenterprise.Assessment: + r"""Creates an Assessment of the likelihood an event is + legitimate. + + Args: + request (:class:`google.cloud.recaptchaenterprise_v1.types.CreateAssessmentRequest`): + The request object. The create assessment request + message. + parent (:class:`str`): + Required. The name of the project in + which the assessment will be created, in + the format "projects/{project}". + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + assessment (:class:`google.cloud.recaptchaenterprise_v1.types.Assessment`): + Required. The assessment details. + This corresponds to the ``assessment`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.recaptchaenterprise_v1.types.Assessment: + A recaptcha assessment resource. + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, assessment]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = recaptchaenterprise.CreateAssessmentRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if parent is not None: + request.parent = parent + if assessment is not None: + request.assessment = assessment + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.create_assessment, + default_timeout=600.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def annotate_assessment( + self, + request: recaptchaenterprise.AnnotateAssessmentRequest = None, + *, + name: str = None, + annotation: recaptchaenterprise.AnnotateAssessmentRequest.Annotation = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> recaptchaenterprise.AnnotateAssessmentResponse: + r"""Annotates a previously created Assessment to provide + additional information on whether the event turned out + to be authentic or fradulent. + + Args: + request (:class:`google.cloud.recaptchaenterprise_v1.types.AnnotateAssessmentRequest`): + The request object. The request message to annotate an + Assessment. + name (:class:`str`): + Required. The resource name of the + Assessment, in the format + "projects/{project}/assessments/{assessment}". + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + annotation (:class:`google.cloud.recaptchaenterprise_v1.types.AnnotateAssessmentRequest.Annotation`): + Required. The annotation that will be + assigned to the Event. + + This corresponds to the ``annotation`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.recaptchaenterprise_v1.types.AnnotateAssessmentResponse: + Empty response for + AnnotateAssessment. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name, annotation]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = recaptchaenterprise.AnnotateAssessmentRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if name is not None: + request.name = name + if annotation is not None: + request.annotation = annotation + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.annotate_assessment, + default_timeout=600.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def create_key( + self, + request: recaptchaenterprise.CreateKeyRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> recaptchaenterprise.Key: + r"""Creates a new reCAPTCHA Enterprise key. + + Args: + request (:class:`google.cloud.recaptchaenterprise_v1.types.CreateKeyRequest`): + The request object. The create key request message. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.recaptchaenterprise_v1.types.Key: + A key used to identify and configure + applications (web and/or mobile) that + use reCAPTCHA Enterprise. + + """ + # Create or coerce a protobuf request object. + + request = recaptchaenterprise.CreateKeyRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.create_key, + default_timeout=600.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def list_keys( + self, + request: recaptchaenterprise.ListKeysRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListKeysAsyncPager: + r"""Returns the list of all keys that belong to a + project. + + Args: + request (:class:`google.cloud.recaptchaenterprise_v1.types.ListKeysRequest`): + The request object. The list keys request message. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.recaptchaenterprise_v1.services.recaptcha_enterprise_service.pagers.ListKeysAsyncPager: + Response to request to list keys in a + project. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + + request = recaptchaenterprise.ListKeysRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.list_keys, + default_timeout=600.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListKeysAsyncPager( + method=rpc, request=request, response=response, metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_key( + self, + request: recaptchaenterprise.GetKeyRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> recaptchaenterprise.Key: + r"""Returns the specified key. + + Args: + request (:class:`google.cloud.recaptchaenterprise_v1.types.GetKeyRequest`): + The request object. The get key request message. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.recaptchaenterprise_v1.types.Key: + A key used to identify and configure + applications (web and/or mobile) that + use reCAPTCHA Enterprise. + + """ + # Create or coerce a protobuf request object. + + request = recaptchaenterprise.GetKeyRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.get_key, + default_timeout=600.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def update_key( + self, + request: recaptchaenterprise.UpdateKeyRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> recaptchaenterprise.Key: + r"""Updates the specified key. + + Args: + request (:class:`google.cloud.recaptchaenterprise_v1.types.UpdateKeyRequest`): + The request object. The update key request message. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.recaptchaenterprise_v1.types.Key: + A key used to identify and configure + applications (web and/or mobile) that + use reCAPTCHA Enterprise. + + """ + # Create or coerce a protobuf request object. + + request = recaptchaenterprise.UpdateKeyRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.update_key, + default_timeout=600.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("key.name", request.key.name),)), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def delete_key( + self, + request: recaptchaenterprise.DeleteKeyRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes the specified key. + + Args: + request (:class:`google.cloud.recaptchaenterprise_v1.types.DeleteKeyRequest`): + The request object. The delete key request message. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + + request = recaptchaenterprise.DeleteKeyRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.delete_key, + default_timeout=600.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Send the request. + await rpc( + request, retry=retry, timeout=timeout, metadata=metadata, + ) + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-recaptcha-enterprise", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ("RecaptchaEnterpriseServiceAsyncClient",) diff --git a/google/cloud/recaptchaenterprise_v1/services/recaptcha_enterprise_service/client.py b/google/cloud/recaptchaenterprise_v1/services/recaptcha_enterprise_service/client.py index efc07b8..1cd52c6 100644 --- a/google/cloud/recaptchaenterprise_v1/services/recaptcha_enterprise_service/client.py +++ b/google/cloud/recaptchaenterprise_v1/services/recaptcha_enterprise_service/client.py @@ -16,15 +16,20 @@ # 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 from google.cloud.recaptchaenterprise_v1.services.recaptcha_enterprise_service import ( @@ -33,8 +38,9 @@ from google.cloud.recaptchaenterprise_v1.types import recaptchaenterprise from google.protobuf import timestamp_pb2 as timestamp # type: ignore -from .transports.base import RecaptchaEnterpriseServiceTransport +from .transports.base import RecaptchaEnterpriseServiceTransport, DEFAULT_CLIENT_INFO from .transports.grpc import RecaptchaEnterpriseServiceGrpcTransport +from .transports.grpc_asyncio import RecaptchaEnterpriseServiceGrpcAsyncIOTransport class RecaptchaEnterpriseServiceClientMeta(type): @@ -49,9 +55,10 @@ class RecaptchaEnterpriseServiceClientMeta(type): OrderedDict() ) # type: Dict[str, Type[RecaptchaEnterpriseServiceTransport]] _transport_registry["grpc"] = RecaptchaEnterpriseServiceGrpcTransport + _transport_registry["grpc_asyncio"] = RecaptchaEnterpriseServiceGrpcAsyncIOTransport def get_transport_class( - cls, label: str = None + cls, label: str = None, ) -> Type[RecaptchaEnterpriseServiceTransport]: """Return an appropriate transport class. @@ -108,6 +115,22 @@ def _get_default_mtls_endpoint(api_endpoint): DEFAULT_ENDPOINT ) + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + RecaptchaEnterpriseServiceClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_info(info) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -120,7 +143,7 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): kwargs: Additional arguments to pass to the constructor. Returns: - {@api.name}: The constructed client. + RecaptchaEnterpriseServiceClient: The constructed client. """ credentials = service_account.Credentials.from_service_account_file(filename) kwargs["credentials"] = credentials @@ -128,11 +151,20 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): from_service_account_json = from_service_account_file + @property + def transport(self) -> RecaptchaEnterpriseServiceTransport: + """Return the transport used by the client instance. + + Returns: + RecaptchaEnterpriseServiceTransport: The transport used by the client instance. + """ + return self._transport + @staticmethod - def assessment_path(project: str, assessment: str) -> str: + def assessment_path(project: str, assessment: str,) -> str: """Return a fully-qualified assessment string.""" return "projects/{project}/assessments/{assessment}".format( - project=project, assessment=assessment + project=project, assessment=assessment, ) @staticmethod @@ -144,9 +176,9 @@ def parse_assessment_path(path: str) -> Dict[str, str]: return m.groupdict() if m else {} @staticmethod - def key_path(project: str, key: str) -> str: + def key_path(project: str, key: str,) -> str: """Return a fully-qualified key string.""" - return "projects/{project}/keys/{key}".format(project=project, key=key) + return "projects/{project}/keys/{key}".format(project=project, key=key,) @staticmethod def parse_key_path(path: str) -> Dict[str, str]: @@ -154,12 +186,72 @@ def parse_key_path(path: str) -> Dict[str, str]: m = re.match(r"^projects/(?P.+?)/keys/(?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, RecaptchaEnterpriseServiceTransport] = None, - client_options: ClientOptions = None, + credentials: Optional[credentials.Credentials] = None, + transport: Union[str, RecaptchaEnterpriseServiceTransport, None] = None, + client_options: Optional[client_options_lib.ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: """Instantiate the recaptcha enterprise service client. @@ -169,69 +261,105 @@ def __init__( credentials identify the application to the service; if none are specified, the client will attempt to ascertain the credentials from the environment. - transport (Union[str, ~.RecaptchaEnterpriseServiceTransport]): The + transport (Union[str, RecaptchaEnterpriseServiceTransport]): The transport to use. If set to None, a transport is chosen automatically. - client_options (ClientOptions): Custom options for the client. + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. It won't take effect if a ``transport`` instance is provided. (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. - (2) If ``transport`` argument is None, ``client_options`` can be - used to create a mutual TLS transport. If ``client_cert_source`` - is provided, mutual TLS transport will be created with the given - ``api_endpoint`` or the default mTLS endpoint, and the client - SSL credentials obtained from ``client_cert_source``. + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport creation failed for any reason. """ if isinstance(client_options, dict): - client_options = ClientOptions.from_dict(client_options) + client_options = client_options_lib.from_dict(client_options) + if client_options is None: + client_options = 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 + + 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": + api_endpoint = self.DEFAULT_ENDPOINT + elif use_mtls_env == "always": + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + elif use_mtls_env == "auto": + api_endpoint = ( + self.DEFAULT_MTLS_ENDPOINT if is_mtls else self.DEFAULT_ENDPOINT + ) + else: + raise MutualTLSChannelError( + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted values: never, auto, always" + ) # Save or instantiate the transport. # Ordinarily, we provide the transport, but allowing a custom transport # instance provides an extensibility point for unusual situations. if isinstance(transport, RecaptchaEnterpriseServiceTransport): # transport is a RecaptchaEnterpriseServiceTransport instance. - if credentials: + if credentials or client_options.credentials_file: raise ValueError( "When providing a transport instance, " "provide its credentials directly." ) + if client_options.scopes: + raise ValueError( + "When providing a transport instance, " + "provide its scopes directly." + ) self._transport = transport - elif client_options is None or ( - client_options.api_endpoint is None - and client_options.client_cert_source is None - ): - # Don't trigger mTLS if we get an empty ClientOptions. + else: Transport = type(self).get_transport_class(transport) self._transport = Transport( - credentials=credentials, host=self.DEFAULT_ENDPOINT - ) - else: - # We have a non-empty ClientOptions. If client_cert_source is - # provided, trigger mTLS with user provided endpoint or the default - # mTLS endpoint. - if client_options.client_cert_source: - api_mtls_endpoint = ( - client_options.api_endpoint - if client_options.api_endpoint - else self.DEFAULT_MTLS_ENDPOINT - ) - else: - api_mtls_endpoint = None - - api_endpoint = ( - client_options.api_endpoint - if client_options.api_endpoint - else self.DEFAULT_ENDPOINT - ) - - self._transport = RecaptchaEnterpriseServiceGrpcTransport( credentials=credentials, + credentials_file=client_options.credentials_file, host=api_endpoint, - api_mtls_endpoint=api_mtls_endpoint, - client_cert_source=client_options.client_cert_source, + scopes=client_options.scopes, + ssl_channel_credentials=ssl_credentials, + quota_project_id=client_options.quota_project_id, + client_info=client_info, ) def create_assessment( @@ -248,17 +376,18 @@ def create_assessment( legitimate. Args: - request (:class:`~.recaptchaenterprise.CreateAssessmentRequest`): + request (google.cloud.recaptchaenterprise_v1.types.CreateAssessmentRequest): The request object. The create assessment request message. - parent (:class:`str`): + parent (str): Required. The name of the project in which the assessment will be created, in the format "projects/{project}". + This corresponds to the ``parent`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - assessment (:class:`~.recaptchaenterprise.Assessment`): + assessment (google.cloud.recaptchaenterprise_v1.types.Assessment): Required. The assessment details. This corresponds to the ``assessment`` field on the ``request`` instance; if ``request`` is provided, this @@ -271,38 +400,46 @@ def create_assessment( sent along with the request as metadata. Returns: - ~.recaptchaenterprise.Assessment: + google.cloud.recaptchaenterprise_v1.types.Assessment: A recaptcha assessment resource. """ # Create or coerce a protobuf request object. # Sanity check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - if request is not None and any([parent, assessment]): + has_flattened_params = any([parent, assessment]) + if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " "the individual field arguments should be set." ) - request = recaptchaenterprise.CreateAssessmentRequest(request) + # Minor optimization to avoid making a copy if the user passes + # in a recaptchaenterprise.CreateAssessmentRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, recaptchaenterprise.CreateAssessmentRequest): + request = recaptchaenterprise.CreateAssessmentRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. + # If we have keyword arguments corresponding to fields on the + # request, apply these. - if parent is not None: - request.parent = parent - if assessment is not None: - request.assessment = assessment + if parent is not None: + request.parent = parent + if assessment is not None: + request.assessment = assessment # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.create_assessment, - default_timeout=None, - client_info=_client_info, + rpc = self._transport._wrapped_methods[self._transport.create_assessment] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) # Send the request. - response = rpc(request, retry=retry, timeout=timeout, metadata=metadata) + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) # Done; return the response. return response @@ -322,19 +459,21 @@ def annotate_assessment( to be authentic or fradulent. Args: - request (:class:`~.recaptchaenterprise.AnnotateAssessmentRequest`): + request (google.cloud.recaptchaenterprise_v1.types.AnnotateAssessmentRequest): The request object. The request message to annotate an Assessment. - name (:class:`str`): + name (str): Required. The resource name of the Assessment, in the format "projects/{project}/assessments/{assessment}". + This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - annotation (:class:`~.recaptchaenterprise.AnnotateAssessmentRequest.Annotation`): + annotation (google.cloud.recaptchaenterprise_v1.types.AnnotateAssessmentRequest.Annotation): Required. The annotation that will be assigned to the Event. + This corresponds to the ``annotation`` field on the ``request`` instance; if ``request`` is provided, this should not be set. @@ -346,7 +485,7 @@ def annotate_assessment( sent along with the request as metadata. Returns: - ~.recaptchaenterprise.AnnotateAssessmentResponse: + google.cloud.recaptchaenterprise_v1.types.AnnotateAssessmentResponse: Empty response for AnnotateAssessment. @@ -354,32 +493,40 @@ def annotate_assessment( # 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, annotation]): + has_flattened_params = any([name, annotation]) + if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " "the individual field arguments should be set." ) - request = recaptchaenterprise.AnnotateAssessmentRequest(request) + # Minor optimization to avoid making a copy if the user passes + # in a recaptchaenterprise.AnnotateAssessmentRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, recaptchaenterprise.AnnotateAssessmentRequest): + request = recaptchaenterprise.AnnotateAssessmentRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. + # If we have keyword arguments corresponding to fields on the + # request, apply these. - if name is not None: - request.name = name - if annotation is not None: - request.annotation = annotation + if name is not None: + request.name = name + if annotation is not None: + request.annotation = annotation # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.annotate_assessment, - default_timeout=None, - client_info=_client_info, + rpc = self._transport._wrapped_methods[self._transport.annotate_assessment] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Send the request. - response = rpc(request, retry=retry, timeout=timeout, metadata=metadata) + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) # Done; return the response. return response @@ -395,7 +542,7 @@ def create_key( r"""Creates a new reCAPTCHA Enterprise key. Args: - request (:class:`~.recaptchaenterprise.CreateKeyRequest`): + request (google.cloud.recaptchaenterprise_v1.types.CreateKeyRequest): The request object. The create key request message. retry (google.api_core.retry.Retry): Designation of what errors, if any, @@ -405,7 +552,7 @@ def create_key( sent along with the request as metadata. Returns: - ~.recaptchaenterprise.Key: + google.cloud.recaptchaenterprise_v1.types.Key: A key used to identify and configure applications (web and/or mobile) that use reCAPTCHA Enterprise. @@ -413,16 +560,25 @@ def create_key( """ # Create or coerce a protobuf request object. - request = recaptchaenterprise.CreateKeyRequest(request) + # Minor optimization to avoid making a copy if the user passes + # in a recaptchaenterprise.CreateKeyRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, recaptchaenterprise.CreateKeyRequest): + request = recaptchaenterprise.CreateKeyRequest(request) # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.create_key, default_timeout=None, client_info=_client_info + rpc = self._transport._wrapped_methods[self._transport.create_key] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) # Send the request. - response = rpc(request, retry=retry, timeout=timeout, metadata=metadata) + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) # Done; return the response. return response @@ -439,7 +595,7 @@ def list_keys( project. Args: - request (:class:`~.recaptchaenterprise.ListKeysRequest`): + request (google.cloud.recaptchaenterprise_v1.types.ListKeysRequest): The request object. The list keys request message. retry (google.api_core.retry.Retry): Designation of what errors, if any, @@ -449,7 +605,7 @@ def list_keys( sent along with the request as metadata. Returns: - ~.pagers.ListKeysPager: + google.cloud.recaptchaenterprise_v1.services.recaptcha_enterprise_service.pagers.ListKeysPager: Response to request to list keys in a project. Iterating over this object will yield @@ -459,13 +615,16 @@ def list_keys( """ # Create or coerce a protobuf request object. - request = recaptchaenterprise.ListKeysRequest(request) + # Minor optimization to avoid making a copy if the user passes + # in a recaptchaenterprise.ListKeysRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, recaptchaenterprise.ListKeysRequest): + request = recaptchaenterprise.ListKeysRequest(request) # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.list_keys, default_timeout=None, client_info=_client_info - ) + rpc = self._transport._wrapped_methods[self._transport.list_keys] # Certain fields should be provided within the metadata header; # add these here. @@ -474,11 +633,13 @@ def list_keys( ) # Send the request. - response = rpc(request, retry=retry, timeout=timeout, metadata=metadata) + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) # This method is paged; wrap the response in a pager, which provides # an `__iter__` convenience method. - response = pagers.ListKeysPager(method=rpc, request=request, response=response) + response = pagers.ListKeysPager( + method=rpc, request=request, response=response, metadata=metadata, + ) # Done; return the response. return response @@ -494,7 +655,7 @@ def get_key( r"""Returns the specified key. Args: - request (:class:`~.recaptchaenterprise.GetKeyRequest`): + request (google.cloud.recaptchaenterprise_v1.types.GetKeyRequest): The request object. The get key request message. retry (google.api_core.retry.Retry): Designation of what errors, if any, @@ -504,7 +665,7 @@ def get_key( sent along with the request as metadata. Returns: - ~.recaptchaenterprise.Key: + google.cloud.recaptchaenterprise_v1.types.Key: A key used to identify and configure applications (web and/or mobile) that use reCAPTCHA Enterprise. @@ -512,13 +673,16 @@ def get_key( """ # Create or coerce a protobuf request object. - request = recaptchaenterprise.GetKeyRequest(request) + # Minor optimization to avoid making a copy if the user passes + # in a recaptchaenterprise.GetKeyRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, recaptchaenterprise.GetKeyRequest): + request = recaptchaenterprise.GetKeyRequest(request) # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.get_key, default_timeout=None, client_info=_client_info - ) + rpc = self._transport._wrapped_methods[self._transport.get_key] # Certain fields should be provided within the metadata header; # add these here. @@ -527,7 +691,7 @@ def get_key( ) # Send the request. - response = rpc(request, retry=retry, timeout=timeout, metadata=metadata) + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) # Done; return the response. return response @@ -543,7 +707,7 @@ def update_key( r"""Updates the specified key. Args: - request (:class:`~.recaptchaenterprise.UpdateKeyRequest`): + request (google.cloud.recaptchaenterprise_v1.types.UpdateKeyRequest): The request object. The update key request message. retry (google.api_core.retry.Retry): Designation of what errors, if any, @@ -553,7 +717,7 @@ def update_key( sent along with the request as metadata. Returns: - ~.recaptchaenterprise.Key: + google.cloud.recaptchaenterprise_v1.types.Key: A key used to identify and configure applications (web and/or mobile) that use reCAPTCHA Enterprise. @@ -561,16 +725,25 @@ def update_key( """ # Create or coerce a protobuf request object. - request = recaptchaenterprise.UpdateKeyRequest(request) + # Minor optimization to avoid making a copy if the user passes + # in a recaptchaenterprise.UpdateKeyRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, recaptchaenterprise.UpdateKeyRequest): + request = recaptchaenterprise.UpdateKeyRequest(request) # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.update_key, default_timeout=None, client_info=_client_info + rpc = self._transport._wrapped_methods[self._transport.update_key] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("key.name", request.key.name),)), ) # Send the request. - response = rpc(request, retry=retry, timeout=timeout, metadata=metadata) + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) # Done; return the response. return response @@ -586,7 +759,7 @@ def delete_key( r"""Deletes the specified key. Args: - request (:class:`~.recaptchaenterprise.DeleteKeyRequest`): + request (google.cloud.recaptchaenterprise_v1.types.DeleteKeyRequest): The request object. The delete key request message. retry (google.api_core.retry.Retry): Designation of what errors, if any, @@ -597,26 +770,37 @@ def delete_key( """ # Create or coerce a protobuf request object. - request = recaptchaenterprise.DeleteKeyRequest(request) + # Minor optimization to avoid making a copy if the user passes + # in a recaptchaenterprise.DeleteKeyRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, recaptchaenterprise.DeleteKeyRequest): + request = recaptchaenterprise.DeleteKeyRequest(request) # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.delete_key, default_timeout=None, client_info=_client_info + rpc = self._transport._wrapped_methods[self._transport.delete_key] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Send the request. - rpc(request, retry=retry, timeout=timeout, metadata=metadata) + rpc( + request, retry=retry, timeout=timeout, metadata=metadata, + ) try: - _client_info = gapic_v1.client_info.ClientInfo( + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=pkg_resources.get_distribution( - "google-cloud-recaptcha-enterprise" - ).version + "google-cloud-recaptcha-enterprise", + ).version, ) except pkg_resources.DistributionNotFound: - _client_info = gapic_v1.client_info.ClientInfo() + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() __all__ = ("RecaptchaEnterpriseServiceClient",) diff --git a/google/cloud/recaptchaenterprise_v1/services/recaptcha_enterprise_service/pagers.py b/google/cloud/recaptchaenterprise_v1/services/recaptcha_enterprise_service/pagers.py index 1dc640b..107e61b 100644 --- a/google/cloud/recaptchaenterprise_v1/services/recaptcha_enterprise_service/pagers.py +++ b/google/cloud/recaptchaenterprise_v1/services/recaptcha_enterprise_service/pagers.py @@ -15,7 +15,7 @@ # limitations under the License. # -from typing import Any, Callable, Iterable +from typing import Any, AsyncIterable, Awaitable, Callable, Iterable, Sequence, Tuple from google.cloud.recaptchaenterprise_v1.types import recaptchaenterprise @@ -24,7 +24,7 @@ class ListKeysPager: """A pager for iterating through ``list_keys`` requests. This class thinly wraps an initial - :class:`~.recaptchaenterprise.ListKeysResponse` object, and + :class:`google.cloud.recaptchaenterprise_v1.types.ListKeysResponse` object, and provides an ``__iter__`` method to iterate through its ``keys`` field. @@ -33,32 +33,35 @@ class ListKeysPager: through the ``keys`` field on the corresponding responses. - All the usual :class:`~.recaptchaenterprise.ListKeysResponse` + All the usual :class:`google.cloud.recaptchaenterprise_v1.types.ListKeysResponse` attributes are available on the pager. If multiple requests are made, only the most recent response is retained, and thus used for attribute lookup. """ def __init__( self, - method: Callable[ - [recaptchaenterprise.ListKeysRequest], recaptchaenterprise.ListKeysResponse - ], + method: Callable[..., recaptchaenterprise.ListKeysResponse], request: recaptchaenterprise.ListKeysRequest, response: recaptchaenterprise.ListKeysResponse, + *, + metadata: Sequence[Tuple[str, str]] = () ): """Instantiate the pager. Args: method (Callable): The method that was originally called, and which instantiated this pager. - request (:class:`~.recaptchaenterprise.ListKeysRequest`): + request (google.cloud.recaptchaenterprise_v1.types.ListKeysRequest): The initial request object. - response (:class:`~.recaptchaenterprise.ListKeysResponse`): + response (google.cloud.recaptchaenterprise_v1.types.ListKeysResponse): The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. """ self._method = method self._request = recaptchaenterprise.ListKeysRequest(request) self._response = response + self._metadata = metadata def __getattr__(self, name: str) -> Any: return getattr(self._response, name) @@ -68,7 +71,7 @@ def pages(self) -> Iterable[recaptchaenterprise.ListKeysResponse]: yield self._response while self._response.next_page_token: self._request.page_token = self._response.next_page_token - self._response = self._method(self._request) + self._response = self._method(self._request, metadata=self._metadata) yield self._response def __iter__(self) -> Iterable[recaptchaenterprise.Key]: @@ -77,3 +80,69 @@ def __iter__(self) -> Iterable[recaptchaenterprise.Key]: def __repr__(self) -> str: return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListKeysAsyncPager: + """A pager for iterating through ``list_keys`` requests. + + This class thinly wraps an initial + :class:`google.cloud.recaptchaenterprise_v1.types.ListKeysResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``keys`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListKeys`` requests and continue to iterate + through the ``keys`` field on the + corresponding responses. + + All the usual :class:`google.cloud.recaptchaenterprise_v1.types.ListKeysResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., Awaitable[recaptchaenterprise.ListKeysResponse]], + request: recaptchaenterprise.ListKeysRequest, + response: recaptchaenterprise.ListKeysResponse, + *, + metadata: Sequence[Tuple[str, str]] = () + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.recaptchaenterprise_v1.types.ListKeysRequest): + The initial request object. + response (google.cloud.recaptchaenterprise_v1.types.ListKeysResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = recaptchaenterprise.ListKeysRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterable[recaptchaenterprise.ListKeysResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method(self._request, metadata=self._metadata) + yield self._response + + def __aiter__(self) -> AsyncIterable[recaptchaenterprise.Key]: + async def async_generator(): + async for page in self.pages: + for response in page.keys: + yield response + + return async_generator() + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) diff --git a/google/cloud/recaptchaenterprise_v1/services/recaptcha_enterprise_service/transports/__init__.py b/google/cloud/recaptchaenterprise_v1/services/recaptcha_enterprise_service/transports/__init__.py index 6dfddaf..20c02b3 100644 --- a/google/cloud/recaptchaenterprise_v1/services/recaptcha_enterprise_service/transports/__init__.py +++ b/google/cloud/recaptchaenterprise_v1/services/recaptcha_enterprise_service/transports/__init__.py @@ -20,6 +20,7 @@ from .base import RecaptchaEnterpriseServiceTransport from .grpc import RecaptchaEnterpriseServiceGrpcTransport +from .grpc_asyncio import RecaptchaEnterpriseServiceGrpcAsyncIOTransport # Compile a registry of transports. @@ -27,9 +28,10 @@ OrderedDict() ) # type: Dict[str, Type[RecaptchaEnterpriseServiceTransport]] _transport_registry["grpc"] = RecaptchaEnterpriseServiceGrpcTransport - +_transport_registry["grpc_asyncio"] = RecaptchaEnterpriseServiceGrpcAsyncIOTransport __all__ = ( "RecaptchaEnterpriseServiceTransport", "RecaptchaEnterpriseServiceGrpcTransport", + "RecaptchaEnterpriseServiceGrpcAsyncIOTransport", ) diff --git a/google/cloud/recaptchaenterprise_v1/services/recaptcha_enterprise_service/transports/base.py b/google/cloud/recaptchaenterprise_v1/services/recaptcha_enterprise_service/transports/base.py index 1b03418..c4575d2 100644 --- a/google/cloud/recaptchaenterprise_v1/services/recaptcha_enterprise_service/transports/base.py +++ b/google/cloud/recaptchaenterprise_v1/services/recaptcha_enterprise_service/transports/base.py @@ -17,15 +17,29 @@ import abc import typing +import pkg_resources -from google import auth +from google import auth # type: ignore +from google.api_core import exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore from google.auth import credentials # type: ignore from google.cloud.recaptchaenterprise_v1.types import recaptchaenterprise from google.protobuf import empty_pb2 as empty # type: ignore -class RecaptchaEnterpriseServiceTransport(metaclass=abc.ABCMeta): +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-recaptcha-enterprise", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +class RecaptchaEnterpriseServiceTransport(abc.ABC): """Abstract transport class for RecaptchaEnterpriseService.""" AUTH_SCOPES = ("https://www.googleapis.com/auth/cloud-platform",) @@ -35,6 +49,11 @@ def __init__( *, host: str = "recaptchaenterprise.googleapis.com", credentials: credentials.Credentials = None, + credentials_file: typing.Optional[str] = None, + scopes: typing.Optional[typing.Sequence[str]] = AUTH_SCOPES, + quota_project_id: typing.Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + **kwargs, ) -> None: """Instantiate the transport. @@ -45,6 +64,17 @@ def __init__( credentials identify the application to the service; if none are specified, the client will attempt to ascertain the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scope (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. """ # Save the hostname. Default to port 443 (HTTPS) if none is specified. if ":" not in host: @@ -53,64 +83,132 @@ def __init__( # If no credentials are provided, then determine the appropriate # defaults. - if credentials is None: - credentials, _ = auth.default(scopes=self.AUTH_SCOPES) + if credentials and credentials_file: + raise exceptions.DuplicateCredentialArgs( + "'credentials_file' and 'credentials' are mutually exclusive" + ) + + if credentials_file is not None: + credentials, _ = auth.load_credentials_from_file( + credentials_file, scopes=scopes, quota_project_id=quota_project_id + ) + + elif credentials is None: + credentials, _ = auth.default( + scopes=scopes, quota_project_id=quota_project_id + ) # Save the credentials. self._credentials = credentials + # Lifted into its own function so it can be stubbed out during tests. + self._prep_wrapped_messages(client_info) + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.create_assessment: gapic_v1.method.wrap_method( + self.create_assessment, default_timeout=600.0, client_info=client_info, + ), + self.annotate_assessment: gapic_v1.method.wrap_method( + self.annotate_assessment, + default_timeout=600.0, + client_info=client_info, + ), + self.create_key: gapic_v1.method.wrap_method( + self.create_key, default_timeout=600.0, client_info=client_info, + ), + self.list_keys: gapic_v1.method.wrap_method( + self.list_keys, default_timeout=600.0, client_info=client_info, + ), + self.get_key: gapic_v1.method.wrap_method( + self.get_key, default_timeout=600.0, client_info=client_info, + ), + self.update_key: gapic_v1.method.wrap_method( + self.update_key, default_timeout=600.0, client_info=client_info, + ), + self.delete_key: gapic_v1.method.wrap_method( + self.delete_key, default_timeout=600.0, client_info=client_info, + ), + } + @property def create_assessment( self, ) -> typing.Callable[ - [recaptchaenterprise.CreateAssessmentRequest], recaptchaenterprise.Assessment + [recaptchaenterprise.CreateAssessmentRequest], + typing.Union[ + recaptchaenterprise.Assessment, + typing.Awaitable[recaptchaenterprise.Assessment], + ], ]: - raise NotImplementedError + raise NotImplementedError() @property def annotate_assessment( self, ) -> typing.Callable[ [recaptchaenterprise.AnnotateAssessmentRequest], - recaptchaenterprise.AnnotateAssessmentResponse, + typing.Union[ + recaptchaenterprise.AnnotateAssessmentResponse, + typing.Awaitable[recaptchaenterprise.AnnotateAssessmentResponse], + ], ]: - raise NotImplementedError + raise NotImplementedError() @property def create_key( self, ) -> typing.Callable[ - [recaptchaenterprise.CreateKeyRequest], recaptchaenterprise.Key + [recaptchaenterprise.CreateKeyRequest], + typing.Union[ + recaptchaenterprise.Key, typing.Awaitable[recaptchaenterprise.Key] + ], ]: - raise NotImplementedError + raise NotImplementedError() @property def list_keys( self, ) -> typing.Callable[ - [recaptchaenterprise.ListKeysRequest], recaptchaenterprise.ListKeysResponse + [recaptchaenterprise.ListKeysRequest], + typing.Union[ + recaptchaenterprise.ListKeysResponse, + typing.Awaitable[recaptchaenterprise.ListKeysResponse], + ], ]: - raise NotImplementedError + raise NotImplementedError() @property def get_key( self, - ) -> typing.Callable[[recaptchaenterprise.GetKeyRequest], recaptchaenterprise.Key]: - raise NotImplementedError + ) -> typing.Callable[ + [recaptchaenterprise.GetKeyRequest], + typing.Union[ + recaptchaenterprise.Key, typing.Awaitable[recaptchaenterprise.Key] + ], + ]: + raise NotImplementedError() @property def update_key( self, ) -> typing.Callable[ - [recaptchaenterprise.UpdateKeyRequest], recaptchaenterprise.Key + [recaptchaenterprise.UpdateKeyRequest], + typing.Union[ + recaptchaenterprise.Key, typing.Awaitable[recaptchaenterprise.Key] + ], ]: - raise NotImplementedError + raise NotImplementedError() @property def delete_key( self, - ) -> typing.Callable[[recaptchaenterprise.DeleteKeyRequest], empty.Empty]: - raise NotImplementedError + ) -> typing.Callable[ + [recaptchaenterprise.DeleteKeyRequest], + typing.Union[empty.Empty, typing.Awaitable[empty.Empty]], + ]: + raise NotImplementedError() __all__ = ("RecaptchaEnterpriseServiceTransport",) diff --git a/google/cloud/recaptchaenterprise_v1/services/recaptcha_enterprise_service/transports/grpc.py b/google/cloud/recaptchaenterprise_v1/services/recaptcha_enterprise_service/transports/grpc.py index 96f2227..c9e40f8 100644 --- a/google/cloud/recaptchaenterprise_v1/services/recaptcha_enterprise_service/transports/grpc.py +++ b/google/cloud/recaptchaenterprise_v1/services/recaptcha_enterprise_service/transports/grpc.py @@ -15,19 +15,21 @@ # limitations under the License. # -from typing import Callable, Dict, Tuple +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple from google.api_core import grpc_helpers # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google import auth # type: ignore from google.auth import credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore - import grpc # type: ignore from google.cloud.recaptchaenterprise_v1.types import recaptchaenterprise from google.protobuf import empty_pb2 as empty # type: ignore -from .base import RecaptchaEnterpriseServiceTransport +from .base import RecaptchaEnterpriseServiceTransport, DEFAULT_CLIENT_INFO class RecaptchaEnterpriseServiceGrpcTransport(RecaptchaEnterpriseServiceTransport): @@ -43,14 +45,21 @@ class RecaptchaEnterpriseServiceGrpcTransport(RecaptchaEnterpriseServiceTranspor top of HTTP/2); the ``grpcio`` package must be installed. """ + _stubs: Dict[str, Callable] + def __init__( self, *, host: str = "recaptchaenterprise.googleapis.com", credentials: credentials.Credentials = None, + credentials_file: str = None, + scopes: Sequence[str] = None, channel: grpc.Channel = None, api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None + 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: """Instantiate the transport. @@ -62,21 +71,39 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. channel (Optional[grpc.Channel]): A ``Channel`` instance through which to make calls. - api_mtls_endpoint (Optional[str]): The mutual TLS endpoint. If - provided, it overrides the ``host`` argument and tries to create + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create a mutual TLS channel with client SSL credentials from ``client_cert_source`` or applicatin default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): A - callback to provide client SSL certificate bytes and private key - bytes, both in PEM format. It is ignored if ``api_mtls_endpoint`` - is None. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for grpc channel. It is ignored if ``channel`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. """ + self._ssl_channel_credentials = ssl_channel_credentials + if channel: # Sanity check: Ensure that channel and credentials are not both # provided. @@ -84,13 +111,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: @@ -102,56 +140,102 @@ def __init__( ssl_credentials = SslCredentials().ssl_credentials # create a new channel. The provided one is ignored. - self._grpc_channel = grpc_helpers.create_channel( + self._grpc_channel = type(self).create_channel( host, credentials=credentials, + credentials_file=credentials_file, ssl_credentials=ssl_credentials, - scopes=self.AUTH_SCOPES, + scopes=scopes or self.AUTH_SCOPES, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + self._ssl_channel_credentials = ssl_credentials + else: + host = host if ":" in host else host + ":443" + + if 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, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], ) - # Run the base constructor. - super().__init__(host=host, credentials=credentials) self._stubs = {} # type: Dict[str, Callable] + # Run the base constructor. + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes or self.AUTH_SCOPES, + quota_project_id=quota_project_id, + client_info=client_info, + ) + @classmethod def create_channel( cls, host: str = "recaptchaenterprise.googleapis.com", credentials: credentials.Credentials = None, - **kwargs + credentials_file: str = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs, ) -> grpc.Channel: """Create and return a gRPC channel object. Args: - address (Optionsl[str]): The host for the channel to use. + address (Optional[str]): The host for the channel to use. credentials (Optional[~.Credentials]): The authorization credentials to attach to requests. These credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. kwargs (Optional[dict]): Keyword arguments, which are passed to the channel creation. Returns: grpc.Channel: A gRPC channel object. + + Raises: + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. """ + scopes = scopes or cls.AUTH_SCOPES return grpc_helpers.create_channel( - host, credentials=credentials, scopes=cls.AUTH_SCOPES, **kwargs + host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + **kwargs, ) @property def grpc_channel(self) -> grpc.Channel: - """Create the channel designed to connect to this service. - - This property caches on the instance; repeated calls return - the same channel. + """Return the channel designed to connect to this service. """ - # Sanity check: Only create a new channel if we do not already - # have one. - if not hasattr(self, "_grpc_channel"): - self._grpc_channel = self.create_channel( - self._host, credentials=self._credentials - ) - - # Return the channel from cache. return self._grpc_channel @property diff --git a/google/cloud/recaptchaenterprise_v1/services/recaptcha_enterprise_service/transports/grpc_asyncio.py b/google/cloud/recaptchaenterprise_v1/services/recaptcha_enterprise_service/transports/grpc_asyncio.py new file mode 100644 index 0000000..8cc602e --- /dev/null +++ b/google/cloud/recaptchaenterprise_v1/services/recaptcha_enterprise_service/transports/grpc_asyncio.py @@ -0,0 +1,449 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple + +from google.api_core import gapic_v1 # type: ignore +from google.api_core import grpc_helpers_async # type: ignore +from google import auth # type: ignore +from google.auth import credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.recaptchaenterprise_v1.types import recaptchaenterprise +from google.protobuf import empty_pb2 as empty # type: ignore + +from .base import RecaptchaEnterpriseServiceTransport, DEFAULT_CLIENT_INFO +from .grpc import RecaptchaEnterpriseServiceGrpcTransport + + +class RecaptchaEnterpriseServiceGrpcAsyncIOTransport( + RecaptchaEnterpriseServiceTransport +): + """gRPC AsyncIO backend transport for RecaptchaEnterpriseService. + + Service to determine the likelihood an event is legitimate. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + + _grpc_channel: aio.Channel + _stubs: Dict[str, Callable] = {} + + @classmethod + def create_channel( + cls, + host: str = "recaptchaenterprise.googleapis.com", + credentials: credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs, + ) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + address (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + scopes = scopes or cls.AUTH_SCOPES + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + **kwargs, + ) + + def __init__( + self, + *, + host: str = "recaptchaenterprise.googleapis.com", + credentials: credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: aio.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + quota_project_id=None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[aio.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or applicatin default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for grpc channel. It is ignored if ``channel`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._ssl_channel_credentials = ssl_channel_credentials + + if channel: + # Sanity check: Ensure that channel and credentials are not both + # provided. + credentials = False + + # 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: + cert, key = client_cert_source() + ssl_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + ssl_credentials = SslCredentials().ssl_credentials + + # create a new channel. The provided one is ignored. + self._grpc_channel = type(self).create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + ssl_credentials=ssl_credentials, + scopes=scopes or self.AUTH_SCOPES, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + self._ssl_channel_credentials = ssl_credentials + else: + host = host if ":" in host else host + ":443" + + if 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, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Run the base constructor. + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes or self.AUTH_SCOPES, + quota_project_id=quota_project_id, + client_info=client_info, + ) + + self._stubs = {} + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def create_assessment( + self, + ) -> Callable[ + [recaptchaenterprise.CreateAssessmentRequest], + Awaitable[recaptchaenterprise.Assessment], + ]: + r"""Return a callable for the create assessment method over gRPC. + + Creates an Assessment of the likelihood an event is + legitimate. + + Returns: + Callable[[~.CreateAssessmentRequest], + Awaitable[~.Assessment]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "create_assessment" not in self._stubs: + self._stubs["create_assessment"] = self.grpc_channel.unary_unary( + "/google.cloud.recaptchaenterprise.v1.RecaptchaEnterpriseService/CreateAssessment", + request_serializer=recaptchaenterprise.CreateAssessmentRequest.serialize, + response_deserializer=recaptchaenterprise.Assessment.deserialize, + ) + return self._stubs["create_assessment"] + + @property + def annotate_assessment( + self, + ) -> Callable[ + [recaptchaenterprise.AnnotateAssessmentRequest], + Awaitable[recaptchaenterprise.AnnotateAssessmentResponse], + ]: + r"""Return a callable for the annotate assessment method over gRPC. + + Annotates a previously created Assessment to provide + additional information on whether the event turned out + to be authentic or fradulent. + + Returns: + Callable[[~.AnnotateAssessmentRequest], + Awaitable[~.AnnotateAssessmentResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "annotate_assessment" not in self._stubs: + self._stubs["annotate_assessment"] = self.grpc_channel.unary_unary( + "/google.cloud.recaptchaenterprise.v1.RecaptchaEnterpriseService/AnnotateAssessment", + request_serializer=recaptchaenterprise.AnnotateAssessmentRequest.serialize, + response_deserializer=recaptchaenterprise.AnnotateAssessmentResponse.deserialize, + ) + return self._stubs["annotate_assessment"] + + @property + def create_key( + self, + ) -> Callable[ + [recaptchaenterprise.CreateKeyRequest], Awaitable[recaptchaenterprise.Key] + ]: + r"""Return a callable for the create key method over gRPC. + + Creates a new reCAPTCHA Enterprise key. + + Returns: + Callable[[~.CreateKeyRequest], + Awaitable[~.Key]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "create_key" not in self._stubs: + self._stubs["create_key"] = self.grpc_channel.unary_unary( + "/google.cloud.recaptchaenterprise.v1.RecaptchaEnterpriseService/CreateKey", + request_serializer=recaptchaenterprise.CreateKeyRequest.serialize, + response_deserializer=recaptchaenterprise.Key.deserialize, + ) + return self._stubs["create_key"] + + @property + def list_keys( + self, + ) -> Callable[ + [recaptchaenterprise.ListKeysRequest], + Awaitable[recaptchaenterprise.ListKeysResponse], + ]: + r"""Return a callable for the list keys method over gRPC. + + Returns the list of all keys that belong to a + project. + + Returns: + Callable[[~.ListKeysRequest], + Awaitable[~.ListKeysResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_keys" not in self._stubs: + self._stubs["list_keys"] = self.grpc_channel.unary_unary( + "/google.cloud.recaptchaenterprise.v1.RecaptchaEnterpriseService/ListKeys", + request_serializer=recaptchaenterprise.ListKeysRequest.serialize, + response_deserializer=recaptchaenterprise.ListKeysResponse.deserialize, + ) + return self._stubs["list_keys"] + + @property + def get_key( + self, + ) -> Callable[ + [recaptchaenterprise.GetKeyRequest], Awaitable[recaptchaenterprise.Key] + ]: + r"""Return a callable for the get key method over gRPC. + + Returns the specified key. + + Returns: + Callable[[~.GetKeyRequest], + Awaitable[~.Key]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_key" not in self._stubs: + self._stubs["get_key"] = self.grpc_channel.unary_unary( + "/google.cloud.recaptchaenterprise.v1.RecaptchaEnterpriseService/GetKey", + request_serializer=recaptchaenterprise.GetKeyRequest.serialize, + response_deserializer=recaptchaenterprise.Key.deserialize, + ) + return self._stubs["get_key"] + + @property + def update_key( + self, + ) -> Callable[ + [recaptchaenterprise.UpdateKeyRequest], Awaitable[recaptchaenterprise.Key] + ]: + r"""Return a callable for the update key method over gRPC. + + Updates the specified key. + + Returns: + Callable[[~.UpdateKeyRequest], + Awaitable[~.Key]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "update_key" not in self._stubs: + self._stubs["update_key"] = self.grpc_channel.unary_unary( + "/google.cloud.recaptchaenterprise.v1.RecaptchaEnterpriseService/UpdateKey", + request_serializer=recaptchaenterprise.UpdateKeyRequest.serialize, + response_deserializer=recaptchaenterprise.Key.deserialize, + ) + return self._stubs["update_key"] + + @property + def delete_key( + self, + ) -> Callable[[recaptchaenterprise.DeleteKeyRequest], Awaitable[empty.Empty]]: + r"""Return a callable for the delete key method over gRPC. + + Deletes the specified key. + + Returns: + Callable[[~.DeleteKeyRequest], + Awaitable[~.Empty]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_key" not in self._stubs: + self._stubs["delete_key"] = self.grpc_channel.unary_unary( + "/google.cloud.recaptchaenterprise.v1.RecaptchaEnterpriseService/DeleteKey", + request_serializer=recaptchaenterprise.DeleteKeyRequest.serialize, + response_deserializer=empty.Empty.FromString, + ) + return self._stubs["delete_key"] + + +__all__ = ("RecaptchaEnterpriseServiceGrpcAsyncIOTransport",) diff --git a/google/cloud/recaptchaenterprise_v1/types/__init__.py b/google/cloud/recaptchaenterprise_v1/types/__init__.py index 1990d5b..6f9058a 100644 --- a/google/cloud/recaptchaenterprise_v1/types/__init__.py +++ b/google/cloud/recaptchaenterprise_v1/types/__init__.py @@ -35,7 +35,6 @@ IOSKeySettings, ) - __all__ = ( "CreateAssessmentRequest", "AnnotateAssessmentRequest", diff --git a/google/cloud/recaptchaenterprise_v1/types/recaptchaenterprise.py b/google/cloud/recaptchaenterprise_v1/types/recaptchaenterprise.py index 75288bf..366e1ce 100644 --- a/google/cloud/recaptchaenterprise_v1/types/recaptchaenterprise.py +++ b/google/cloud/recaptchaenterprise_v1/types/recaptchaenterprise.py @@ -54,12 +54,13 @@ class CreateAssessmentRequest(proto.Message): Required. The name of the project in which the assessment will be created, in the format "projects/{project}". - assessment (~.recaptchaenterprise.Assessment): + assessment (google.cloud.recaptchaenterprise_v1.types.Assessment): Required. The assessment details. """ parent = proto.Field(proto.STRING, number=1) - assessment = proto.Field(proto.MESSAGE, number=2, message="Assessment") + + assessment = proto.Field(proto.MESSAGE, number=2, message="Assessment",) class AnnotateAssessmentRequest(proto.Message): @@ -70,7 +71,7 @@ class AnnotateAssessmentRequest(proto.Message): Required. The resource name of the Assessment, in the format "projects/{project}/assessments/{assessment}". - annotation (~.recaptchaenterprise.AnnotateAssessmentRequest.Annotation): + annotation (google.cloud.recaptchaenterprise_v1.types.AnnotateAssessmentRequest.Annotation): Required. The annotation that will be assigned to the Event. """ @@ -84,7 +85,8 @@ class Annotation(proto.Enum): PASSWORD_INCORRECT = 4 name = proto.Field(proto.STRING, number=1) - annotation = proto.Field(proto.ENUM, number=2, enum=Annotation) + + annotation = proto.Field(proto.ENUM, number=2, enum=Annotation,) class AnnotateAssessmentResponse(proto.Message): @@ -99,20 +101,23 @@ class Assessment(proto.Message): Output only. The resource name for the Assessment in the format "projects/{project}/assessments/{assessment}". - event (~.recaptchaenterprise.Event): + event (google.cloud.recaptchaenterprise_v1.types.Event): The event being assessed. - risk_analysis (~.recaptchaenterprise.RiskAnalysis): + risk_analysis (google.cloud.recaptchaenterprise_v1.types.RiskAnalysis): Output only. The risk analysis result for the event being assessed. - token_properties (~.recaptchaenterprise.TokenProperties): + token_properties (google.cloud.recaptchaenterprise_v1.types.TokenProperties): Output only. Properties of the provided event token. """ name = proto.Field(proto.STRING, number=1) - event = proto.Field(proto.MESSAGE, number=2, message="Event") - risk_analysis = proto.Field(proto.MESSAGE, number=3, message="RiskAnalysis") - token_properties = proto.Field(proto.MESSAGE, number=4, message="TokenProperties") + + event = proto.Field(proto.MESSAGE, number=2, message="Event",) + + risk_analysis = proto.Field(proto.MESSAGE, number=3, message="RiskAnalysis",) + + token_properties = proto.Field(proto.MESSAGE, number=4, message="TokenProperties",) class Event(proto.Message): @@ -143,9 +148,13 @@ class Event(proto.Message): """ token = proto.Field(proto.STRING, number=1) + site_key = proto.Field(proto.STRING, number=2) + user_agent = proto.Field(proto.STRING, number=3) + user_ip_address = proto.Field(proto.STRING, number=4) + expected_action = proto.Field(proto.STRING, number=5) @@ -157,7 +166,7 @@ class RiskAnalysis(proto.Message): Legitimate event score from 0.0 to 1.0. (1.0 means very likely legitimate traffic while 0.0 means very likely non-legitimate traffic). - reasons (Sequence[~.recaptchaenterprise.RiskAnalysis.ClassificationReason]): + reasons (Sequence[google.cloud.recaptchaenterprise_v1.types.RiskAnalysis.ClassificationReason]): Reasons contributing to the risk analysis verdict. """ @@ -174,7 +183,8 @@ class ClassificationReason(proto.Enum): LOW_CONFIDENCE_SCORE = 5 score = proto.Field(proto.FLOAT, number=1) - reasons = proto.RepeatedField(proto.ENUM, number=2, enum=ClassificationReason) + + reasons = proto.RepeatedField(proto.ENUM, number=2, enum=ClassificationReason,) class TokenProperties(proto.Message): @@ -188,10 +198,10 @@ class TokenProperties(proto.Message): solve a challenge or a sitekey mismatch (i.e the sitekey used to generate the token was different than the one specified in the assessment). - invalid_reason (~.recaptchaenterprise.TokenProperties.InvalidReason): + invalid_reason (google.cloud.recaptchaenterprise_v1.types.TokenProperties.InvalidReason): Reason associated with the response when valid = false. - create_time (~.timestamp.Timestamp): + create_time (google.protobuf.timestamp_pb2.Timestamp): The timestamp corresponding to the generation of the token. hostname (str): @@ -213,9 +223,13 @@ class InvalidReason(proto.Enum): MISSING = 5 valid = proto.Field(proto.BOOL, number=1) - invalid_reason = proto.Field(proto.ENUM, number=2, enum=InvalidReason) - create_time = proto.Field(proto.MESSAGE, number=3, message=timestamp.Timestamp) + + invalid_reason = proto.Field(proto.ENUM, number=2, enum=InvalidReason,) + + create_time = proto.Field(proto.MESSAGE, number=3, message=timestamp.Timestamp,) + hostname = proto.Field(proto.STRING, number=4) + action = proto.Field(proto.STRING, number=5) @@ -227,13 +241,14 @@ class CreateKeyRequest(proto.Message): Required. The name of the project in which the key will be created, in the format "projects/{project}". - key (~.recaptchaenterprise.Key): + key (google.cloud.recaptchaenterprise_v1.types.Key): Required. Information to create a reCAPTCHA Enterprise key. """ parent = proto.Field(proto.STRING, number=1) - key = proto.Field(proto.MESSAGE, number=2, message="Key") + + key = proto.Field(proto.MESSAGE, number=2, message="Key",) class ListKeysRequest(proto.Message): @@ -253,7 +268,9 @@ class ListKeysRequest(proto.Message): """ parent = proto.Field(proto.STRING, number=1) + page_size = proto.Field(proto.INT32, number=2) + page_token = proto.Field(proto.STRING, number=3) @@ -261,7 +278,7 @@ class ListKeysResponse(proto.Message): r"""Response to request to list keys in a project. Attributes: - keys (Sequence[~.recaptchaenterprise.Key]): + keys (Sequence[google.cloud.recaptchaenterprise_v1.types.Key]): Key details. next_page_token (str): Token to retrieve the next page of results. @@ -272,7 +289,8 @@ class ListKeysResponse(proto.Message): def raw_page(self): return self - keys = proto.RepeatedField(proto.MESSAGE, number=1, message="Key") + keys = proto.RepeatedField(proto.MESSAGE, number=1, message="Key",) + next_page_token = proto.Field(proto.STRING, number=2) @@ -292,16 +310,17 @@ class UpdateKeyRequest(proto.Message): r"""The update key request message. Attributes: - key (~.recaptchaenterprise.Key): + key (google.cloud.recaptchaenterprise_v1.types.Key): Required. The key to update. - update_mask (~.field_mask.FieldMask): + update_mask (google.protobuf.field_mask_pb2.FieldMask): Optional. The mask to control which field of the key get updated. If the mask is not present, all fields will be updated. """ - key = proto.Field(proto.MESSAGE, number=1, message="Key") - update_mask = proto.Field(proto.MESSAGE, number=2, message=field_mask.FieldMask) + key = proto.Field(proto.MESSAGE, number=1, message="Key",) + + update_mask = proto.Field(proto.MESSAGE, number=2, message=field_mask.FieldMask,) class DeleteKeyRequest(proto.Message): @@ -327,34 +346,47 @@ class Key(proto.Message): display_name (str): Human-readable display name of this key. Modifiable by user. - web_settings (~.recaptchaenterprise.WebKeySettings): + web_settings (google.cloud.recaptchaenterprise_v1.types.WebKeySettings): Settings for keys that can be used by websites. - android_settings (~.recaptchaenterprise.AndroidKeySettings): + android_settings (google.cloud.recaptchaenterprise_v1.types.AndroidKeySettings): Settings for keys that can be used by Android apps. - ios_settings (~.recaptchaenterprise.IOSKeySettings): + ios_settings (google.cloud.recaptchaenterprise_v1.types.IOSKeySettings): Settings for keys that can be used by iOS apps. - labels (Sequence[~.recaptchaenterprise.Key.LabelsEntry]): + labels (Sequence[google.cloud.recaptchaenterprise_v1.types.Key.LabelsEntry]): Optional. See Creating and managing labels. - create_time (~.timestamp.Timestamp): + create_time (google.protobuf.timestamp_pb2.Timestamp): The timestamp corresponding to the creation of this Key. """ name = proto.Field(proto.STRING, number=1) + display_name = proto.Field(proto.STRING, number=2) - web_settings = proto.Field(proto.MESSAGE, number=3, message="WebKeySettings") + + web_settings = proto.Field( + proto.MESSAGE, number=3, oneof="platform_settings", message="WebKeySettings", + ) + android_settings = proto.Field( - proto.MESSAGE, number=4, message="AndroidKeySettings" + proto.MESSAGE, + number=4, + oneof="platform_settings", + message="AndroidKeySettings", ) - ios_settings = proto.Field(proto.MESSAGE, number=5, message="IOSKeySettings") + + ios_settings = proto.Field( + proto.MESSAGE, number=5, oneof="platform_settings", message="IOSKeySettings", + ) + labels = proto.MapField(proto.STRING, proto.STRING, number=6) - create_time = proto.Field(proto.MESSAGE, number=7, message=timestamp.Timestamp) + + create_time = proto.Field(proto.MESSAGE, number=7, message=timestamp.Timestamp,) class WebKeySettings(proto.Message): @@ -374,10 +406,10 @@ class WebKeySettings(proto.Message): allow_amp_traffic (bool): Required. Whether this key can be used on AMP (Accelerated Mobile Pages) websites. - integration_type (~.recaptchaenterprise.WebKeySettings.IntegrationType): + integration_type (google.cloud.recaptchaenterprise_v1.types.WebKeySettings.IntegrationType): Required. Describes how this key is integrated with the website. - challenge_security_preference (~.recaptchaenterprise.WebKeySettings.ChallengeSecurityPreference): + challenge_security_preference (google.cloud.recaptchaenterprise_v1.types.WebKeySettings.ChallengeSecurityPreference): Settings for the frequency and difficulty at which this key triggers captcha challenges. This should only be specified for IntegrationTypes @@ -401,11 +433,15 @@ class ChallengeSecurityPreference(proto.Enum): SECURITY = 3 allow_all_domains = proto.Field(proto.BOOL, number=3) + allowed_domains = proto.RepeatedField(proto.STRING, number=1) + allow_amp_traffic = proto.Field(proto.BOOL, number=2) - integration_type = proto.Field(proto.ENUM, number=4, enum=IntegrationType) + + integration_type = proto.Field(proto.ENUM, number=4, enum=IntegrationType,) + challenge_security_preference = proto.Field( - proto.ENUM, number=5, enum=ChallengeSecurityPreference + proto.ENUM, number=5, enum=ChallengeSecurityPreference, ) diff --git a/noxfile.py b/noxfile.py index 0cc4578..e938b7f 100644 --- a/noxfile.py +++ b/noxfile.py @@ -28,7 +28,18 @@ 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"] + +# 'docfx' is excluded since it only needs to run in 'docs-presubmit' +nox.options.sessions = [ + "unit", + "system", + "cover", + "lint", + "lint_setup_py", + "blacken", + "docs", +] @nox.session(python=DEFAULT_PYTHON_VERSION) @@ -122,11 +133,9 @@ def system(session): # Install all test dependencies, then install this package into the # virtualenv's dist-packages. - session.install( "mock", "pytest", "google-cloud-testutils", ) - session.install("-e", ".") # Run py.test against the system tests. diff --git a/scripts/fixup_recaptchaenterprise_v1_keywords.py b/scripts/fixup_recaptchaenterprise_v1_keywords.py new file mode 100644 index 0000000..baf7f33 --- /dev/null +++ b/scripts/fixup_recaptchaenterprise_v1_keywords.py @@ -0,0 +1,185 @@ +#! /usr/bin/env python3 +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +import argparse +import os +import libcst as cst +import pathlib +import sys +from typing import (Any, Callable, Dict, List, Sequence, Tuple) + + +def partition( + predicate: Callable[[Any], bool], + iterator: Sequence[Any] +) -> Tuple[List[Any], List[Any]]: + """A stable, out-of-place partition.""" + results = ([], []) + + for i in iterator: + results[int(predicate(i))].append(i) + + # Returns trueList, falseList + return results[1], results[0] + + +class recaptchaenterpriseCallTransformer(cst.CSTTransformer): + CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') + METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { + 'annotate_assessment': ('name', 'annotation', ), + 'create_assessment': ('parent', 'assessment', ), + 'create_key': ('parent', 'key', ), + 'delete_key': ('name', ), + 'get_key': ('name', ), + 'list_keys': ('parent', 'page_size', 'page_token', ), + 'update_key': ('key', 'update_mask', ), + + } + + def leave_Call(self, original: cst.Call, updated: cst.Call) -> cst.CSTNode: + try: + key = original.func.attr.value + kword_params = self.METHOD_TO_PARAMS[key] + except (AttributeError, KeyError): + # Either not a method from the API or too convoluted to be sure. + return updated + + # If the existing code is valid, keyword args come after positional args. + # Therefore, all positional args must map to the first parameters. + args, kwargs = partition(lambda a: not bool(a.keyword), updated.args) + if any(k.keyword.value == "request" for k in kwargs): + # We've already fixed this file, don't fix it again. + return updated + + kwargs, ctrl_kwargs = partition( + lambda a: not a.keyword.value in self.CTRL_PARAMS, + kwargs + ) + + args, ctrl_args = args[:len(kword_params)], args[len(kword_params):] + ctrl_kwargs.extend(cst.Arg(value=a.value, keyword=cst.Name(value=ctrl)) + for a, ctrl in zip(ctrl_args, self.CTRL_PARAMS)) + + request_arg = cst.Arg( + value=cst.Dict([ + cst.DictElement( + cst.SimpleString("'{}'".format(name)), + cst.Element(value=arg.value) + ) + # Note: the args + kwargs looks silly, but keep in mind that + # the control parameters had to be stripped out, and that + # those could have been passed positionally or by keyword. + for name, arg in zip(kword_params, args + kwargs)]), + keyword=cst.Name("request") + ) + + return updated.with_changes( + args=[request_arg] + ctrl_kwargs + ) + + +def fix_files( + in_dir: pathlib.Path, + out_dir: pathlib.Path, + *, + transformer=recaptchaenterpriseCallTransformer(), +): + """Duplicate the input dir to the output dir, fixing file method calls. + + Preconditions: + * in_dir is a real directory + * out_dir is a real, empty directory + """ + pyfile_gen = ( + pathlib.Path(os.path.join(root, f)) + for root, _, files in os.walk(in_dir) + for f in files if os.path.splitext(f)[1] == ".py" + ) + + for fpath in pyfile_gen: + with open(fpath, 'r') as f: + src = f.read() + + # Parse the code and insert method call fixes. + tree = cst.parse_module(src) + updated = tree.visit(transformer) + + # Create the path and directory structure for the new file. + updated_path = out_dir.joinpath(fpath.relative_to(in_dir)) + updated_path.parent.mkdir(parents=True, exist_ok=True) + + # Generate the updated source file at the corresponding path. + with open(updated_path, 'w') as f: + f.write(updated.code) + + +if __name__ == '__main__': + parser = argparse.ArgumentParser( + description="""Fix up source that uses the recaptchaenterprise client library. + +The existing sources are NOT overwritten but are copied to output_dir with changes made. + +Note: This tool operates at a best-effort level at converting positional + parameters in client method calls to keyword based parameters. + Cases where it WILL FAIL include + A) * or ** expansion in a method call. + B) Calls via function or method alias (includes free function calls) + C) Indirect or dispatched calls (e.g. the method is looked up dynamically) + + These all constitute false negatives. The tool will also detect false + positives when an API method shares a name with another method. +""") + parser.add_argument( + '-d', + '--input-directory', + required=True, + dest='input_dir', + help='the input directory to walk for python files to fix up', + ) + parser.add_argument( + '-o', + '--output-directory', + required=True, + dest='output_dir', + help='the directory to output files fixed via un-flattening', + ) + args = parser.parse_args() + input_dir = pathlib.Path(args.input_dir) + output_dir = pathlib.Path(args.output_dir) + if not input_dir.is_dir(): + print( + f"input directory '{input_dir}' does not exist or is not a directory", + file=sys.stderr, + ) + sys.exit(-1) + + if not output_dir.is_dir(): + print( + f"output directory '{output_dir}' does not exist or is not a directory", + file=sys.stderr, + ) + sys.exit(-1) + + if os.listdir(output_dir): + print( + f"output directory '{output_dir}' is not empty", + file=sys.stderr, + ) + sys.exit(-1) + + fix_files(input_dir, output_dir) diff --git a/setup.py b/setup.py index 06f2bdc..dcb4b06 100644 --- a/setup.py +++ b/setup.py @@ -40,7 +40,7 @@ platforms="Posix; MacOS X; Windows", include_package_data=True, install_requires=( - "google-api-core[grpc] >= 1.21.0, < 2.0.0dev", + "google-api-core[grpc] >= 1.22.2, < 2.0.0dev", "proto-plus >= 1.10.0", ), python_requires=">=3.6", diff --git a/synth.metadata b/synth.metadata index fd0631a..a5a9849 100644 --- a/synth.metadata +++ b/synth.metadata @@ -3,30 +3,30 @@ { "git": { "name": ".", - "remote": "https://github.com/googleapis/python-recaptcha-enterprise.git", - "sha": "7324dab498edf1e202eec05d3c85efb7cd9d2d43" + "remote": "git@github.com:googleapis/python-recaptcha-enterprise", + "sha": "24a724739ccd8d627e44dec23c05f47960bc276f" } }, { "git": { "name": "googleapis", "remote": "https://github.com/googleapis/googleapis.git", - "sha": "eafa840ceec23b44a5c21670288107c661252711", - "internalRef": "313488995" + "sha": "61ab0348bd228c942898aee291d677f0afdb888c", + "internalRef": "352069361" } }, { "git": { "name": "synthtool", "remote": "https://github.com/googleapis/synthtool.git", - "sha": "274dd49554809834287c24b6dd324a85283f1182" + "sha": "16ec872dd898d7de6e1822badfac32484b5d9031" } }, { "git": { "name": "synthtool", "remote": "https://github.com/googleapis/synthtool.git", - "sha": "71b8a272549c06b5768d00fa48d3ae990e871bec" + "sha": "16ec872dd898d7de6e1822badfac32484b5d9031" } } ], @@ -37,7 +37,7 @@ "apiName": "recaptchaenterprise", "apiVersion": "v1", "language": "python", - "generator": "gapic-generator-python" + "generator": "bazel" } } ] diff --git a/synth.py b/synth.py index f33bcdb..e275482 100644 --- a/synth.py +++ b/synth.py @@ -25,13 +25,16 @@ # ---------------------------------------------------------------------------- # Generate reCAPTCHA Enterprise GAPIC layer # ---------------------------------------------------------------------------- -library = gapic.py_library( - service="recaptchaenterprise", - version="v1", - bazel_target=f"//google/cloud/recaptchaenterprise/{version}:recaptchaenterprise-{version}-py", -) +versions = ["v1"] + +for version in versions: + library = gapic.py_library( + service="recaptchaenterprise", + version="v1", + bazel_target=f"//google/cloud/recaptchaenterprise/{version}:recaptchaenterprise-{version}-py", + ) -s.move(library, excludes=["nox.py", "setup.py", "README.rst", "docs/index.rst"]) + s.move(library, excludes=["setup.py", "README.rst", "docs/index.rst"]) # rename to google-cloud-recaptcha-enterprise diff --git a/tests/unit/gapic/recaptchaenterprise_v1/__init__.py b/tests/unit/gapic/recaptchaenterprise_v1/__init__.py new file mode 100644 index 0000000..8b13789 --- /dev/null +++ b/tests/unit/gapic/recaptchaenterprise_v1/__init__.py @@ -0,0 +1 @@ + diff --git a/tests/unit/gapic/recaptchaenterprise_v1/test_recaptcha_enterprise_service.py b/tests/unit/gapic/recaptchaenterprise_v1/test_recaptcha_enterprise_service.py index 76c0abc..3f465b2 100644 --- a/tests/unit/gapic/recaptchaenterprise_v1/test_recaptcha_enterprise_service.py +++ b/tests/unit/gapic/recaptchaenterprise_v1/test_recaptcha_enterprise_service.py @@ -15,16 +15,26 @@ # limitations under the License. # -from unittest import mock +import os +import mock import grpc +from grpc.experimental import aio import math import pytest +from proto.marshal.rules.dates import DurationRule, TimestampRule from google import auth from google.api_core import client_options +from google.api_core import exceptions +from google.api_core import gapic_v1 from google.api_core import grpc_helpers +from google.api_core import grpc_helpers_async from google.auth import credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.recaptchaenterprise_v1.services.recaptcha_enterprise_service import ( + RecaptchaEnterpriseServiceAsyncClient, +) from google.cloud.recaptchaenterprise_v1.services.recaptcha_enterprise_service import ( RecaptchaEnterpriseServiceClient, ) @@ -44,6 +54,17 @@ def client_cert_source_callback(): return b"cert bytes", b"key bytes" +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return ( + "foo.googleapis.com" + if ("localhost" in client.DEFAULT_ENDPOINT) + else client.DEFAULT_ENDPOINT + ) + + def test__get_default_mtls_endpoint(): api_endpoint = "example.googleapis.com" api_mtls_endpoint = "example.mtls.googleapis.com" @@ -76,92 +97,380 @@ def test__get_default_mtls_endpoint(): ) -def test_recaptcha_enterprise_service_client_from_service_account_file(): +def test_recaptcha_enterprise_service_client_from_service_account_info(): + creds = credentials.AnonymousCredentials() + with mock.patch.object( + service_account.Credentials, "from_service_account_info" + ) as factory: + factory.return_value = creds + info = {"valid": True} + client = RecaptchaEnterpriseServiceClient.from_service_account_info(info) + assert client.transport._credentials == creds + + assert client.transport._host == "recaptchaenterprise.googleapis.com:443" + + +@pytest.mark.parametrize( + "client_class", + [RecaptchaEnterpriseServiceClient, RecaptchaEnterpriseServiceAsyncClient,], +) +def test_recaptcha_enterprise_service_client_from_service_account_file(client_class): creds = credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_file" ) as factory: factory.return_value = creds - client = RecaptchaEnterpriseServiceClient.from_service_account_file( - "dummy/file/path.json" - ) - assert client._transport._credentials == creds + client = client_class.from_service_account_file("dummy/file/path.json") + assert client.transport._credentials == creds - client = RecaptchaEnterpriseServiceClient.from_service_account_json( - "dummy/file/path.json" - ) - assert client._transport._credentials == creds + client = client_class.from_service_account_json("dummy/file/path.json") + assert client.transport._credentials == creds - assert client._transport._host == "recaptchaenterprise.googleapis.com:443" + assert client.transport._host == "recaptchaenterprise.googleapis.com:443" -def test_recaptcha_enterprise_service_client_client_options(): +def test_recaptcha_enterprise_service_client_get_transport_class(): + transport = RecaptchaEnterpriseServiceClient.get_transport_class() + available_transports = [ + transports.RecaptchaEnterpriseServiceGrpcTransport, + ] + assert transport in available_transports + + transport = RecaptchaEnterpriseServiceClient.get_transport_class("grpc") + assert transport == transports.RecaptchaEnterpriseServiceGrpcTransport + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + ( + RecaptchaEnterpriseServiceClient, + transports.RecaptchaEnterpriseServiceGrpcTransport, + "grpc", + ), + ( + RecaptchaEnterpriseServiceAsyncClient, + transports.RecaptchaEnterpriseServiceGrpcAsyncIOTransport, + "grpc_asyncio", + ), + ], +) +@mock.patch.object( + RecaptchaEnterpriseServiceClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(RecaptchaEnterpriseServiceClient), +) +@mock.patch.object( + RecaptchaEnterpriseServiceAsyncClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(RecaptchaEnterpriseServiceAsyncClient), +) +def test_recaptcha_enterprise_service_client_client_options( + client_class, transport_class, transport_name +): # Check that if channel is provided we won't create a new one. - with mock.patch( - "google.cloud.recaptchaenterprise_v1.services.recaptcha_enterprise_service.RecaptchaEnterpriseServiceClient.get_transport_class" + with mock.patch.object( + RecaptchaEnterpriseServiceClient, "get_transport_class" ) as gtc: - transport = transports.RecaptchaEnterpriseServiceGrpcTransport( - credentials=credentials.AnonymousCredentials() - ) - client = RecaptchaEnterpriseServiceClient(transport=transport) + transport = transport_class(credentials=credentials.AnonymousCredentials()) + client = client_class(transport=transport) gtc.assert_not_called() - # Check mTLS is not triggered with empty client options. - options = client_options.ClientOptions() - with mock.patch( - "google.cloud.recaptchaenterprise_v1.services.recaptcha_enterprise_service.RecaptchaEnterpriseServiceClient.get_transport_class" + # Check that if channel is provided via str we will create a new one. + with mock.patch.object( + RecaptchaEnterpriseServiceClient, "get_transport_class" ) as gtc: - transport = gtc.return_value = mock.MagicMock() - client = RecaptchaEnterpriseServiceClient(client_options=options) - transport.assert_called_once_with( - credentials=None, host=client.DEFAULT_ENDPOINT - ) + client = client_class(transport=transport_name) + gtc.assert_called() - # Check mTLS is not triggered if api_endpoint is provided but - # client_cert_source is None. + # Check the case api_endpoint is provided. options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") - with mock.patch( - "google.cloud.recaptchaenterprise_v1.services.recaptcha_enterprise_service.transports.RecaptchaEnterpriseServiceGrpcTransport.__init__" - ) as grpc_transport: - grpc_transport.return_value = None - client = RecaptchaEnterpriseServiceClient(client_options=options) - grpc_transport.assert_called_once_with( - api_mtls_endpoint=None, - client_cert_source=None, + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( credentials=None, + credentials_file=None, host="squid.clam.whelk", + scopes=None, + ssl_channel_credentials=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, ) - # Check mTLS is triggered if client_cert_source is provided. - options = client_options.ClientOptions( - client_cert_source=client_cert_source_callback - ) - with mock.patch( - "google.cloud.recaptchaenterprise_v1.services.recaptcha_enterprise_service.transports.RecaptchaEnterpriseServiceGrpcTransport.__init__" - ) as grpc_transport: - grpc_transport.return_value = None - client = RecaptchaEnterpriseServiceClient(client_options=options) - grpc_transport.assert_called_once_with( - api_mtls_endpoint=client.DEFAULT_MTLS_ENDPOINT, - client_cert_source=client_cert_source_callback, + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + 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_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + 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_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, ) - # Check mTLS is triggered if api_endpoint and client_cert_source are provided. - options = client_options.ClientOptions( - api_endpoint="squid.clam.whelk", client_cert_source=client_cert_source_callback - ) - with mock.patch( - "google.cloud.recaptchaenterprise_v1.services.recaptcha_enterprise_service.transports.RecaptchaEnterpriseServiceGrpcTransport.__init__" - ) as grpc_transport: - grpc_transport.return_value = None - client = RecaptchaEnterpriseServiceClient(client_options=options) - grpc_transport.assert_called_once_with( - api_mtls_endpoint="squid.clam.whelk", - client_cert_source=client_cert_source_callback, + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name,use_client_cert_env", + [ + ( + RecaptchaEnterpriseServiceClient, + transports.RecaptchaEnterpriseServiceGrpcTransport, + "grpc", + "true", + ), + ( + RecaptchaEnterpriseServiceAsyncClient, + transports.RecaptchaEnterpriseServiceGrpcAsyncIOTransport, + "grpc_asyncio", + "true", + ), + ( + RecaptchaEnterpriseServiceClient, + transports.RecaptchaEnterpriseServiceGrpcTransport, + "grpc", + "false", + ), + ( + RecaptchaEnterpriseServiceAsyncClient, + transports.RecaptchaEnterpriseServiceGrpcAsyncIOTransport, + "grpc_asyncio", + "false", + ), + ], +) +@mock.patch.object( + RecaptchaEnterpriseServiceClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(RecaptchaEnterpriseServiceClient), +) +@mock.patch.object( + RecaptchaEnterpriseServiceAsyncClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(RecaptchaEnterpriseServiceAsyncClient), +) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_recaptcha_enterprise_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: + ssl_channel_creds = mock.Mock() + with mock.patch( + "grpc.ssl_channel_credentials", return_value=ssl_channel_creds + ): + patched.return_value = None + 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=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 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.grpc.SslCredentials.__init__", return_value=None + ): + 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( + "client_class,transport_class,transport_name", + [ + ( + RecaptchaEnterpriseServiceClient, + transports.RecaptchaEnterpriseServiceGrpcTransport, + "grpc", + ), + ( + RecaptchaEnterpriseServiceAsyncClient, + transports.RecaptchaEnterpriseServiceGrpcAsyncIOTransport, + "grpc_asyncio", + ), + ], +) +def test_recaptcha_enterprise_service_client_client_options_scopes( + client_class, transport_class, transport_name +): + # Check the case scopes are provided. + options = client_options.ClientOptions(scopes=["1", "2"],) + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( credentials=None, - host="squid.clam.whelk", + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=["1", "2"], + ssl_channel_credentials=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + ( + RecaptchaEnterpriseServiceClient, + transports.RecaptchaEnterpriseServiceGrpcTransport, + "grpc", + ), + ( + RecaptchaEnterpriseServiceAsyncClient, + transports.RecaptchaEnterpriseServiceGrpcAsyncIOTransport, + "grpc_asyncio", + ), + ], +) +def test_recaptcha_enterprise_service_client_client_options_credentials_file( + client_class, transport_class, transport_name +): + # Check the case credentials file is provided. + options = client_options.ClientOptions(credentials_file="credentials.json") + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + ssl_channel_credentials=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, ) @@ -174,28 +483,33 @@ def test_recaptcha_enterprise_service_client_client_options_from_dict(): client_options={"api_endpoint": "squid.clam.whelk"} ) grpc_transport.assert_called_once_with( - api_mtls_endpoint=None, - client_cert_source=None, credentials=None, + credentials_file=None, host="squid.clam.whelk", + scopes=None, + ssl_channel_credentials=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, ) -def test_create_assessment(transport: str = "grpc"): +def test_create_assessment( + transport: str = "grpc", request_type=recaptchaenterprise.CreateAssessmentRequest +): client = RecaptchaEnterpriseServiceClient( - credentials=credentials.AnonymousCredentials(), transport=transport + 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 = recaptchaenterprise.CreateAssessmentRequest() + request = request_type() # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client._transport.create_assessment), "__call__" + type(client.transport.create_assessment), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = recaptchaenterprise.Assessment(name="name_value") + call.return_value = recaptchaenterprise.Assessment(name="name_value",) response = client.create_assessment(request) @@ -203,28 +517,134 @@ def test_create_assessment(transport: str = "grpc"): assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == request + assert args[0] == recaptchaenterprise.CreateAssessmentRequest() + + # Establish that the response is the type that we expect. + + assert isinstance(response, recaptchaenterprise.Assessment) + + assert response.name == "name_value" + + +def test_create_assessment_from_dict(): + test_create_assessment(request_type=dict) + + +@pytest.mark.asyncio +async def test_create_assessment_async( + transport: str = "grpc_asyncio", + request_type=recaptchaenterprise.CreateAssessmentRequest, +): + client = RecaptchaEnterpriseServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_assessment), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + recaptchaenterprise.Assessment(name="name_value",) + ) + + response = await client.create_assessment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == recaptchaenterprise.CreateAssessmentRequest() # Establish that the response is the type that we expect. assert isinstance(response, recaptchaenterprise.Assessment) + assert response.name == "name_value" +@pytest.mark.asyncio +async def test_create_assessment_async_from_dict(): + await test_create_assessment_async(request_type=dict) + + +def test_create_assessment_field_headers(): + client = RecaptchaEnterpriseServiceClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = recaptchaenterprise.CreateAssessmentRequest() + request.parent = "parent/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_assessment), "__call__" + ) as call: + call.return_value = recaptchaenterprise.Assessment() + + client.create_assessment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "parent=parent/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_create_assessment_field_headers_async(): + client = RecaptchaEnterpriseServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = recaptchaenterprise.CreateAssessmentRequest() + request.parent = "parent/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_assessment), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + recaptchaenterprise.Assessment() + ) + + await client.create_assessment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "parent=parent/value",) in kw["metadata"] + + def test_create_assessment_flattened(): client = RecaptchaEnterpriseServiceClient( - credentials=credentials.AnonymousCredentials() + credentials=credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client._transport.create_assessment), "__call__" + type(client.transport.create_assessment), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = recaptchaenterprise.Assessment() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - response = client.create_assessment( + client.create_assessment( parent="parent_value", assessment=recaptchaenterprise.Assessment(name="name_value"), ) @@ -233,13 +653,15 @@ def test_create_assessment_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] + assert args[0].parent == "parent_value" + assert args[0].assessment == recaptchaenterprise.Assessment(name="name_value") def test_create_assessment_flattened_error(): client = RecaptchaEnterpriseServiceClient( - credentials=credentials.AnonymousCredentials() + credentials=credentials.AnonymousCredentials(), ) # Attempting to call a method with both a request object and flattened @@ -252,150 +674,516 @@ def test_create_assessment_flattened_error(): ) -def test_annotate_assessment(transport: str = "grpc"): - client = RecaptchaEnterpriseServiceClient( - 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 = recaptchaenterprise.AnnotateAssessmentRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client._transport.annotate_assessment), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = recaptchaenterprise.AnnotateAssessmentResponse() - - response = client.annotate_assessment(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, recaptchaenterprise.AnnotateAssessmentResponse) - - -def test_annotate_assessment_flattened(): - client = RecaptchaEnterpriseServiceClient( - credentials=credentials.AnonymousCredentials() +@pytest.mark.asyncio +async def test_create_assessment_flattened_async(): + client = RecaptchaEnterpriseServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client._transport.annotate_assessment), "__call__" + type(client.transport.create_assessment), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = recaptchaenterprise.AnnotateAssessmentResponse() + call.return_value = recaptchaenterprise.Assessment() + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + recaptchaenterprise.Assessment() + ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - response = client.annotate_assessment( - name="name_value", - annotation=recaptchaenterprise.AnnotateAssessmentRequest.Annotation.LEGITIMATE, + response = await client.create_assessment( + parent="parent_value", + assessment=recaptchaenterprise.Assessment(name="name_value"), ) # Establish that the underlying call was made with the expected # request object values. - assert len(call.mock_calls) == 1 + assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" - assert ( - args[0].annotation - == recaptchaenterprise.AnnotateAssessmentRequest.Annotation.LEGITIMATE - ) + assert args[0].parent == "parent_value" -def test_annotate_assessment_flattened_error(): - client = RecaptchaEnterpriseServiceClient( - credentials=credentials.AnonymousCredentials() + assert args[0].assessment == recaptchaenterprise.Assessment(name="name_value") + + +@pytest.mark.asyncio +async def test_create_assessment_flattened_error_async(): + client = RecaptchaEnterpriseServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), ) # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.annotate_assessment( - recaptchaenterprise.AnnotateAssessmentRequest(), - name="name_value", - annotation=recaptchaenterprise.AnnotateAssessmentRequest.Annotation.LEGITIMATE, + await client.create_assessment( + recaptchaenterprise.CreateAssessmentRequest(), + parent="parent_value", + assessment=recaptchaenterprise.Assessment(name="name_value"), ) -def test_create_key(transport: str = "grpc"): +def test_annotate_assessment( + transport: str = "grpc", request_type=recaptchaenterprise.AnnotateAssessmentRequest +): client = RecaptchaEnterpriseServiceClient( - credentials=credentials.AnonymousCredentials(), transport=transport + 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 = recaptchaenterprise.CreateKeyRequest() + request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client._transport.create_key), "__call__") as call: + with mock.patch.object( + type(client.transport.annotate_assessment), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value = recaptchaenterprise.Key( - name="name_value", display_name="display_name_value" - ) + call.return_value = recaptchaenterprise.AnnotateAssessmentResponse() - response = client.create_key(request) + response = client.annotate_assessment(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == request + assert args[0] == recaptchaenterprise.AnnotateAssessmentRequest() # Establish that the response is the type that we expect. - assert isinstance(response, recaptchaenterprise.Key) - assert response.name == "name_value" - assert response.display_name == "display_name_value" + + assert isinstance(response, recaptchaenterprise.AnnotateAssessmentResponse) -def test_list_keys(transport: str = "grpc"): - client = RecaptchaEnterpriseServiceClient( - credentials=credentials.AnonymousCredentials(), transport=transport +def test_annotate_assessment_from_dict(): + test_annotate_assessment(request_type=dict) + + +@pytest.mark.asyncio +async def test_annotate_assessment_async( + transport: str = "grpc_asyncio", + request_type=recaptchaenterprise.AnnotateAssessmentRequest, +): + client = RecaptchaEnterpriseServiceAsyncClient( + 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 = recaptchaenterprise.ListKeysRequest() + request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client._transport.list_keys), "__call__") as call: + with mock.patch.object( + type(client.transport.annotate_assessment), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value = recaptchaenterprise.ListKeysResponse( - next_page_token="next_page_token_value" + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + recaptchaenterprise.AnnotateAssessmentResponse() ) - response = client.list_keys(request) + response = await client.annotate_assessment(request) # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 + assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == request + assert args[0] == recaptchaenterprise.AnnotateAssessmentRequest() # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListKeysPager) - assert response.next_page_token == "next_page_token_value" + assert isinstance(response, recaptchaenterprise.AnnotateAssessmentResponse) -def test_list_keys_field_headers(): +@pytest.mark.asyncio +async def test_annotate_assessment_async_from_dict(): + await test_annotate_assessment_async(request_type=dict) + + +def test_annotate_assessment_field_headers(): client = RecaptchaEnterpriseServiceClient( - credentials=credentials.AnonymousCredentials() + credentials=credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = recaptchaenterprise.ListKeysRequest(parent="parent/value") + request = recaptchaenterprise.AnnotateAssessmentRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client._transport.list_keys), "__call__") as call: + with mock.patch.object( + type(client.transport.annotate_assessment), "__call__" + ) as call: + call.return_value = recaptchaenterprise.AnnotateAssessmentResponse() + + client.annotate_assessment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=name/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_annotate_assessment_field_headers_async(): + client = RecaptchaEnterpriseServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = recaptchaenterprise.AnnotateAssessmentRequest() + request.name = "name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.annotate_assessment), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + recaptchaenterprise.AnnotateAssessmentResponse() + ) + + await client.annotate_assessment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=name/value",) in kw["metadata"] + + +def test_annotate_assessment_flattened(): + client = RecaptchaEnterpriseServiceClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.annotate_assessment), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = recaptchaenterprise.AnnotateAssessmentResponse() + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.annotate_assessment( + name="name_value", + annotation=recaptchaenterprise.AnnotateAssessmentRequest.Annotation.LEGITIMATE, + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0].name == "name_value" + + assert ( + args[0].annotation + == recaptchaenterprise.AnnotateAssessmentRequest.Annotation.LEGITIMATE + ) + + +def test_annotate_assessment_flattened_error(): + client = RecaptchaEnterpriseServiceClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.annotate_assessment( + recaptchaenterprise.AnnotateAssessmentRequest(), + name="name_value", + annotation=recaptchaenterprise.AnnotateAssessmentRequest.Annotation.LEGITIMATE, + ) + + +@pytest.mark.asyncio +async def test_annotate_assessment_flattened_async(): + client = RecaptchaEnterpriseServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.annotate_assessment), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = recaptchaenterprise.AnnotateAssessmentResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + recaptchaenterprise.AnnotateAssessmentResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.annotate_assessment( + name="name_value", + annotation=recaptchaenterprise.AnnotateAssessmentRequest.Annotation.LEGITIMATE, + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0].name == "name_value" + + assert ( + args[0].annotation + == recaptchaenterprise.AnnotateAssessmentRequest.Annotation.LEGITIMATE + ) + + +@pytest.mark.asyncio +async def test_annotate_assessment_flattened_error_async(): + client = RecaptchaEnterpriseServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.annotate_assessment( + recaptchaenterprise.AnnotateAssessmentRequest(), + name="name_value", + annotation=recaptchaenterprise.AnnotateAssessmentRequest.Annotation.LEGITIMATE, + ) + + +def test_create_key( + transport: str = "grpc", request_type=recaptchaenterprise.CreateKeyRequest +): + client = RecaptchaEnterpriseServiceClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.create_key), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = recaptchaenterprise.Key( + name="name_value", + display_name="display_name_value", + web_settings=recaptchaenterprise.WebKeySettings(allow_all_domains=True), + ) + + response = client.create_key(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == recaptchaenterprise.CreateKeyRequest() + + # Establish that the response is the type that we expect. + + assert isinstance(response, recaptchaenterprise.Key) + + assert response.name == "name_value" + + assert response.display_name == "display_name_value" + + +def test_create_key_from_dict(): + test_create_key(request_type=dict) + + +@pytest.mark.asyncio +async def test_create_key_async( + transport: str = "grpc_asyncio", request_type=recaptchaenterprise.CreateKeyRequest +): + client = RecaptchaEnterpriseServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.create_key), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + recaptchaenterprise.Key( + name="name_value", display_name="display_name_value", + ) + ) + + response = await client.create_key(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == recaptchaenterprise.CreateKeyRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, recaptchaenterprise.Key) + + assert response.name == "name_value" + + assert response.display_name == "display_name_value" + + +@pytest.mark.asyncio +async def test_create_key_async_from_dict(): + await test_create_key_async(request_type=dict) + + +def test_create_key_field_headers(): + client = RecaptchaEnterpriseServiceClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = recaptchaenterprise.CreateKeyRequest() + request.parent = "parent/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.create_key), "__call__") as call: + call.return_value = recaptchaenterprise.Key() + + client.create_key(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "parent=parent/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_create_key_field_headers_async(): + client = RecaptchaEnterpriseServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = recaptchaenterprise.CreateKeyRequest() + request.parent = "parent/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.create_key), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + recaptchaenterprise.Key() + ) + + await client.create_key(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "parent=parent/value",) in kw["metadata"] + + +def test_list_keys( + transport: str = "grpc", request_type=recaptchaenterprise.ListKeysRequest +): + client = RecaptchaEnterpriseServiceClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_keys), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = recaptchaenterprise.ListKeysResponse( + next_page_token="next_page_token_value", + ) + + response = client.list_keys(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == recaptchaenterprise.ListKeysRequest() + + # Establish that the response is the type that we expect. + + assert isinstance(response, pagers.ListKeysPager) + + assert response.next_page_token == "next_page_token_value" + + +def test_list_keys_from_dict(): + test_list_keys(request_type=dict) + + +@pytest.mark.asyncio +async def test_list_keys_async( + transport: str = "grpc_asyncio", request_type=recaptchaenterprise.ListKeysRequest +): + client = RecaptchaEnterpriseServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_keys), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + recaptchaenterprise.ListKeysResponse( + next_page_token="next_page_token_value", + ) + ) + + response = await client.list_keys(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == recaptchaenterprise.ListKeysRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListKeysAsyncPager) + + assert response.next_page_token == "next_page_token_value" + + +@pytest.mark.asyncio +async def test_list_keys_async_from_dict(): + await test_list_keys_async(request_type=dict) + + +def test_list_keys_field_headers(): + client = RecaptchaEnterpriseServiceClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = recaptchaenterprise.ListKeysRequest() + request.parent = "parent/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_keys), "__call__") as call: call.return_value = recaptchaenterprise.ListKeysResponse() + client.list_keys(request) # Establish that the underlying gRPC stub method was called. @@ -405,16 +1193,45 @@ def test_list_keys_field_headers(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "parent=parent/value") in kw["metadata"] + assert ("x-goog-request-params", "parent=parent/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_list_keys_field_headers_async(): + client = RecaptchaEnterpriseServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = recaptchaenterprise.ListKeysRequest() + request.parent = "parent/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_keys), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + recaptchaenterprise.ListKeysResponse() + ) + + await client.list_keys(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "parent=parent/value",) in kw["metadata"] def test_list_keys_pager(): client = RecaptchaEnterpriseServiceClient( - credentials=credentials.AnonymousCredentials + credentials=credentials.AnonymousCredentials, ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client._transport.list_keys), "__call__") as call: + with mock.patch.object(type(client.transport.list_keys), "__call__") as call: # Set the response to a series of pages. call.side_effect = ( recaptchaenterprise.ListKeysResponse( @@ -425,27 +1242,36 @@ def test_list_keys_pager(): ], next_page_token="abc", ), - recaptchaenterprise.ListKeysResponse(keys=[], next_page_token="def"), + recaptchaenterprise.ListKeysResponse(keys=[], next_page_token="def",), recaptchaenterprise.ListKeysResponse( - keys=[recaptchaenterprise.Key()], next_page_token="ghi" + keys=[recaptchaenterprise.Key(),], next_page_token="ghi", ), recaptchaenterprise.ListKeysResponse( - keys=[recaptchaenterprise.Key(), recaptchaenterprise.Key()] + keys=[recaptchaenterprise.Key(), recaptchaenterprise.Key(),], ), RuntimeError, ) - results = [i for i in client.list_keys(request={})] + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), + ) + pager = client.list_keys(request={}) + + assert pager._metadata == metadata + + results = [i for i in pager] assert len(results) == 6 assert all(isinstance(i, recaptchaenterprise.Key) for i in results) def test_list_keys_pages(): client = RecaptchaEnterpriseServiceClient( - credentials=credentials.AnonymousCredentials + credentials=credentials.AnonymousCredentials, ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client._transport.list_keys), "__call__") as call: + with mock.patch.object(type(client.transport.list_keys), "__call__") as call: # Set the response to a series of pages. call.side_effect = ( recaptchaenterprise.ListKeysResponse( @@ -456,63 +1282,331 @@ def test_list_keys_pages(): ], next_page_token="abc", ), - recaptchaenterprise.ListKeysResponse(keys=[], next_page_token="def"), + recaptchaenterprise.ListKeysResponse(keys=[], next_page_token="def",), recaptchaenterprise.ListKeysResponse( - keys=[recaptchaenterprise.Key()], next_page_token="ghi" + keys=[recaptchaenterprise.Key(),], next_page_token="ghi", ), recaptchaenterprise.ListKeysResponse( - keys=[recaptchaenterprise.Key(), recaptchaenterprise.Key()] + keys=[recaptchaenterprise.Key(), recaptchaenterprise.Key(),], ), RuntimeError, ) pages = list(client.list_keys(request={}).pages) - for page, token in zip(pages, ["abc", "def", "ghi", ""]): - assert page.raw_page.next_page_token == token + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.asyncio +async def test_list_keys_async_pager(): + client = RecaptchaEnterpriseServiceAsyncClient( + credentials=credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_keys), "__call__", new_callable=mock.AsyncMock + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + recaptchaenterprise.ListKeysResponse( + keys=[ + recaptchaenterprise.Key(), + recaptchaenterprise.Key(), + recaptchaenterprise.Key(), + ], + next_page_token="abc", + ), + recaptchaenterprise.ListKeysResponse(keys=[], next_page_token="def",), + recaptchaenterprise.ListKeysResponse( + keys=[recaptchaenterprise.Key(),], next_page_token="ghi", + ), + recaptchaenterprise.ListKeysResponse( + keys=[recaptchaenterprise.Key(), recaptchaenterprise.Key(),], + ), + RuntimeError, + ) + async_pager = await client.list_keys(request={},) + assert async_pager.next_page_token == "abc" + responses = [] + async for response in async_pager: + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, recaptchaenterprise.Key) for i in responses) + + +@pytest.mark.asyncio +async def test_list_keys_async_pages(): + client = RecaptchaEnterpriseServiceAsyncClient( + credentials=credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_keys), "__call__", new_callable=mock.AsyncMock + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + recaptchaenterprise.ListKeysResponse( + keys=[ + recaptchaenterprise.Key(), + recaptchaenterprise.Key(), + recaptchaenterprise.Key(), + ], + next_page_token="abc", + ), + recaptchaenterprise.ListKeysResponse(keys=[], next_page_token="def",), + recaptchaenterprise.ListKeysResponse( + keys=[recaptchaenterprise.Key(),], next_page_token="ghi", + ), + recaptchaenterprise.ListKeysResponse( + keys=[recaptchaenterprise.Key(), recaptchaenterprise.Key(),], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.list_keys(request={})).pages: + pages.append(page_) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +def test_get_key( + transport: str = "grpc", request_type=recaptchaenterprise.GetKeyRequest +): + client = RecaptchaEnterpriseServiceClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_key), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = recaptchaenterprise.Key( + name="name_value", + display_name="display_name_value", + web_settings=recaptchaenterprise.WebKeySettings(allow_all_domains=True), + ) + + response = client.get_key(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == recaptchaenterprise.GetKeyRequest() + + # Establish that the response is the type that we expect. + + assert isinstance(response, recaptchaenterprise.Key) + + assert response.name == "name_value" + + assert response.display_name == "display_name_value" + + +def test_get_key_from_dict(): + test_get_key(request_type=dict) + + +@pytest.mark.asyncio +async def test_get_key_async( + transport: str = "grpc_asyncio", request_type=recaptchaenterprise.GetKeyRequest +): + client = RecaptchaEnterpriseServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_key), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + recaptchaenterprise.Key( + name="name_value", display_name="display_name_value", + ) + ) + + response = await client.get_key(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == recaptchaenterprise.GetKeyRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, recaptchaenterprise.Key) + + assert response.name == "name_value" + + assert response.display_name == "display_name_value" + + +@pytest.mark.asyncio +async def test_get_key_async_from_dict(): + await test_get_key_async(request_type=dict) + + +def test_get_key_field_headers(): + client = RecaptchaEnterpriseServiceClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = recaptchaenterprise.GetKeyRequest() + request.name = "name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_key), "__call__") as call: + call.return_value = recaptchaenterprise.Key() + + client.get_key(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=name/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_get_key_field_headers_async(): + client = RecaptchaEnterpriseServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = recaptchaenterprise.GetKeyRequest() + request.name = "name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_key), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + recaptchaenterprise.Key() + ) + + await client.get_key(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=name/value",) in kw["metadata"] -def test_get_key(transport: str = "grpc"): +def test_update_key( + transport: str = "grpc", request_type=recaptchaenterprise.UpdateKeyRequest +): client = RecaptchaEnterpriseServiceClient( - credentials=credentials.AnonymousCredentials(), transport=transport + 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 = recaptchaenterprise.GetKeyRequest() + request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client._transport.get_key), "__call__") as call: + with mock.patch.object(type(client.transport.update_key), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = recaptchaenterprise.Key( - name="name_value", display_name="display_name_value" + name="name_value", + display_name="display_name_value", + web_settings=recaptchaenterprise.WebKeySettings(allow_all_domains=True), ) - response = client.get_key(request) + response = client.update_key(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == request + assert args[0] == recaptchaenterprise.UpdateKeyRequest() # Establish that the response is the type that we expect. + assert isinstance(response, recaptchaenterprise.Key) + assert response.name == "name_value" + assert response.display_name == "display_name_value" -def test_get_key_field_headers(): +def test_update_key_from_dict(): + test_update_key(request_type=dict) + + +@pytest.mark.asyncio +async def test_update_key_async( + transport: str = "grpc_asyncio", request_type=recaptchaenterprise.UpdateKeyRequest +): + client = RecaptchaEnterpriseServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.update_key), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + recaptchaenterprise.Key( + name="name_value", display_name="display_name_value", + ) + ) + + response = await client.update_key(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == recaptchaenterprise.UpdateKeyRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, recaptchaenterprise.Key) + + assert response.name == "name_value" + + assert response.display_name == "display_name_value" + + +@pytest.mark.asyncio +async def test_update_key_async_from_dict(): + await test_update_key_async(request_type=dict) + + +def test_update_key_field_headers(): client = RecaptchaEnterpriseServiceClient( - credentials=credentials.AnonymousCredentials() + credentials=credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = recaptchaenterprise.GetKeyRequest(name="name/value") + request = recaptchaenterprise.UpdateKeyRequest() + request.key.name = "key.name/value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client._transport.get_key), "__call__") as call: + with mock.patch.object(type(client.transport.update_key), "__call__") as call: call.return_value = recaptchaenterprise.Key() - client.get_key(request) + + client.update_key(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -521,100 +1615,254 @@ def test_get_key_field_headers(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "name=name/value") in kw["metadata"] + assert ("x-goog-request-params", "key.name=key.name/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_update_key_field_headers_async(): + client = RecaptchaEnterpriseServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = recaptchaenterprise.UpdateKeyRequest() + request.key.name = "key.name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.update_key), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + recaptchaenterprise.Key() + ) + + await client.update_key(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "key.name=key.name/value",) in kw["metadata"] -def test_update_key(transport: str = "grpc"): +def test_delete_key( + transport: str = "grpc", request_type=recaptchaenterprise.DeleteKeyRequest +): client = RecaptchaEnterpriseServiceClient( - credentials=credentials.AnonymousCredentials(), transport=transport + 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 = recaptchaenterprise.UpdateKeyRequest() + request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client._transport.update_key), "__call__") as call: + with mock.patch.object(type(client.transport.delete_key), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = recaptchaenterprise.Key( - name="name_value", display_name="display_name_value" - ) + call.return_value = None - response = client.update_key(request) + response = client.delete_key(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == request + assert args[0] == recaptchaenterprise.DeleteKeyRequest() # Establish that the response is the type that we expect. - assert isinstance(response, recaptchaenterprise.Key) - assert response.name == "name_value" - assert response.display_name == "display_name_value" + assert response is None -def test_delete_key(transport: str = "grpc"): - client = RecaptchaEnterpriseServiceClient( - credentials=credentials.AnonymousCredentials(), transport=transport +def test_delete_key_from_dict(): + test_delete_key(request_type=dict) + + +@pytest.mark.asyncio +async def test_delete_key_async( + transport: str = "grpc_asyncio", request_type=recaptchaenterprise.DeleteKeyRequest +): + client = RecaptchaEnterpriseServiceAsyncClient( + 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 = recaptchaenterprise.DeleteKeyRequest() + request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client._transport.delete_key), "__call__") as call: + with mock.patch.object(type(client.transport.delete_key), "__call__") as call: # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + + response = await client.delete_key(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == recaptchaenterprise.DeleteKeyRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.asyncio +async def test_delete_key_async_from_dict(): + await test_delete_key_async(request_type=dict) + + +def test_delete_key_field_headers(): + client = RecaptchaEnterpriseServiceClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = recaptchaenterprise.DeleteKeyRequest() + request.name = "name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_key), "__call__") as call: call.return_value = None - response = client.delete_key(request) + client.delete_key(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=name/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_delete_key_field_headers_async(): + client = RecaptchaEnterpriseServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = recaptchaenterprise.DeleteKeyRequest() + request.name = "name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_key), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + + await client.delete_key(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] assert args[0] == request - # Establish that the response is the type that we expect. - assert response is None + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=name/value",) in kw["metadata"] def test_credentials_transport_error(): # It is an error to provide credentials and a transport instance. transport = transports.RecaptchaEnterpriseServiceGrpcTransport( - credentials=credentials.AnonymousCredentials() + credentials=credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = RecaptchaEnterpriseServiceClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.RecaptchaEnterpriseServiceGrpcTransport( + credentials=credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = RecaptchaEnterpriseServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.RecaptchaEnterpriseServiceGrpcTransport( + credentials=credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = RecaptchaEnterpriseServiceClient( - credentials=credentials.AnonymousCredentials(), transport=transport + client_options={"scopes": ["1", "2"]}, transport=transport, ) def test_transport_instance(): # A client may be instantiated with a custom transport instance. transport = transports.RecaptchaEnterpriseServiceGrpcTransport( - credentials=credentials.AnonymousCredentials() + credentials=credentials.AnonymousCredentials(), ) client = RecaptchaEnterpriseServiceClient(transport=transport) - assert client._transport is transport + assert client.transport is transport + + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.RecaptchaEnterpriseServiceGrpcTransport( + credentials=credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.RecaptchaEnterpriseServiceGrpcAsyncIOTransport( + credentials=credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.RecaptchaEnterpriseServiceGrpcTransport, + transports.RecaptchaEnterpriseServiceGrpcAsyncIOTransport, + ], +) +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 = RecaptchaEnterpriseServiceClient( - credentials=credentials.AnonymousCredentials() + credentials=credentials.AnonymousCredentials(), ) assert isinstance( - client._transport, transports.RecaptchaEnterpriseServiceGrpcTransport + client.transport, transports.RecaptchaEnterpriseServiceGrpcTransport, ) +def test_recaptcha_enterprise_service_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(exceptions.DuplicateCredentialArgs): + transport = transports.RecaptchaEnterpriseServiceTransport( + credentials=credentials.AnonymousCredentials(), + credentials_file="credentials.json", + ) + + def test_recaptcha_enterprise_service_base_transport(): # Instantiate the base transport. - transport = transports.RecaptchaEnterpriseServiceTransport( - credentials=credentials.AnonymousCredentials() - ) + with mock.patch( + "google.cloud.recaptchaenterprise_v1.services.recaptcha_enterprise_service.transports.RecaptchaEnterpriseServiceTransport.__init__" + ) as Transport: + Transport.return_value = None + transport = transports.RecaptchaEnterpriseServiceTransport( + credentials=credentials.AnonymousCredentials(), + ) # Every method on the transport should just blindly # raise NotImplementedError. @@ -632,13 +1880,58 @@ def test_recaptcha_enterprise_service_base_transport(): getattr(transport, method)(request=object()) +def test_recaptcha_enterprise_service_base_transport_with_credentials_file(): + # Instantiate the base transport with a credentials file + with mock.patch.object( + auth, "load_credentials_from_file" + ) as load_creds, mock.patch( + "google.cloud.recaptchaenterprise_v1.services.recaptcha_enterprise_service.transports.RecaptchaEnterpriseServiceTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (credentials.AnonymousCredentials(), None) + transport = transports.RecaptchaEnterpriseServiceTransport( + credentials_file="credentials.json", quota_project_id="octopus", + ) + load_creds.assert_called_once_with( + "credentials.json", + scopes=("https://www.googleapis.com/auth/cloud-platform",), + quota_project_id="octopus", + ) + + +def test_recaptcha_enterprise_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.cloud.recaptchaenterprise_v1.services.recaptcha_enterprise_service.transports.RecaptchaEnterpriseServiceTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + adc.return_value = (credentials.AnonymousCredentials(), None) + transport = transports.RecaptchaEnterpriseServiceTransport() + adc.assert_called_once() + + def test_recaptcha_enterprise_service_auth_adc(): # If no credentials are provided, we should use ADC credentials. with mock.patch.object(auth, "default") as adc: adc.return_value = (credentials.AnonymousCredentials(), None) RecaptchaEnterpriseServiceClient() adc.assert_called_once_with( - scopes=("https://www.googleapis.com/auth/cloud-platform",) + scopes=("https://www.googleapis.com/auth/cloud-platform",), + quota_project_id=None, + ) + + +def test_recaptcha_enterprise_service_transport_auth_adc(): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(auth, "default") as adc: + adc.return_value = (credentials.AnonymousCredentials(), None) + transports.RecaptchaEnterpriseServiceGrpcTransport( + host="squid.clam.whelk", quota_project_id="octopus" + ) + adc.assert_called_once_with( + scopes=("https://www.googleapis.com/auth/cloud-platform",), + quota_project_id="octopus", ) @@ -648,9 +1941,8 @@ def test_recaptcha_enterprise_service_host_no_port(): client_options=client_options.ClientOptions( api_endpoint="recaptchaenterprise.googleapis.com" ), - transport="grpc", ) - assert client._transport._host == "recaptchaenterprise.googleapis.com:443" + assert client.transport._host == "recaptchaenterprise.googleapis.com:443" def test_recaptcha_enterprise_service_host_with_port(): @@ -659,94 +1951,128 @@ def test_recaptcha_enterprise_service_host_with_port(): client_options=client_options.ClientOptions( api_endpoint="recaptchaenterprise.googleapis.com:8000" ), - transport="grpc", ) - assert client._transport._host == "recaptchaenterprise.googleapis.com:8000" + assert client.transport._host == "recaptchaenterprise.googleapis.com:8000" def test_recaptcha_enterprise_service_grpc_transport_channel(): - channel = grpc.insecure_channel("http://localhost/") + channel = grpc.secure_channel("http://localhost/", grpc.local_channel_credentials()) - # 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.RecaptchaEnterpriseServiceGrpcTransport( - host="squid.clam.whelk", - channel=channel, - api_mtls_endpoint="mtls.squid.clam.whelk", - client_cert_source=callback, + host="squid.clam.whelk", channel=channel, ) assert transport.grpc_channel == channel assert transport._host == "squid.clam.whelk:443" - assert not callback.called + assert transport._ssl_channel_credentials == None -@mock.patch("grpc.ssl_channel_credentials", autospec=True) -@mock.patch("google.api_core.grpc_helpers.create_channel", autospec=True) -def test_recaptcha_enterprise_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 +def test_recaptcha_enterprise_service_grpc_asyncio_transport_channel(): + channel = aio.secure_channel("http://localhost/", grpc.local_channel_credentials()) - transport = transports.RecaptchaEnterpriseServiceGrpcTransport( - 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" + # Check that channel is used if provided. + transport = transports.RecaptchaEnterpriseServiceGrpcAsyncIOTransport( + host="squid.clam.whelk", channel=channel, ) - grpc_create_channel.assert_called_once_with( - "mtls.squid.clam.whelk:443", - credentials=mock_cred, - ssl_credentials=mock_ssl_cred, - scopes=("https://www.googleapis.com/auth/cloud-platform",), - ) - assert transport.grpc_channel == mock_grpc_channel + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert transport._ssl_channel_credentials == None @pytest.mark.parametrize( - "api_mtls_endpoint", ["mtls.squid.clam.whelk", "mtls.squid.clam.whelk:443"] + "transport_class", + [ + transports.RecaptchaEnterpriseServiceGrpcTransport, + transports.RecaptchaEnterpriseServiceGrpcAsyncIOTransport, + ], ) -@mock.patch("google.api_core.grpc_helpers.create_channel", autospec=True) -def test_recaptcha_enterprise_service_grpc_transport_channel_mtls_with_adc( - grpc_create_channel, api_mtls_endpoint +def test_recaptcha_enterprise_service_transport_channel_mtls_with_client_cert_source( + transport_class, ): - # 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 + with mock.patch( + "grpc.ssl_channel_credentials", autospec=True + ) as grpc_ssl_channel_cred: + with mock.patch.object( + transport_class, "create_channel" + ) as grpc_create_channel: + mock_ssl_cred = mock.Mock() + grpc_ssl_channel_cred.return_value = mock_ssl_cred + + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + + cred = credentials.AnonymousCredentials() + with pytest.warns(DeprecationWarning): + with mock.patch.object(auth, "default") as adc: + adc.return_value = (cred, None) + transport = transport_class( + host="squid.clam.whelk", + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=client_cert_source_callback, + ) + adc.assert_called_once() + + grpc_ssl_channel_cred.assert_called_once_with( + certificate_chain=b"cert bytes", private_key=b"key bytes" + ) + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=("https://www.googleapis.com/auth/cloud-platform",), + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + assert transport._ssl_channel_credentials == mock_ssl_cred + - # Mock google.auth.transport.grpc.SslCredentials class. +@pytest.mark.parametrize( + "transport_class", + [ + transports.RecaptchaEnterpriseServiceGrpcTransport, + transports.RecaptchaEnterpriseServiceGrpcAsyncIOTransport, + ], +) +def test_recaptcha_enterprise_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.RecaptchaEnterpriseServiceGrpcTransport( - 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, - ssl_credentials=mock_ssl_cred, - scopes=("https://www.googleapis.com/auth/cloud-platform",), - ) - assert transport.grpc_channel == mock_grpc_channel + with mock.patch.object( + transport_class, "create_channel" + ) as grpc_create_channel: + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + mock_cred = mock.Mock() + + with pytest.warns(DeprecationWarning): + transport = transport_class( + host="squid.clam.whelk", + credentials=mock_cred, + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=None, + ) + + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=mock_cred, + credentials_file=None, + scopes=("https://www.googleapis.com/auth/cloud-platform",), + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel def test_assessment_path(): @@ -754,14 +2080,17 @@ def test_assessment_path(): assessment = "clam" expected = "projects/{project}/assessments/{assessment}".format( - project=project, assessment=assessment + project=project, assessment=assessment, ) actual = RecaptchaEnterpriseServiceClient.assessment_path(project, assessment) assert expected == actual def test_parse_assessment_path(): - expected = {"project": "whelk", "assessment": "octopus"} + expected = { + "project": "whelk", + "assessment": "octopus", + } path = RecaptchaEnterpriseServiceClient.assessment_path(**expected) # Check that the path construction is reversible. @@ -770,18 +2099,145 @@ def test_parse_assessment_path(): def test_key_path(): - project = "squid" - key = "clam" + project = "oyster" + key = "nudibranch" - expected = "projects/{project}/keys/{key}".format(project=project, key=key) + expected = "projects/{project}/keys/{key}".format(project=project, key=key,) actual = RecaptchaEnterpriseServiceClient.key_path(project, key) assert expected == actual def test_parse_key_path(): - expected = {"project": "whelk", "key": "octopus"} + expected = { + "project": "cuttlefish", + "key": "mussel", + } path = RecaptchaEnterpriseServiceClient.key_path(**expected) # Check that the path construction is reversible. actual = RecaptchaEnterpriseServiceClient.parse_key_path(path) assert expected == actual + + +def test_common_billing_account_path(): + billing_account = "winkle" + + expected = "billingAccounts/{billing_account}".format( + billing_account=billing_account, + ) + actual = RecaptchaEnterpriseServiceClient.common_billing_account_path( + billing_account + ) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "nautilus", + } + path = RecaptchaEnterpriseServiceClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = RecaptchaEnterpriseServiceClient.parse_common_billing_account_path(path) + assert expected == actual + + +def test_common_folder_path(): + folder = "scallop" + + expected = "folders/{folder}".format(folder=folder,) + actual = RecaptchaEnterpriseServiceClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "abalone", + } + path = RecaptchaEnterpriseServiceClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = RecaptchaEnterpriseServiceClient.parse_common_folder_path(path) + assert expected == actual + + +def test_common_organization_path(): + organization = "squid" + + expected = "organizations/{organization}".format(organization=organization,) + actual = RecaptchaEnterpriseServiceClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "clam", + } + path = RecaptchaEnterpriseServiceClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = RecaptchaEnterpriseServiceClient.parse_common_organization_path(path) + assert expected == actual + + +def test_common_project_path(): + project = "whelk" + + expected = "projects/{project}".format(project=project,) + actual = RecaptchaEnterpriseServiceClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "octopus", + } + path = RecaptchaEnterpriseServiceClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = RecaptchaEnterpriseServiceClient.parse_common_project_path(path) + assert expected == actual + + +def test_common_location_path(): + project = "oyster" + location = "nudibranch" + + expected = "projects/{project}/locations/{location}".format( + project=project, location=location, + ) + actual = RecaptchaEnterpriseServiceClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "cuttlefish", + "location": "mussel", + } + path = RecaptchaEnterpriseServiceClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = RecaptchaEnterpriseServiceClient.parse_common_location_path(path) + assert expected == actual + + +def test_client_withDEFAULT_CLIENT_INFO(): + client_info = gapic_v1.client_info.ClientInfo() + + with mock.patch.object( + transports.RecaptchaEnterpriseServiceTransport, "_prep_wrapped_messages" + ) as prep: + client = RecaptchaEnterpriseServiceClient( + credentials=credentials.AnonymousCredentials(), client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object( + transports.RecaptchaEnterpriseServiceTransport, "_prep_wrapped_messages" + ) as prep: + transport_class = RecaptchaEnterpriseServiceClient.get_transport_class() + transport = transport_class( + credentials=credentials.AnonymousCredentials(), client_info=client_info, + ) + prep.assert_called_once_with(client_info)