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 #145

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 @@ -624,6 +624,12 @@ async def delete_budget(
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(
Expand Down
18 changes: 14 additions & 4 deletions google/cloud/billing/budgets_v1/services/budget_service/client.py
Expand Up @@ -346,10 +346,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_budget(
Expand Down Expand Up @@ -770,6 +767,19 @@ def delete_budget(
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(
Expand Down
Expand Up @@ -224,6 +224,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_budget(
self,
Expand Down
Expand Up @@ -379,5 +379,8 @@ def delete_budget(
)
return self._stubs["delete_budget"]

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


__all__ = ("BudgetServiceGrpcTransport",)
Expand Up @@ -383,5 +383,8 @@ def delete_budget(
)
return self._stubs["delete_budget"]

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


__all__ = ("BudgetServiceGrpcAsyncIOTransport",)
4 changes: 3 additions & 1 deletion google/cloud/billing/budgets_v1/types/budget_model.py
Expand Up @@ -101,6 +101,7 @@ class Budget(proto.Message):

class BudgetAmount(proto.Message):
r"""The budgeted amount for each usage period.

Attributes:
specified_amount (google.type.money_pb2.Money):
A specified amount to use as the budget. ``currency_code``
Expand Down Expand Up @@ -135,7 +136,8 @@ class LastPeriodAmount(proto.Message):
configuring a percentage of last period's spend). LastPeriodAmount
cannot be set for a budget configured with a
[Filter.custom_period][google.cloud.billing.budgets.v1.Filter.custom_period].
"""

"""


class ThresholdRule(proto.Message):
Expand Down
6 changes: 6 additions & 0 deletions google/cloud/billing/budgets_v1/types/budget_service.py
Expand Up @@ -34,6 +34,7 @@

class CreateBudgetRequest(proto.Message):
r"""Request for CreateBudget

Attributes:
parent (str):
Required. The name of the billing account to create the
Expand All @@ -49,6 +50,7 @@ class CreateBudgetRequest(proto.Message):

class UpdateBudgetRequest(proto.Message):
r"""Request for UpdateBudget

Attributes:
budget (google.cloud.billing.budgets_v1.types.Budget):
Required. The updated budget object.
Expand All @@ -71,6 +73,7 @@ class UpdateBudgetRequest(proto.Message):

class GetBudgetRequest(proto.Message):
r"""Request for GetBudget

Attributes:
name (str):
Required. Name of budget to get. Values are of the form
Expand All @@ -82,6 +85,7 @@ class GetBudgetRequest(proto.Message):

class ListBudgetsRequest(proto.Message):
r"""Request for ListBudgets

Attributes:
parent (str):
Required. Name of billing account to list budgets under.
Expand All @@ -105,6 +109,7 @@ class ListBudgetsRequest(proto.Message):

class ListBudgetsResponse(proto.Message):
r"""Response for ListBudgets

Attributes:
budgets (Sequence[google.cloud.billing.budgets_v1.types.Budget]):
List of the budgets owned by the requested
Expand All @@ -125,6 +130,7 @@ def raw_page(self):

class DeleteBudgetRequest(proto.Message):
r"""Request for DeleteBudget

Attributes:
name (str):
Required. Name of the budget to delete. Values are of the
Expand Down
Expand Up @@ -487,6 +487,12 @@ async def delete_budget(
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(
Expand Down
Expand Up @@ -345,10 +345,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_budget(
Expand Down Expand Up @@ -638,6 +635,19 @@ def delete_budget(
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(
Expand Down
Expand Up @@ -224,6 +224,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_budget(
self,
Expand Down
Expand Up @@ -379,5 +379,8 @@ def delete_budget(
)
return self._stubs["delete_budget"]

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


__all__ = ("BudgetServiceGrpcTransport",)
Expand Up @@ -383,5 +383,8 @@ def delete_budget(
)
return self._stubs["delete_budget"]

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


__all__ = ("BudgetServiceGrpcAsyncIOTransport",)
4 changes: 3 additions & 1 deletion google/cloud/billing/budgets_v1beta1/types/budget_model.py
Expand Up @@ -99,6 +99,7 @@ class Budget(proto.Message):

class BudgetAmount(proto.Message):
r"""The budgeted amount for each usage period.

Attributes:
specified_amount (google.type.money_pb2.Money):
A specified amount to use as the budget. ``currency_code``
Expand Down Expand Up @@ -133,7 +134,8 @@ class LastPeriodAmount(proto.Message):
configuring a percentage of last period's spend). LastPeriodAmount
cannot be set for a budget configured with a
[Filter.custom_period][google.cloud.billing.budgets.v1beta1.Filter.custom_period].
"""

"""


class ThresholdRule(proto.Message):
Expand Down
6 changes: 6 additions & 0 deletions google/cloud/billing/budgets_v1beta1/types/budget_service.py
Expand Up @@ -34,6 +34,7 @@

class CreateBudgetRequest(proto.Message):
r"""Request for CreateBudget

Attributes:
parent (str):
Required. The name of the billing account to create the
Expand All @@ -49,6 +50,7 @@ class CreateBudgetRequest(proto.Message):

class UpdateBudgetRequest(proto.Message):
r"""Request for UpdateBudget

Attributes:
budget (google.cloud.billing.budgets_v1beta1.types.Budget):
Required. The updated budget object.
Expand All @@ -71,6 +73,7 @@ class UpdateBudgetRequest(proto.Message):

class GetBudgetRequest(proto.Message):
r"""Request for GetBudget

Attributes:
name (str):
Required. Name of budget to get. Values are of the form
Expand All @@ -82,6 +85,7 @@ class GetBudgetRequest(proto.Message):

class ListBudgetsRequest(proto.Message):
r"""Request for ListBudgets

Attributes:
parent (str):
Required. Name of billing account to list budgets under.
Expand All @@ -105,6 +109,7 @@ class ListBudgetsRequest(proto.Message):

class ListBudgetsResponse(proto.Message):
r"""Response for ListBudgets

Attributes:
budgets (Sequence[google.cloud.billing.budgets_v1beta1.types.Budget]):
List of the budgets owned by the requested
Expand All @@ -125,6 +130,7 @@ def raw_page(self):

class DeleteBudgetRequest(proto.Message):
r"""Request for DeleteBudget

Attributes:
name (str):
Required. Name of the budget to delete. Values are of the
Expand Down
50 changes: 50 additions & 0 deletions tests/unit/gapic/budgets_v1/test_budget_service.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.billing.budgets_v1.services.budget_service import (
Expand Down Expand Up @@ -1784,6 +1785,9 @@ def test_budget_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_budget_service_base_transport_with_credentials_file():
Expand Down Expand Up @@ -2283,3 +2287,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 = BudgetServiceAsyncClient(
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 = BudgetServiceClient(
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 = BudgetServiceClient(
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()