From 69d2b347f9aab3f30a3b0265fc9dcd9a3926f62d Mon Sep 17 00:00:00 2001 From: "gcf-owl-bot[bot]" <78513119+gcf-owl-bot[bot]@users.noreply.github.com> Date: Thu, 7 Oct 2021 00:42:27 +0000 Subject: [PATCH] feat: add context manager support in client (#131) - [ ] Regenerate this pull request now. chore: fix docstring for first attribute of protos committer: @busunkim96 PiperOrigin-RevId: 401271153 Source-Link: https://github.com/googleapis/googleapis/commit/787f8c9a731f44e74a90b9847d48659ca9462d10 Source-Link: https://github.com/googleapis/googleapis-gen/commit/81decffe9fc72396a8153e756d1d67a6eecfd620 Copy-Tag: eyJwIjoiLmdpdGh1Yi8uT3dsQm90LnlhbWwiLCJoIjoiODFkZWNmZmU5ZmM3MjM5NmE4MTUzZTc1NmQxZDY3YTZlZWNmZDYyMCJ9 --- .../async_client.py | 6 +++ .../recaptcha_enterprise_service/client.py | 18 +++++-- .../transports/base.py | 9 ++++ .../transports/grpc.py | 3 ++ .../transports/grpc_asyncio.py | 3 ++ .../types/recaptchaenterprise.py | 25 +++++++++- .../test_recaptcha_enterprise_service.py | 50 +++++++++++++++++++ 7 files changed, 109 insertions(+), 5 deletions(-) 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 index 78ce360..4195fa7 100644 --- a/google/cloud/recaptchaenterprise_v1/services/recaptcha_enterprise_service/async_client.py +++ b/google/cloud/recaptchaenterprise_v1/services/recaptcha_enterprise_service/async_client.py @@ -716,6 +716,12 @@ async def get_metrics( # Done; return the response. return response + async def __aenter__(self): + return self + + async def __aexit__(self, exc_type, exc, tb): + await self.transport.close() + try: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( 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 50bb383..14d3ae3 100644 --- a/google/cloud/recaptchaenterprise_v1/services/recaptcha_enterprise_service/client.py +++ b/google/cloud/recaptchaenterprise_v1/services/recaptcha_enterprise_service/client.py @@ -370,10 +370,7 @@ def __init__( client_cert_source_for_mtls=client_cert_source_func, quota_project_id=client_options.quota_project_id, client_info=client_info, - always_use_jwt_access=( - Transport == type(self).get_transport_class("grpc") - or Transport == type(self).get_transport_class("grpc_asyncio") - ), + always_use_jwt_access=True, ) def create_assessment( @@ -919,6 +916,19 @@ def get_metrics( # Done; return the response. return response + def __enter__(self): + return self + + def __exit__(self, type, value, traceback): + """Releases underlying transport's resources. + + .. warning:: + ONLY use as a context manager if the transport is NOT shared + with other clients! Exiting the with block will CLOSE the transport + and may cause errors in other clients! + """ + self.transport.close() + try: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( 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 b9090a9..16269de 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 @@ -186,6 +186,15 @@ def _prep_wrapped_messages(self, client_info): ), } + def close(self): + """Closes resources associated with the transport. + + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! + """ + raise NotImplementedError() + @property def create_assessment( self, 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 39dcefc..65a5dda 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 @@ -478,5 +478,8 @@ def get_metrics( ) return self._stubs["get_metrics"] + def close(self): + self.grpc_channel.close() + __all__ = ("RecaptchaEnterpriseServiceGrpcTransport",) 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 index f7975ce..57ece55 100644 --- 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 @@ -495,5 +495,8 @@ def get_metrics( ) return self._stubs["get_metrics"] + def close(self): + return self.grpc_channel.close() + __all__ = ("RecaptchaEnterpriseServiceGrpcAsyncIOTransport",) diff --git a/google/cloud/recaptchaenterprise_v1/types/recaptchaenterprise.py b/google/cloud/recaptchaenterprise_v1/types/recaptchaenterprise.py index 1aa9908..3186f38 100644 --- a/google/cloud/recaptchaenterprise_v1/types/recaptchaenterprise.py +++ b/google/cloud/recaptchaenterprise_v1/types/recaptchaenterprise.py @@ -52,6 +52,7 @@ class CreateAssessmentRequest(proto.Message): r"""The create assessment request message. + Attributes: parent (str): Required. The name of the project in which @@ -67,6 +68,7 @@ class CreateAssessmentRequest(proto.Message): class AnnotateAssessmentRequest(proto.Message): r"""The request message to annotate an Assessment. + Attributes: name (str): Required. The resource name of the @@ -110,11 +112,13 @@ class Reason(proto.Enum): class AnnotateAssessmentResponse(proto.Message): - r"""Empty response for AnnotateAssessment. """ + r"""Empty response for AnnotateAssessment. + """ class Assessment(proto.Message): r"""A recaptcha assessment resource. + Attributes: name (str): Output only. The resource name for the @@ -138,6 +142,7 @@ class Assessment(proto.Message): class Event(proto.Message): r""" + Attributes: token (str): Optional. The user response token provided by @@ -171,6 +176,7 @@ class Event(proto.Message): class RiskAnalysis(proto.Message): r"""Risk analysis result for an event. + Attributes: score (float): Legitimate event score from 0.0 to 1.0. @@ -196,6 +202,7 @@ class ClassificationReason(proto.Enum): class TokenProperties(proto.Message): r""" + Attributes: valid (bool): Whether the provided user response token is valid. When @@ -236,6 +243,7 @@ class InvalidReason(proto.Enum): class CreateKeyRequest(proto.Message): r"""The create key request message. + Attributes: parent (str): Required. The name of the project in which @@ -252,6 +260,7 @@ class CreateKeyRequest(proto.Message): class ListKeysRequest(proto.Message): r"""The list keys request message. + Attributes: parent (str): Required. The name of the project that @@ -272,6 +281,7 @@ class ListKeysRequest(proto.Message): class ListKeysResponse(proto.Message): r"""Response to request to list keys in a project. + Attributes: keys (Sequence[google.cloud.recaptchaenterprise_v1.types.Key]): Key details. @@ -290,6 +300,7 @@ def raw_page(self): class GetKeyRequest(proto.Message): r"""The get key request message. + Attributes: name (str): Required. The name of the requested key, in @@ -301,6 +312,7 @@ class GetKeyRequest(proto.Message): class UpdateKeyRequest(proto.Message): r"""The update key request message. + Attributes: key (google.cloud.recaptchaenterprise_v1.types.Key): Required. The key to update. @@ -318,6 +330,7 @@ class UpdateKeyRequest(proto.Message): class DeleteKeyRequest(proto.Message): r"""The delete key request message. + Attributes: name (str): Required. The name of the key to be deleted, @@ -329,6 +342,7 @@ class DeleteKeyRequest(proto.Message): class MigrateKeyRequest(proto.Message): r"""The migrate key request message. + Attributes: name (str): Required. The name of the key to be migrated, @@ -340,6 +354,7 @@ class MigrateKeyRequest(proto.Message): class GetMetricsRequest(proto.Message): r"""The get metrics request message. + Attributes: name (str): Required. The name of the requested metrics, @@ -352,6 +367,7 @@ class GetMetricsRequest(proto.Message): class Metrics(proto.Message): r"""Metrics for a single Key. + Attributes: name (str): Output only. The name of the metrics, in the @@ -432,6 +448,7 @@ class Key(proto.Message): class TestingOptions(proto.Message): r"""Options for user acceptance testing. + Attributes: testing_score (float): All assessments for this Key will return this @@ -458,6 +475,7 @@ class TestingChallenge(proto.Enum): class WebKeySettings(proto.Message): r"""Settings specific to keys that can be used by websites. + Attributes: allow_all_domains (bool): If set to true, it means allowed_domains will not be @@ -510,6 +528,7 @@ class ChallengeSecurityPreference(proto.Enum): class AndroidKeySettings(proto.Message): r"""Settings specific to keys that can be used by Android apps. + Attributes: allow_all_package_names (bool): If set to true, it means allowed_package_names will not be @@ -525,6 +544,7 @@ class AndroidKeySettings(proto.Message): class IOSKeySettings(proto.Message): r"""Settings specific to keys that can be used by iOS apps. + Attributes: allow_all_bundle_ids (bool): If set to true, it means allowed_bundle_ids will not be @@ -541,6 +561,7 @@ class IOSKeySettings(proto.Message): class ScoreDistribution(proto.Message): r"""Score distribution. + Attributes: score_buckets (Sequence[google.cloud.recaptchaenterprise_v1.types.ScoreDistribution.ScoreBucketsEntry]): Map key is score value multiplied by 100. The scores are @@ -554,6 +575,7 @@ class ScoreDistribution(proto.Message): class ScoreMetrics(proto.Message): r"""Metrics related to scoring. + Attributes: overall_metrics (google.cloud.recaptchaenterprise_v1.types.ScoreDistribution): Aggregated score metrics for all traffic. @@ -572,6 +594,7 @@ class ScoreMetrics(proto.Message): class ChallengeMetrics(proto.Message): r"""Metrics related to challenges. + Attributes: pageload_count (int): Count of reCAPTCHA checkboxes or badges 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 9f1e810..779ef8c 100644 --- a/tests/unit/gapic/recaptchaenterprise_v1/test_recaptcha_enterprise_service.py +++ b/tests/unit/gapic/recaptchaenterprise_v1/test_recaptcha_enterprise_service.py @@ -29,6 +29,7 @@ from google.api_core import gapic_v1 from google.api_core import grpc_helpers from google.api_core import grpc_helpers_async +from google.api_core import path_template from google.auth import credentials as ga_credentials from google.auth.exceptions import MutualTLSChannelError from google.cloud.recaptchaenterprise_v1.services.recaptcha_enterprise_service import ( @@ -2324,6 +2325,9 @@ def test_recaptcha_enterprise_service_base_transport(): with pytest.raises(NotImplementedError): getattr(transport, method)(request=object()) + with pytest.raises(NotImplementedError): + transport.close() + @requires_google_auth_gte_1_25_0 def test_recaptcha_enterprise_service_base_transport_with_credentials_file(): @@ -2852,3 +2856,49 @@ def test_client_withDEFAULT_CLIENT_INFO(): credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) + + +@pytest.mark.asyncio +async def test_transport_close_async(): + client = RecaptchaEnterpriseServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc_asyncio", + ) + with mock.patch.object( + type(getattr(client.transport, "grpc_channel")), "close" + ) as close: + async with client: + close.assert_not_called() + close.assert_called_once() + + +def test_transport_close(): + transports = { + "grpc": "_grpc_channel", + } + + for transport, close_name in transports.items(): + client = RecaptchaEnterpriseServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport + ) + with mock.patch.object( + type(getattr(client.transport, close_name)), "close" + ) as close: + with client: + close.assert_not_called() + close.assert_called_once() + + +def test_client_ctx(): + transports = [ + "grpc", + ] + for transport in transports: + client = RecaptchaEnterpriseServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport + ) + # Test client calls underlying transport. + with mock.patch.object(type(client.transport), "close") as close: + close.assert_not_called() + with client: + pass + close.assert_called()