From a5e200515c621695c8c8ed76f739e0b744f32382 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:34:12 +0000 Subject: [PATCH] feat: add context manager support in client (#268) - [ ] 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 --- .../speech_v1/services/speech/async_client.py | 6 +++ .../cloud/speech_v1/services/speech/client.py | 18 +++++-- .../services/speech/transports/base.py | 9 ++++ .../services/speech/transports/grpc.py | 3 ++ .../speech/transports/grpc_asyncio.py | 3 ++ google/cloud/speech_v1/types/cloud_speech.py | 4 ++ .../services/adaptation/async_client.py | 6 +++ .../services/adaptation/client.py | 18 +++++-- .../services/adaptation/transports/base.py | 9 ++++ .../services/adaptation/transports/grpc.py | 3 ++ .../adaptation/transports/grpc_asyncio.py | 3 ++ .../services/speech/async_client.py | 6 +++ .../services/speech/client.py | 18 +++++-- .../services/speech/transports/base.py | 9 ++++ .../services/speech/transports/grpc.py | 3 ++ .../speech/transports/grpc_asyncio.py | 3 ++ .../speech_v1p1beta1/types/cloud_speech.py | 4 ++ .../types/cloud_speech_adaptation.py | 12 +++++ .../cloud/speech_v1p1beta1/types/resource.py | 3 ++ tests/unit/gapic/speech_v1/test_speech.py | 50 +++++++++++++++++++ .../gapic/speech_v1p1beta1/test_adaptation.py | 50 +++++++++++++++++++ .../gapic/speech_v1p1beta1/test_speech.py | 50 +++++++++++++++++++ 22 files changed, 278 insertions(+), 12 deletions(-) diff --git a/google/cloud/speech_v1/services/speech/async_client.py b/google/cloud/speech_v1/services/speech/async_client.py index 83f54612..b4019fcb 100644 --- a/google/cloud/speech_v1/services/speech/async_client.py +++ b/google/cloud/speech_v1/services/speech/async_client.py @@ -460,6 +460,12 @@ def streaming_recognize( # 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/speech_v1/services/speech/client.py b/google/cloud/speech_v1/services/speech/client.py index 5649465b..fbc6ecc1 100644 --- a/google/cloud/speech_v1/services/speech/client.py +++ b/google/cloud/speech_v1/services/speech/client.py @@ -329,10 +329,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 recognize( @@ -610,6 +607,19 @@ def streaming_recognize( # 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/speech_v1/services/speech/transports/base.py b/google/cloud/speech_v1/services/speech/transports/base.py index 9d7d46db..aeb6f3fb 100644 --- a/google/cloud/speech_v1/services/speech/transports/base.py +++ b/google/cloud/speech_v1/services/speech/transports/base.py @@ -191,6 +191,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 operations_client(self) -> operations_v1.OperationsClient: """Return the client designed to process long-running operations.""" diff --git a/google/cloud/speech_v1/services/speech/transports/grpc.py b/google/cloud/speech_v1/services/speech/transports/grpc.py index 253545e4..eaa1445b 100644 --- a/google/cloud/speech_v1/services/speech/transports/grpc.py +++ b/google/cloud/speech_v1/services/speech/transports/grpc.py @@ -331,5 +331,8 @@ def streaming_recognize( ) return self._stubs["streaming_recognize"] + def close(self): + self.grpc_channel.close() + __all__ = ("SpeechGrpcTransport",) diff --git a/google/cloud/speech_v1/services/speech/transports/grpc_asyncio.py b/google/cloud/speech_v1/services/speech/transports/grpc_asyncio.py index caf98f57..45bba730 100644 --- a/google/cloud/speech_v1/services/speech/transports/grpc_asyncio.py +++ b/google/cloud/speech_v1/services/speech/transports/grpc_asyncio.py @@ -340,5 +340,8 @@ def streaming_recognize( ) return self._stubs["streaming_recognize"] + def close(self): + return self.grpc_channel.close() + __all__ = ("SpeechGrpcAsyncIOTransport",) diff --git a/google/cloud/speech_v1/types/cloud_speech.py b/google/cloud/speech_v1/types/cloud_speech.py index 2fae477b..ec214822 100644 --- a/google/cloud/speech_v1/types/cloud_speech.py +++ b/google/cloud/speech_v1/types/cloud_speech.py @@ -381,6 +381,7 @@ class AudioEncoding(proto.Enum): class SpeakerDiarizationConfig(proto.Message): r"""Config to enable speaker diarization. + Attributes: enable_speaker_diarization (bool): If 'true', enables speaker detection for each recognized @@ -410,6 +411,7 @@ class SpeakerDiarizationConfig(proto.Message): class RecognitionMetadata(proto.Message): r"""Description of audio data to be recognized. + Attributes: interaction_type (google.cloud.speech_v1.types.RecognitionMetadata.InteractionType): The use case most closely describing the @@ -793,6 +795,7 @@ class SpeechRecognitionResult(proto.Message): class SpeechRecognitionAlternative(proto.Message): r"""Alternative hypotheses (a.k.a. n-best list). + Attributes: transcript (str): Transcript text representing the words that @@ -819,6 +822,7 @@ class SpeechRecognitionAlternative(proto.Message): class WordInfo(proto.Message): r"""Word-specific information for recognized words. + Attributes: start_time (google.protobuf.duration_pb2.Duration): Time offset relative to the beginning of the audio, and diff --git a/google/cloud/speech_v1p1beta1/services/adaptation/async_client.py b/google/cloud/speech_v1p1beta1/services/adaptation/async_client.py index 1a1f60c4..d06d900b 100644 --- a/google/cloud/speech_v1p1beta1/services/adaptation/async_client.py +++ b/google/cloud/speech_v1p1beta1/services/adaptation/async_client.py @@ -971,6 +971,12 @@ async def delete_custom_class( request, retry=retry, timeout=timeout, metadata=metadata, ) + 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/speech_v1p1beta1/services/adaptation/client.py b/google/cloud/speech_v1p1beta1/services/adaptation/client.py index 42c458e4..931f086b 100644 --- a/google/cloud/speech_v1p1beta1/services/adaptation/client.py +++ b/google/cloud/speech_v1p1beta1/services/adaptation/client.py @@ -360,10 +360,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_phrase_set( @@ -1178,6 +1175,19 @@ def delete_custom_class( request, retry=retry, timeout=timeout, metadata=metadata, ) + 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/speech_v1p1beta1/services/adaptation/transports/base.py b/google/cloud/speech_v1p1beta1/services/adaptation/transports/base.py index b26561bf..0a624e1f 100644 --- a/google/cloud/speech_v1p1beta1/services/adaptation/transports/base.py +++ b/google/cloud/speech_v1p1beta1/services/adaptation/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_phrase_set( self, diff --git a/google/cloud/speech_v1p1beta1/services/adaptation/transports/grpc.py b/google/cloud/speech_v1p1beta1/services/adaptation/transports/grpc.py index 9b82e03a..0c2535f2 100644 --- a/google/cloud/speech_v1p1beta1/services/adaptation/transports/grpc.py +++ b/google/cloud/speech_v1p1beta1/services/adaptation/transports/grpc.py @@ -502,5 +502,8 @@ def delete_custom_class( ) return self._stubs["delete_custom_class"] + def close(self): + self.grpc_channel.close() + __all__ = ("AdaptationGrpcTransport",) diff --git a/google/cloud/speech_v1p1beta1/services/adaptation/transports/grpc_asyncio.py b/google/cloud/speech_v1p1beta1/services/adaptation/transports/grpc_asyncio.py index d09886bc..99e2e4df 100644 --- a/google/cloud/speech_v1p1beta1/services/adaptation/transports/grpc_asyncio.py +++ b/google/cloud/speech_v1p1beta1/services/adaptation/transports/grpc_asyncio.py @@ -517,5 +517,8 @@ def delete_custom_class( ) return self._stubs["delete_custom_class"] + def close(self): + return self.grpc_channel.close() + __all__ = ("AdaptationGrpcAsyncIOTransport",) diff --git a/google/cloud/speech_v1p1beta1/services/speech/async_client.py b/google/cloud/speech_v1p1beta1/services/speech/async_client.py index 2ee05a77..bf15aaf8 100644 --- a/google/cloud/speech_v1p1beta1/services/speech/async_client.py +++ b/google/cloud/speech_v1p1beta1/services/speech/async_client.py @@ -464,6 +464,12 @@ def streaming_recognize( # 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/speech_v1p1beta1/services/speech/client.py b/google/cloud/speech_v1p1beta1/services/speech/client.py index 4e478223..91c017c7 100644 --- a/google/cloud/speech_v1p1beta1/services/speech/client.py +++ b/google/cloud/speech_v1p1beta1/services/speech/client.py @@ -361,10 +361,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 recognize( @@ -642,6 +639,19 @@ def streaming_recognize( # 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/speech_v1p1beta1/services/speech/transports/base.py b/google/cloud/speech_v1p1beta1/services/speech/transports/base.py index f5c65061..640df196 100644 --- a/google/cloud/speech_v1p1beta1/services/speech/transports/base.py +++ b/google/cloud/speech_v1p1beta1/services/speech/transports/base.py @@ -191,6 +191,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 operations_client(self) -> operations_v1.OperationsClient: """Return the client designed to process long-running operations.""" diff --git a/google/cloud/speech_v1p1beta1/services/speech/transports/grpc.py b/google/cloud/speech_v1p1beta1/services/speech/transports/grpc.py index af059284..b8c4d603 100644 --- a/google/cloud/speech_v1p1beta1/services/speech/transports/grpc.py +++ b/google/cloud/speech_v1p1beta1/services/speech/transports/grpc.py @@ -331,5 +331,8 @@ def streaming_recognize( ) return self._stubs["streaming_recognize"] + def close(self): + self.grpc_channel.close() + __all__ = ("SpeechGrpcTransport",) diff --git a/google/cloud/speech_v1p1beta1/services/speech/transports/grpc_asyncio.py b/google/cloud/speech_v1p1beta1/services/speech/transports/grpc_asyncio.py index 7083ae0b..cae9aeff 100644 --- a/google/cloud/speech_v1p1beta1/services/speech/transports/grpc_asyncio.py +++ b/google/cloud/speech_v1p1beta1/services/speech/transports/grpc_asyncio.py @@ -340,5 +340,8 @@ def streaming_recognize( ) return self._stubs["streaming_recognize"] + def close(self): + return self.grpc_channel.close() + __all__ = ("SpeechGrpcAsyncIOTransport",) diff --git a/google/cloud/speech_v1p1beta1/types/cloud_speech.py b/google/cloud/speech_v1p1beta1/types/cloud_speech.py index 9dd978f0..f037137a 100644 --- a/google/cloud/speech_v1p1beta1/types/cloud_speech.py +++ b/google/cloud/speech_v1p1beta1/types/cloud_speech.py @@ -461,6 +461,7 @@ class AudioEncoding(proto.Enum): class SpeakerDiarizationConfig(proto.Message): r"""Config to enable speaker diarization. + Attributes: enable_speaker_diarization (bool): If 'true', enables speaker detection for each recognized @@ -490,6 +491,7 @@ class SpeakerDiarizationConfig(proto.Message): class RecognitionMetadata(proto.Message): r"""Description of audio data to be recognized. + Attributes: interaction_type (google.cloud.speech_v1p1beta1.types.RecognitionMetadata.InteractionType): The use case most closely describing the @@ -914,6 +916,7 @@ class SpeechRecognitionResult(proto.Message): class SpeechRecognitionAlternative(proto.Message): r"""Alternative hypotheses (a.k.a. n-best list). + Attributes: transcript (str): Transcript text representing the words that @@ -940,6 +943,7 @@ class SpeechRecognitionAlternative(proto.Message): class WordInfo(proto.Message): r"""Word-specific information for recognized words. + Attributes: start_time (google.protobuf.duration_pb2.Duration): Time offset relative to the beginning of the audio, and diff --git a/google/cloud/speech_v1p1beta1/types/cloud_speech_adaptation.py b/google/cloud/speech_v1p1beta1/types/cloud_speech_adaptation.py index 578fc0bb..7e8b0457 100644 --- a/google/cloud/speech_v1p1beta1/types/cloud_speech_adaptation.py +++ b/google/cloud/speech_v1p1beta1/types/cloud_speech_adaptation.py @@ -40,6 +40,7 @@ class CreatePhraseSetRequest(proto.Message): r"""Message sent by the client for the ``CreatePhraseSet`` method. + Attributes: parent (str): Required. The parent resource where this phrase set will be @@ -63,6 +64,7 @@ class CreatePhraseSetRequest(proto.Message): class UpdatePhraseSetRequest(proto.Message): r"""Message sent by the client for the ``UpdatePhraseSet`` method. + Attributes: phrase_set (google.cloud.speech_v1p1beta1.types.PhraseSet): Required. The phrase set to update. @@ -82,6 +84,7 @@ class UpdatePhraseSetRequest(proto.Message): class GetPhraseSetRequest(proto.Message): r"""Message sent by the client for the ``GetPhraseSet`` method. + Attributes: name (str): Required. The name of the phrase set to retrieve. Format: @@ -93,6 +96,7 @@ class GetPhraseSetRequest(proto.Message): class ListPhraseSetRequest(proto.Message): r"""Message sent by the client for the ``ListPhraseSet`` method. + Attributes: parent (str): Required. The parent, which owns this @@ -120,6 +124,7 @@ class ListPhraseSetRequest(proto.Message): class ListPhraseSetResponse(proto.Message): r"""Message returned to the client by the ``ListPhraseSet`` method. + Attributes: phrase_sets (Sequence[google.cloud.speech_v1p1beta1.types.PhraseSet]): The phrase set. @@ -141,6 +146,7 @@ def raw_page(self): class DeletePhraseSetRequest(proto.Message): r"""Message sent by the client for the ``DeletePhraseSet`` method. + Attributes: name (str): Required. The name of the phrase set to delete. Format: @@ -152,6 +158,7 @@ class DeletePhraseSetRequest(proto.Message): class CreateCustomClassRequest(proto.Message): r"""Message sent by the client for the ``CreateCustomClass`` method. + Attributes: parent (str): Required. The parent resource where this custom class will @@ -175,6 +182,7 @@ class CreateCustomClassRequest(proto.Message): class UpdateCustomClassRequest(proto.Message): r"""Message sent by the client for the ``UpdateCustomClass`` method. + Attributes: custom_class (google.cloud.speech_v1p1beta1.types.CustomClass): Required. The custom class to update. @@ -194,6 +202,7 @@ class UpdateCustomClassRequest(proto.Message): class GetCustomClassRequest(proto.Message): r"""Message sent by the client for the ``GetCustomClass`` method. + Attributes: name (str): Required. The name of the custom class to retrieve. Format: @@ -205,6 +214,7 @@ class GetCustomClassRequest(proto.Message): class ListCustomClassesRequest(proto.Message): r"""Message sent by the client for the ``ListCustomClasses`` method. + Attributes: parent (str): Required. The parent, which owns this collection of custom @@ -232,6 +242,7 @@ class ListCustomClassesRequest(proto.Message): class ListCustomClassesResponse(proto.Message): r"""Message returned to the client by the ``ListCustomClasses`` method. + Attributes: custom_classes (Sequence[google.cloud.speech_v1p1beta1.types.CustomClass]): The custom classes. @@ -253,6 +264,7 @@ def raw_page(self): class DeleteCustomClassRequest(proto.Message): r"""Message sent by the client for the ``DeleteCustomClass`` method. + Attributes: name (str): Required. The name of the custom class to delete. Format: diff --git a/google/cloud/speech_v1p1beta1/types/resource.py b/google/cloud/speech_v1p1beta1/types/resource.py index 822a4210..31b09326 100644 --- a/google/cloud/speech_v1p1beta1/types/resource.py +++ b/google/cloud/speech_v1p1beta1/types/resource.py @@ -45,6 +45,7 @@ class CustomClass(proto.Message): class ClassItem(proto.Message): r"""An item of the class. + Attributes: value (str): The class item's value. @@ -132,6 +133,7 @@ class Phrase(proto.Message): class SpeechAdaptation(proto.Message): r"""Speech adaptation configuration. + Attributes: phrase_sets (Sequence[google.cloud.speech_v1p1beta1.types.PhraseSet]): A collection of phrase sets. To specify the hints inline, @@ -173,6 +175,7 @@ class TranscriptNormalization(proto.Message): class Entry(proto.Message): r"""A single replacement configuration. + Attributes: search (str): What to replace. Max length is 100 diff --git a/tests/unit/gapic/speech_v1/test_speech.py b/tests/unit/gapic/speech_v1/test_speech.py index 23e6806d..595962f2 100644 --- a/tests/unit/gapic/speech_v1/test_speech.py +++ b/tests/unit/gapic/speech_v1/test_speech.py @@ -32,6 +32,7 @@ from google.api_core import grpc_helpers_async from google.api_core import operation_async # type: ignore from google.api_core import operations_v1 +from google.api_core import path_template from google.auth import credentials as ga_credentials from google.auth.exceptions import MutualTLSChannelError from google.cloud.speech_v1.services.speech import SpeechAsyncClient @@ -979,6 +980,9 @@ def test_speech_base_transport(): with pytest.raises(NotImplementedError): getattr(transport, method)(request=object()) + with pytest.raises(NotImplementedError): + transport.close() + # Additionally, the LRO client (a property) should # also raise NotImplementedError with pytest.raises(NotImplementedError): @@ -1451,3 +1455,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 = SpeechAsyncClient( + 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 = SpeechClient( + 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 = SpeechClient( + 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() diff --git a/tests/unit/gapic/speech_v1p1beta1/test_adaptation.py b/tests/unit/gapic/speech_v1p1beta1/test_adaptation.py index f42b9e3a..c31dd38f 100644 --- a/tests/unit/gapic/speech_v1p1beta1/test_adaptation.py +++ b/tests/unit/gapic/speech_v1p1beta1/test_adaptation.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.speech_v1p1beta1.services.adaptation import AdaptationAsyncClient @@ -3038,6 +3039,9 @@ def test_adaptation_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_adaptation_base_transport_with_credentials_file(): @@ -3527,3 +3531,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 = AdaptationAsyncClient( + 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 = AdaptationClient( + 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 = AdaptationClient( + 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() diff --git a/tests/unit/gapic/speech_v1p1beta1/test_speech.py b/tests/unit/gapic/speech_v1p1beta1/test_speech.py index 37de474f..6e205910 100644 --- a/tests/unit/gapic/speech_v1p1beta1/test_speech.py +++ b/tests/unit/gapic/speech_v1p1beta1/test_speech.py @@ -32,6 +32,7 @@ from google.api_core import grpc_helpers_async from google.api_core import operation_async # type: ignore from google.api_core import operations_v1 +from google.api_core import path_template from google.auth import credentials as ga_credentials from google.auth.exceptions import MutualTLSChannelError from google.cloud.speech_v1p1beta1.services.speech import SpeechAsyncClient @@ -983,6 +984,9 @@ def test_speech_base_transport(): with pytest.raises(NotImplementedError): getattr(transport, method)(request=object()) + with pytest.raises(NotImplementedError): + transport.close() + # Additionally, the LRO client (a property) should # also raise NotImplementedError with pytest.raises(NotImplementedError): @@ -1503,3 +1507,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 = SpeechAsyncClient( + 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 = SpeechClient( + 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 = SpeechClient( + 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()