Skip to content
This repository was archived by the owner on Jul 6, 2023. It is now read-only.

Commit f90696e

Browse files
feat: add context manager support in client (#70)
- [ ] 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: https://github.com/googleapis/googleapis-gen/commit/81decffe9fc72396a8153e756d1d67a6eecfd620 Copy-Tag: eyJwIjoiLmdpdGh1Yi8uT3dsQm90LnlhbWwiLCJoIjoiODFkZWNmZmU5ZmM3MjM5NmE4MTUzZTc1NmQxZDY3YTZlZWNmZDYyMCJ9
1 parent de2daa2 commit f90696e

File tree

8 files changed

+108
-10
lines changed

8 files changed

+108
-10
lines changed

google/cloud/contact_center_insights_v1/services/contact_center_insights/async_client.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2322,6 +2322,12 @@ async def update_settings(
23222322
# Done; return the response.
23232323
return response
23242324

2325+
async def __aenter__(self):
2326+
return self
2327+
2328+
async def __aexit__(self, exc_type, exc, tb):
2329+
await self.transport.close()
2330+
23252331

23262332
try:
23272333
DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(

google/cloud/contact_center_insights_v1/services/contact_center_insights/client.py

Lines changed: 14 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -457,10 +457,7 @@ def __init__(
457457
client_cert_source_for_mtls=client_cert_source_func,
458458
quota_project_id=client_options.quota_project_id,
459459
client_info=client_info,
460-
always_use_jwt_access=(
461-
Transport == type(self).get_transport_class("grpc")
462-
or Transport == type(self).get_transport_class("grpc_asyncio")
463-
),
460+
always_use_jwt_access=True,
464461
)
465462

466463
def create_conversation(
@@ -2596,6 +2593,19 @@ def update_settings(
25962593
# Done; return the response.
25972594
return response
25982595

2596+
def __enter__(self):
2597+
return self
2598+
2599+
def __exit__(self, type, value, traceback):
2600+
"""Releases underlying transport's resources.
2601+
2602+
.. warning::
2603+
ONLY use as a context manager if the transport is NOT shared
2604+
with other clients! Exiting the with block will CLOSE the transport
2605+
and may cause errors in other clients!
2606+
"""
2607+
self.transport.close()
2608+
25992609

26002610
try:
26012611
DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(

google/cloud/contact_center_insights_v1/services/contact_center_insights/transports/base.py

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -256,6 +256,15 @@ def _prep_wrapped_messages(self, client_info):
256256
),
257257
}
258258

259+
def close(self):
260+
"""Closes resources associated with the transport.
261+
262+
.. warning::
263+
Only call this method if the transport is NOT shared
264+
with other clients - this may cause errors in other clients!
265+
"""
266+
raise NotImplementedError()
267+
259268
@property
260269
def operations_client(self) -> operations_v1.OperationsClient:
261270
"""Return the client designed to process long-running operations."""

google/cloud/contact_center_insights_v1/services/contact_center_insights/transports/grpc.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1026,5 +1026,8 @@ def update_settings(
10261026
)
10271027
return self._stubs["update_settings"]
10281028

1029+
def close(self):
1030+
self.grpc_channel.close()
1031+
10291032

10301033
__all__ = ("ContactCenterInsightsGrpcTransport",)

google/cloud/contact_center_insights_v1/services/contact_center_insights/transports/grpc_asyncio.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1059,5 +1059,8 @@ def update_settings(
10591059
)
10601060
return self._stubs["update_settings"]
10611061

1062+
def close(self):
1063+
return self.grpc_channel.close()
1064+
10621065

10631066
__all__ = ("ContactCenterInsightsGrpcAsyncIOTransport",)

google/cloud/contact_center_insights_v1/types/contact_center_insights.py

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -132,6 +132,7 @@ class CalculateStatsResponse(proto.Message):
132132

133133
class TimeSeries(proto.Message):
134134
r"""A time series representing conversations over time.
135+
135136
Attributes:
136137
interval_duration (google.protobuf.duration_pb2.Duration):
137138
The duration of each interval.
@@ -144,6 +145,7 @@ class TimeSeries(proto.Message):
144145

145146
class Interval(proto.Message):
146147
r"""A single interval in a time series.
148+
147149
Attributes:
148150
start_time (google.protobuf.timestamp_pb2.Timestamp):
149151
The start time of this interval.
@@ -441,6 +443,7 @@ class ExportInsightsDataRequest(proto.Message):
441443

442444
class BigQueryDestination(proto.Message):
443445
r"""A BigQuery Table Reference.
446+
444447
Attributes:
445448
project_id (str):
446449
A project ID or number. If specified, then
@@ -496,7 +499,8 @@ class ExportInsightsDataMetadata(proto.Message):
496499

497500

498501
class ExportInsightsDataResponse(proto.Message):
499-
r"""Response for an export insights operation. """
502+
r"""Response for an export insights operation.
503+
"""
500504

501505

502506
class CreateIssueModelRequest(proto.Message):
@@ -628,7 +632,8 @@ class DeployIssueModelRequest(proto.Message):
628632

629633

630634
class DeployIssueModelResponse(proto.Message):
631-
r"""The response to deploy an issue model. """
635+
r"""The response to deploy an issue model.
636+
"""
632637

633638

634639
class DeployIssueModelMetadata(proto.Message):
@@ -662,7 +667,8 @@ class UndeployIssueModelRequest(proto.Message):
662667

663668

664669
class UndeployIssueModelResponse(proto.Message):
665-
r"""The response to undeploy an issue model. """
670+
r"""The response to undeploy an issue model.
671+
"""
666672

667673

668674
class UndeployIssueModelMetadata(proto.Message):

google/cloud/contact_center_insights_v1/types/resources.py

Lines changed: 14 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -137,6 +137,7 @@ class Medium(proto.Enum):
137137

138138
class CallMetadata(proto.Message):
139139
r"""Call-specific metadata.
140+
140141
Attributes:
141142
customer_channel (int):
142143
The audio channel that contains the customer.
@@ -149,6 +150,7 @@ class CallMetadata(proto.Message):
149150

150151
class Transcript(proto.Message):
151152
r"""A message representing the transcript of a conversation.
153+
152154
Attributes:
153155
transcript_segments (Sequence[google.cloud.contact_center_insights_v1.types.Conversation.Transcript.TranscriptSegment]):
154156
A list of sequential transcript segments that
@@ -157,6 +159,7 @@ class Transcript(proto.Message):
157159

158160
class TranscriptSegment(proto.Message):
159161
r"""A segment of a full transcript.
162+
160163
Attributes:
161164
message_time (google.protobuf.timestamp_pb2.Timestamp):
162165
The time that the message occurred, if
@@ -192,6 +195,7 @@ class TranscriptSegment(proto.Message):
192195

193196
class WordInfo(proto.Message):
194197
r"""Word-level info for words in a transcript.
198+
195199
Attributes:
196200
start_offset (google.protobuf.duration_pb2.Duration):
197201
Time offset of the start of this word
@@ -387,6 +391,7 @@ class AnalysisResult(proto.Message):
387391

388392
class CallAnalysisMetadata(proto.Message):
389393
r"""Call-specific metadata created during analysis.
394+
390395
Attributes:
391396
annotations (Sequence[google.cloud.contact_center_insights_v1.types.CallAnnotation]):
392397
A list of call annotations that apply to this
@@ -659,15 +664,18 @@ class DialogflowIntent(proto.Message):
659664

660665

661666
class InterruptionData(proto.Message):
662-
r"""The data for an interruption annotation. """
667+
r"""The data for an interruption annotation.
668+
"""
663669

664670

665671
class SilenceData(proto.Message):
666-
r"""The data for a silence annotation. """
672+
r"""The data for a silence annotation.
673+
"""
667674

668675

669676
class HoldData(proto.Message):
670-
r"""The data for a hold annotation. """
677+
r"""The data for a hold annotation.
678+
"""
671679

672680

673681
class EntityMentionData(proto.Message):
@@ -766,6 +774,7 @@ class State(proto.Enum):
766774

767775
class InputDataConfig(proto.Message):
768776
r"""Configs for the input data used to create the issue model.
777+
769778
Attributes:
770779
medium (google.cloud.contact_center_insights_v1.types.Conversation.Medium):
771780
Medium of conversations used in training data. This field is
@@ -835,6 +844,7 @@ class IssueModelLabelStats(proto.Message):
835844

836845
class IssueStats(proto.Message):
837846
r"""Aggregated statistics about an issue.
847+
838848
Attributes:
839849
issue (str):
840850
Issue resource. Format:
@@ -1055,6 +1065,7 @@ class Settings(proto.Message):
10551065

10561066
class AnalysisConfig(proto.Message):
10571067
r"""Default configuration when creating Analyses in Insights.
1068+
10581069
Attributes:
10591070
runtime_integration_analysis_percentage (float):
10601071
Percentage of conversations created using Dialogflow runtime

tests/unit/gapic/contact_center_insights_v1/test_contact_center_insights.py

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,7 @@
3232
from google.api_core import grpc_helpers_async
3333
from google.api_core import operation_async # type: ignore
3434
from google.api_core import operations_v1
35+
from google.api_core import path_template
3536
from google.auth import credentials as ga_credentials
3637
from google.auth.exceptions import MutualTLSChannelError
3738
from google.cloud.contact_center_insights_v1.services.contact_center_insights import (
@@ -7496,6 +7497,9 @@ def test_contact_center_insights_base_transport():
74967497
with pytest.raises(NotImplementedError):
74977498
getattr(transport, method)(request=object())
74987499

7500+
with pytest.raises(NotImplementedError):
7501+
transport.close()
7502+
74997503
# Additionally, the LRO client (a property) should
75007504
# also raise NotImplementedError
75017505
with pytest.raises(NotImplementedError):
@@ -8174,3 +8178,49 @@ def test_client_withDEFAULT_CLIENT_INFO():
81748178
credentials=ga_credentials.AnonymousCredentials(), client_info=client_info,
81758179
)
81768180
prep.assert_called_once_with(client_info)
8181+
8182+
8183+
@pytest.mark.asyncio
8184+
async def test_transport_close_async():
8185+
client = ContactCenterInsightsAsyncClient(
8186+
credentials=ga_credentials.AnonymousCredentials(), transport="grpc_asyncio",
8187+
)
8188+
with mock.patch.object(
8189+
type(getattr(client.transport, "grpc_channel")), "close"
8190+
) as close:
8191+
async with client:
8192+
close.assert_not_called()
8193+
close.assert_called_once()
8194+
8195+
8196+
def test_transport_close():
8197+
transports = {
8198+
"grpc": "_grpc_channel",
8199+
}
8200+
8201+
for transport, close_name in transports.items():
8202+
client = ContactCenterInsightsClient(
8203+
credentials=ga_credentials.AnonymousCredentials(), transport=transport
8204+
)
8205+
with mock.patch.object(
8206+
type(getattr(client.transport, close_name)), "close"
8207+
) as close:
8208+
with client:
8209+
close.assert_not_called()
8210+
close.assert_called_once()
8211+
8212+
8213+
def test_client_ctx():
8214+
transports = [
8215+
"grpc",
8216+
]
8217+
for transport in transports:
8218+
client = ContactCenterInsightsClient(
8219+
credentials=ga_credentials.AnonymousCredentials(), transport=transport
8220+
)
8221+
# Test client calls underlying transport.
8222+
with mock.patch.object(type(client.transport), "close") as close:
8223+
close.assert_not_called()
8224+
with client:
8225+
pass
8226+
close.assert_called()

0 commit comments

Comments
 (0)