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

Commit cba3dad

Browse files
feat: add context manager support in client (#234)
- [ ] 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 4f43bf9 commit cba3dad

File tree

8 files changed

+99
-4
lines changed

8 files changed

+99
-4
lines changed

google/cloud/bigquery_datatransfer_v1/services/data_transfer_service/async_client.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1403,6 +1403,12 @@ async def check_valid_creds(
14031403
# Done; return the response.
14041404
return response
14051405

1406+
async def __aenter__(self):
1407+
return self
1408+
1409+
async def __aexit__(self, exc_type, exc, tb):
1410+
await self.transport.close()
1411+
14061412

14071413
try:
14081414
DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(

google/cloud/bigquery_datatransfer_v1/services/data_transfer_service/client.py

Lines changed: 14 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -388,10 +388,7 @@ def __init__(
388388
client_cert_source_for_mtls=client_cert_source_func,
389389
quota_project_id=client_options.quota_project_id,
390390
client_info=client_info,
391-
always_use_jwt_access=(
392-
Transport == type(self).get_transport_class("grpc")
393-
or Transport == type(self).get_transport_class("grpc_asyncio")
394-
),
391+
always_use_jwt_access=True,
395392
)
396393

397394
def get_data_source(
@@ -1519,6 +1516,19 @@ def check_valid_creds(
15191516
# Done; return the response.
15201517
return response
15211518

1519+
def __enter__(self):
1520+
return self
1521+
1522+
def __exit__(self, type, value, traceback):
1523+
"""Releases underlying transport's resources.
1524+
1525+
.. warning::
1526+
ONLY use as a context manager if the transport is NOT shared
1527+
with other clients! Exiting the with block will CLOSE the transport
1528+
and may cause errors in other clients!
1529+
"""
1530+
self.transport.close()
1531+
15221532

15231533
try:
15241534
DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(

google/cloud/bigquery_datatransfer_v1/services/data_transfer_service/transports/base.py

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -328,6 +328,15 @@ def _prep_wrapped_messages(self, client_info):
328328
),
329329
}
330330

331+
def close(self):
332+
"""Closes resources associated with the transport.
333+
334+
.. warning::
335+
Only call this method if the transport is NOT shared
336+
with other clients - this may cause errors in other clients!
337+
"""
338+
raise NotImplementedError()
339+
331340
@property
332341
def get_data_source(
333342
self,

google/cloud/bigquery_datatransfer_v1/services/data_transfer_service/transports/grpc.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -631,5 +631,8 @@ def check_valid_creds(
631631
)
632632
return self._stubs["check_valid_creds"]
633633

634+
def close(self):
635+
self.grpc_channel.close()
636+
634637

635638
__all__ = ("DataTransferServiceGrpcTransport",)

google/cloud/bigquery_datatransfer_v1/services/data_transfer_service/transports/grpc_asyncio.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -650,5 +650,8 @@ def check_valid_creds(
650650
)
651651
return self._stubs["check_valid_creds"]
652652

653+
def close(self):
654+
return self.grpc_channel.close()
655+
653656

654657
__all__ = ("DataTransferServiceGrpcAsyncIOTransport",)

google/cloud/bigquery_datatransfer_v1/types/datatransfer.py

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -236,6 +236,7 @@ class DataRefreshType(proto.Enum):
236236

237237
class GetDataSourceRequest(proto.Message):
238238
r"""A request to get data source info.
239+
239240
Attributes:
240241
name (str):
241242
Required. The field will contain name of the resource
@@ -275,6 +276,7 @@ class ListDataSourcesRequest(proto.Message):
275276

276277
class ListDataSourcesResponse(proto.Message):
277278
r"""Returns list of supported data sources and their metadata.
279+
278280
Attributes:
279281
data_sources (Sequence[google.cloud.bigquery_datatransfer_v1.types.DataSource]):
280282
List of supported data sources and their
@@ -419,6 +421,7 @@ class UpdateTransferConfigRequest(proto.Message):
419421

420422
class GetTransferConfigRequest(proto.Message):
421423
r"""A request to get data transfer information.
424+
422425
Attributes:
423426
name (str):
424427
Required. The field will contain name of the resource
@@ -447,6 +450,7 @@ class DeleteTransferConfigRequest(proto.Message):
447450

448451
class GetTransferRunRequest(proto.Message):
449452
r"""A request to get data transfer run information.
453+
450454
Attributes:
451455
name (str):
452456
Required. The field will contain name of the resource
@@ -461,6 +465,7 @@ class GetTransferRunRequest(proto.Message):
461465

462466
class DeleteTransferRunRequest(proto.Message):
463467
r"""A request to delete data transfer run information.
468+
464469
Attributes:
465470
name (str):
466471
Required. The field will contain name of the resource
@@ -504,6 +509,7 @@ class ListTransferConfigsRequest(proto.Message):
504509

505510
class ListTransferConfigsResponse(proto.Message):
506511
r"""The returned list of pipelines in the project.
512+
507513
Attributes:
508514
transfer_configs (Sequence[google.cloud.bigquery_datatransfer_v1.types.TransferConfig]):
509515
Output only. The stored pipeline transfer
@@ -568,6 +574,7 @@ class RunAttempt(proto.Enum):
568574

569575
class ListTransferRunsResponse(proto.Message):
570576
r"""The returned list of pipelines in the project.
577+
571578
Attributes:
572579
transfer_runs (Sequence[google.cloud.bigquery_datatransfer_v1.types.TransferRun]):
573580
Output only. The stored pipeline transfer
@@ -624,6 +631,7 @@ class ListTransferLogsRequest(proto.Message):
624631

625632
class ListTransferLogsResponse(proto.Message):
626633
r"""The returned list transfer run messages.
634+
627635
Attributes:
628636
transfer_messages (Sequence[google.cloud.bigquery_datatransfer_v1.types.TransferMessage]):
629637
Output only. The stored pipeline transfer
@@ -678,6 +686,7 @@ class CheckValidCredsResponse(proto.Message):
678686

679687
class ScheduleTransferRunsRequest(proto.Message):
680688
r"""A request to schedule transfer runs for a time range.
689+
681690
Attributes:
682691
parent (str):
683692
Required. Transfer configuration name in the form:
@@ -698,6 +707,7 @@ class ScheduleTransferRunsRequest(proto.Message):
698707

699708
class ScheduleTransferRunsResponse(proto.Message):
700709
r"""A response to schedule transfer runs for a time range.
710+
701711
Attributes:
702712
runs (Sequence[google.cloud.bigquery_datatransfer_v1.types.TransferRun]):
703713
The transfer runs that were scheduled.
@@ -708,6 +718,7 @@ class ScheduleTransferRunsResponse(proto.Message):
708718

709719
class StartManualTransferRunsRequest(proto.Message):
710720
r"""A request to start manual transfer runs.
721+
711722
Attributes:
712723
parent (str):
713724
Transfer configuration name in the form:
@@ -759,6 +770,7 @@ class TimeRange(proto.Message):
759770

760771
class StartManualTransferRunsResponse(proto.Message):
761772
r"""A response to start manual transfer runs.
773+
762774
Attributes:
763775
runs (Sequence[google.cloud.bigquery_datatransfer_v1.types.TransferRun]):
764776
The transfer runs that were created.

google/cloud/bigquery_datatransfer_v1/types/transfer.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -67,6 +67,7 @@ class EmailPreferences(proto.Message):
6767

6868
class ScheduleOptions(proto.Message):
6969
r"""Options customizing the data transfer schedule.
70+
7071
Attributes:
7172
disable_auto_scheduling (bool):
7273
If true, automatic scheduling of data
@@ -205,6 +206,7 @@ class TransferConfig(proto.Message):
205206

206207
class TransferRun(proto.Message):
207208
r"""Represents a data transfer run.
209+
208210
Attributes:
209211
name (str):
210212
The resource name of the transfer run. Transfer run names

tests/unit/gapic/bigquery_datatransfer_v1/test_data_transfer_service.py

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,7 @@
2929
from google.api_core import gapic_v1
3030
from google.api_core import grpc_helpers
3131
from google.api_core import grpc_helpers_async
32+
from google.api_core import path_template
3233
from google.auth import credentials as ga_credentials
3334
from google.auth.exceptions import MutualTLSChannelError
3435
from google.cloud.bigquery_datatransfer_v1.services.data_transfer_service import (
@@ -4589,6 +4590,9 @@ def test_data_transfer_service_base_transport():
45894590
with pytest.raises(NotImplementedError):
45904591
getattr(transport, method)(request=object())
45914592

4593+
with pytest.raises(NotImplementedError):
4594+
transport.close()
4595+
45924596

45934597
@requires_google_auth_gte_1_25_0
45944598
def test_data_transfer_service_base_transport_with_credentials_file():
@@ -5117,3 +5121,49 @@ def test_client_withDEFAULT_CLIENT_INFO():
51175121
credentials=ga_credentials.AnonymousCredentials(), client_info=client_info,
51185122
)
51195123
prep.assert_called_once_with(client_info)
5124+
5125+
5126+
@pytest.mark.asyncio
5127+
async def test_transport_close_async():
5128+
client = DataTransferServiceAsyncClient(
5129+
credentials=ga_credentials.AnonymousCredentials(), transport="grpc_asyncio",
5130+
)
5131+
with mock.patch.object(
5132+
type(getattr(client.transport, "grpc_channel")), "close"
5133+
) as close:
5134+
async with client:
5135+
close.assert_not_called()
5136+
close.assert_called_once()
5137+
5138+
5139+
def test_transport_close():
5140+
transports = {
5141+
"grpc": "_grpc_channel",
5142+
}
5143+
5144+
for transport, close_name in transports.items():
5145+
client = DataTransferServiceClient(
5146+
credentials=ga_credentials.AnonymousCredentials(), transport=transport
5147+
)
5148+
with mock.patch.object(
5149+
type(getattr(client.transport, close_name)), "close"
5150+
) as close:
5151+
with client:
5152+
close.assert_not_called()
5153+
close.assert_called_once()
5154+
5155+
5156+
def test_client_ctx():
5157+
transports = [
5158+
"grpc",
5159+
]
5160+
for transport in transports:
5161+
client = DataTransferServiceClient(
5162+
credentials=ga_credentials.AnonymousCredentials(), transport=transport
5163+
)
5164+
# Test client calls underlying transport.
5165+
with mock.patch.object(type(client.transport), "close") as close:
5166+
close.assert_not_called()
5167+
with client:
5168+
pass
5169+
close.assert_called()

0 commit comments

Comments
 (0)