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

Commit

Permalink
feat: add context manager support in client (#131)
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 8d6fb3a commit eb9fc8b
Show file tree
Hide file tree
Showing 16 changed files with 178 additions and 8 deletions.
Expand Up @@ -2789,6 +2789,12 @@ async def update_certificate_template(
# 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 @@ -450,10 +450,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_certificate(
Expand Down Expand Up @@ -3075,6 +3072,19 @@ def update_certificate_template(
# 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 @@ -282,6 +282,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."""
Expand Down
Expand Up @@ -1103,5 +1103,8 @@ def update_certificate_template(
)
return self._stubs["update_certificate_template"]

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


__all__ = ("CertificateAuthorityServiceGrpcTransport",)
Expand Up @@ -1128,5 +1128,8 @@ def update_certificate_template(
)
return self._stubs["update_certificate_template"]

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


__all__ = ("CertificateAuthorityServiceGrpcAsyncIOTransport",)
2 changes: 2 additions & 0 deletions google/cloud/security/privateca_v1/types/resources.py
Expand Up @@ -904,6 +904,7 @@ class X509Parameters(proto.Message):

class CaOptions(proto.Message):
r"""Describes values that are relevant in a CA certificate.
Attributes:
is_ca (bool):
Optional. Refers to the "CA" X.509 extension,
Expand Down Expand Up @@ -1141,6 +1142,7 @@ class KeyId(proto.Message):

class CertificateFingerprint(proto.Message):
r"""A group of fingerprints for the x509 certificate.
Attributes:
sha256_hash (str):
The SHA 256 hash, encoded in hexadecimal, of
Expand Down
2 changes: 2 additions & 0 deletions google/cloud/security/privateca_v1/types/service.py
Expand Up @@ -872,6 +872,7 @@ class FetchCaCertsResponse(proto.Message):

class CertChain(proto.Message):
r"""
Attributes:
certificates (Sequence[str]):
The certificates that form the CA chain, from
Expand Down Expand Up @@ -1290,6 +1291,7 @@ class UpdateCertificateTemplateRequest(proto.Message):

class OperationMetadata(proto.Message):
r"""Represents the metadata of the long-running operation.
Attributes:
create_time (google.protobuf.timestamp_pb2.Timestamp):
Output only. The time the operation was
Expand Down
Expand Up @@ -1943,6 +1943,12 @@ async def list_reusable_configs(
# 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 @@ -426,10 +426,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_certificate(
Expand Down Expand Up @@ -2202,6 +2199,19 @@ def list_reusable_configs(
# 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 @@ -247,6 +247,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."""
Expand Down
Expand Up @@ -863,5 +863,8 @@ def list_reusable_configs(
)
return self._stubs["list_reusable_configs"]

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


__all__ = ("CertificateAuthorityServiceGrpcTransport",)
Expand Up @@ -881,5 +881,8 @@ def list_reusable_configs(
)
return self._stubs["list_reusable_configs"]

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


__all__ = ("CertificateAuthorityServiceGrpcAsyncIOTransport",)
3 changes: 3 additions & 0 deletions google/cloud/security/privateca_v1beta1/types/resources.py
Expand Up @@ -319,6 +319,7 @@ class CertificateAuthorityPolicy(proto.Message):

class AllowedConfigList(proto.Message):
r"""
Attributes:
allowed_config_values (Sequence[google.cloud.security.privateca_v1beta1.types.ReusableConfigWrapper]):
Required. All
Expand Down Expand Up @@ -770,6 +771,7 @@ class ReusableConfigValues(proto.Message):

class CaOptions(proto.Message):
r"""Describes values that are relevant in a CA certificate.
Attributes:
is_ca (google.protobuf.wrappers_pb2.BoolValue):
Optional. Refers to the "CA" X.509 extension,
Expand Down Expand Up @@ -1038,6 +1040,7 @@ class KeyId(proto.Message):

class CertificateFingerprint(proto.Message):
r"""A group of fingerprints for the x509 certificate.
Attributes:
sha256_hash (str):
The SHA 256 hash, encoded in hexadecimal, of
Expand Down
1 change: 1 addition & 0 deletions google/cloud/security/privateca_v1beta1/types/service.py
Expand Up @@ -857,6 +857,7 @@ def raw_page(self):

class OperationMetadata(proto.Message):
r"""Represents the metadata of the long-running operation.
Attributes:
create_time (google.protobuf.timestamp_pb2.Timestamp):
Output only. The time the operation was
Expand Down
Expand Up @@ -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.security.privateca_v1.services.certificate_authority_service import (
Expand Down Expand Up @@ -8208,6 +8209,9 @@ def test_certificate_authority_service_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):
Expand Down Expand Up @@ -8855,3 +8859,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 = CertificateAuthorityServiceAsyncClient(
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 = CertificateAuthorityServiceClient(
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 = CertificateAuthorityServiceClient(
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()
Expand Up @@ -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.security.privateca_v1beta1.services.certificate_authority_service import (
Expand Down Expand Up @@ -6029,6 +6030,9 @@ def test_certificate_authority_service_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):
Expand Down Expand Up @@ -6647,3 +6651,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 = CertificateAuthorityServiceAsyncClient(
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 = CertificateAuthorityServiceClient(
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 = CertificateAuthorityServiceClient(
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 eb9fc8b

Please sign in to comment.