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

Commit

Permalink
feat: add context manager support in client (#196)
Browse files Browse the repository at this point in the history
- [ ] Regenerate this pull request now.

chore: fix docstring for first attribute of protos

committer: @busunkim96
PiperOrigin-RevId: 401271153

Source-Link: googleapis/googleapis@787f8c9

Source-Link: googleapis/googleapis-gen@81decff
Copy-Tag: eyJwIjoiLmdpdGh1Yi8uT3dsQm90LnlhbWwiLCJoIjoiODFkZWNmZmU5ZmM3MjM5NmE4MTUzZTc1NmQxZDY3YTZlZWNmZDYyMCJ9
  • Loading branch information
gcf-owl-bot[bot] committed Oct 7, 2021
1 parent a77f10f commit 3bbc7ea
Show file tree
Hide file tree
Showing 14 changed files with 178 additions and 8 deletions.
Expand Up @@ -333,6 +333,12 @@ async def synthesize_speech(
# 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
18 changes: 14 additions & 4 deletions google/cloud/texttospeech_v1/services/text_to_speech/client.py
Expand Up @@ -325,10 +325,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 list_voices(
Expand Down Expand Up @@ -490,6 +487,19 @@ def synthesize_speech(
# 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 list_voices(
self,
Expand Down
Expand Up @@ -280,5 +280,8 @@ def synthesize_speech(
)
return self._stubs["synthesize_speech"]

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


__all__ = ("TextToSpeechGrpcTransport",)
Expand Up @@ -286,5 +286,8 @@ def synthesize_speech(
)
return self._stubs["synthesize_speech"]

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


__all__ = ("TextToSpeechGrpcAsyncIOTransport",)
4 changes: 4 additions & 0 deletions google/cloud/texttospeech_v1/types/cloud_tts.py
Expand Up @@ -76,6 +76,7 @@ class ListVoicesRequest(proto.Message):

class ListVoicesResponse(proto.Message):
r"""The message returned to the client by the ``ListVoices`` method.
Attributes:
voices (Sequence[google.cloud.texttospeech_v1.types.Voice]):
The list of voices.
Expand All @@ -86,6 +87,7 @@ class ListVoicesResponse(proto.Message):

class Voice(proto.Message):
r"""Description of a voice supported by the TTS service.
Attributes:
language_codes (Sequence[str]):
The languages that this voice supports, expressed as
Expand Down Expand Up @@ -151,6 +153,7 @@ class SynthesisInput(proto.Message):

class VoiceSelectionParams(proto.Message):
r"""Description of which voice to use for a synthesis request.
Attributes:
language_code (str):
Required. The language (and potentially also the region) of
Expand Down Expand Up @@ -187,6 +190,7 @@ class VoiceSelectionParams(proto.Message):

class AudioConfig(proto.Message):
r"""Description of audio data to be synthesized.
Attributes:
audio_encoding (google.cloud.texttospeech_v1.types.AudioEncoding):
Required. The format of the audio byte
Expand Down
Expand Up @@ -314,6 +314,12 @@ async def synthesize_speech(
# 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 @@ -325,10 +325,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 list_voices(
Expand Down Expand Up @@ -491,6 +488,19 @@ def synthesize_speech(
# 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 @@ -162,6 +162,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 list_voices(
self,
Expand Down
Expand Up @@ -280,5 +280,8 @@ def synthesize_speech(
)
return self._stubs["synthesize_speech"]

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


__all__ = ("TextToSpeechGrpcTransport",)
Expand Up @@ -286,5 +286,8 @@ def synthesize_speech(
)
return self._stubs["synthesize_speech"]

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


__all__ = ("TextToSpeechGrpcAsyncIOTransport",)
4 changes: 4 additions & 0 deletions google/cloud/texttospeech_v1beta1/types/cloud_tts.py
Expand Up @@ -81,6 +81,7 @@ class ListVoicesRequest(proto.Message):

class ListVoicesResponse(proto.Message):
r"""The message returned to the client by the ``ListVoices`` method.
Attributes:
voices (Sequence[google.cloud.texttospeech_v1beta1.types.Voice]):
The list of voices.
Expand All @@ -91,6 +92,7 @@ class ListVoicesResponse(proto.Message):

class Voice(proto.Message):
r"""Description of a voice supported by the TTS service.
Attributes:
language_codes (Sequence[str]):
The languages that this voice supports, expressed as
Expand Down Expand Up @@ -169,6 +171,7 @@ class SynthesisInput(proto.Message):

class VoiceSelectionParams(proto.Message):
r"""Description of which voice to use for a synthesis request.
Attributes:
language_code (str):
Required. The language (and potentially also the region) of
Expand Down Expand Up @@ -205,6 +208,7 @@ class VoiceSelectionParams(proto.Message):

class AudioConfig(proto.Message):
r"""Description of audio data to be synthesized.
Attributes:
audio_encoding (google.cloud.texttospeech_v1beta1.types.AudioEncoding):
Required. The format of the audio byte
Expand Down
50 changes: 50 additions & 0 deletions tests/unit/gapic/texttospeech_v1/test_text_to_speech.py
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.texttospeech_v1.services.text_to_speech import TextToSpeechAsyncClient
Expand Down Expand Up @@ -916,6 +917,9 @@ def test_text_to_speech_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_text_to_speech_base_transport_with_credentials_file():
Expand Down Expand Up @@ -1363,3 +1367,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 = TextToSpeechAsyncClient(
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 = TextToSpeechClient(
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 = TextToSpeechClient(
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()
50 changes: 50 additions & 0 deletions tests/unit/gapic/texttospeech_v1beta1/test_text_to_speech.py
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.texttospeech_v1beta1.services.text_to_speech import (
Expand Down Expand Up @@ -918,6 +919,9 @@ def test_text_to_speech_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_text_to_speech_base_transport_with_credentials_file():
Expand Down Expand Up @@ -1365,3 +1369,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 = TextToSpeechAsyncClient(
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 = TextToSpeechClient(
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 = TextToSpeechClient(
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()

0 comments on commit 3bbc7ea

Please sign in to comment.