Skip to content
This repository has been archived by the owner on Sep 5, 2023. It is now read-only.

feat: add context manager support in client #131

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
Expand Up @@ -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(
Expand Down
Expand Up @@ -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(
Expand Down Expand Up @@ -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(
Expand Down
Expand Up @@ -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,
Expand Down
Expand Up @@ -478,5 +478,8 @@ def get_metrics(
)
return self._stubs["get_metrics"]

def close(self):
self.grpc_channel.close()


__all__ = ("RecaptchaEnterpriseServiceGrpcTransport",)
Expand Up @@ -495,5 +495,8 @@ def get_metrics(
)
return self._stubs["get_metrics"]

def close(self):
return self.grpc_channel.close()


__all__ = ("RecaptchaEnterpriseServiceGrpcAsyncIOTransport",)
25 changes: 24 additions & 1 deletion google/cloud/recaptchaenterprise_v1/types/recaptchaenterprise.py
Expand Up @@ -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
Expand All @@ -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
Expand Down Expand Up @@ -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
Expand All @@ -138,6 +142,7 @@ class Assessment(proto.Message):

class Event(proto.Message):
r"""

Attributes:
token (str):
Optional. The user response token provided by
Expand Down Expand Up @@ -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.
Expand All @@ -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
Expand Down Expand Up @@ -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
Expand All @@ -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
Expand All @@ -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.
Expand All @@ -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
Expand All @@ -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.
Expand All @@ -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,
Expand All @@ -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,
Expand All @@ -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,
Expand All @@ -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
Expand Down Expand Up @@ -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
Expand All @@ -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
Expand Down Expand Up @@ -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
Expand All @@ -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
Expand All @@ -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
Expand All @@ -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.
Expand All @@ -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
Expand Down
Expand Up @@ -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 (
Expand Down Expand Up @@ -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():
Expand Down Expand Up @@ -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()