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 (#37)
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: https://github.com/googleapis/googleapis-gen/commit/81decffe9fc72396a8153e756d1d67a6eecfd620
Copy-Tag: eyJwIjoiLmdpdGh1Yi8uT3dsQm90LnlhbWwiLCJoIjoiODFkZWNmZmU5ZmM3MjM5NmE4MTUzZTc1NmQxZDY3YTZlZWNmZDYyMCJ9
  • Loading branch information
gcf-owl-bot[bot] authored Oct 7, 2021
1 parent faef60d commit 173b3db
Show file tree
Hide file tree
Showing 11 changed files with 110 additions and 4 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -1577,6 +1577,12 @@ async def delete_client_tls_policy(
# 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
Original file line number Diff line number Diff line change
Expand Up @@ -402,10 +402,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_authorization_policies(
Expand Down Expand Up @@ -1818,6 +1815,19 @@ def delete_client_tls_policy(
# 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
Original file line number Diff line number Diff line change
Expand Up @@ -244,6 +244,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
Original file line number Diff line number Diff line change
Expand Up @@ -685,5 +685,8 @@ def delete_client_tls_policy(
)
return self._stubs["delete_client_tls_policy"]

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


__all__ = ("NetworkSecurityGrpcTransport",)
Original file line number Diff line number Diff line change
Expand Up @@ -698,5 +698,8 @@ def delete_client_tls_policy(
)
return self._stubs["delete_client_tls_policy"]

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


__all__ = ("NetworkSecurityGrpcAsyncIOTransport",)
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,7 @@ class Action(proto.Enum):

class Rule(proto.Message):
r"""Specification of rules.
Attributes:
sources (Sequence[google.cloud.network_security_v1beta1.types.AuthorizationPolicy.Rule.Source]):
Optional. List of attributes for the traffic source. All of
Expand All @@ -96,6 +97,7 @@ class Rule(proto.Message):

class Source(proto.Message):
r"""Specification of traffic source attributes.
Attributes:
principals (Sequence[str]):
Optional. List of peer identities to match for
Expand All @@ -115,6 +117,7 @@ class Source(proto.Message):

class Destination(proto.Message):
r"""Specification of traffic destination attributes.
Attributes:
hosts (Sequence[str]):
Required. List of host names to match. Matched against HOST
Expand All @@ -138,6 +141,7 @@ class Destination(proto.Message):

class HttpHeaderMatch(proto.Message):
r"""Specification of HTTP header match atrributes.
Attributes:
regex_match (str):
Required. The value of the header must match
Expand Down Expand Up @@ -186,6 +190,7 @@ class HttpHeaderMatch(proto.Message):

class ListAuthorizationPoliciesRequest(proto.Message):
r"""Request used with the ListAuthorizationPolicies method.
Attributes:
parent (str):
Required. The project and location from which the
Expand All @@ -209,6 +214,7 @@ class ListAuthorizationPoliciesRequest(proto.Message):

class ListAuthorizationPoliciesResponse(proto.Message):
r"""Response returned by the ListAuthorizationPolicies method.
Attributes:
authorization_policies (Sequence[google.cloud.network_security_v1beta1.types.AuthorizationPolicy]):
List of AuthorizationPolicies resources.
Expand All @@ -231,6 +237,7 @@ def raw_page(self):

class GetAuthorizationPolicyRequest(proto.Message):
r"""Request used by the GetAuthorizationPolicy method.
Attributes:
name (str):
Required. A name of the AuthorizationPolicy to get. Must be
Expand All @@ -243,6 +250,7 @@ class GetAuthorizationPolicyRequest(proto.Message):

class CreateAuthorizationPolicyRequest(proto.Message):
r"""Request used by the CreateAuthorizationPolicy method.
Attributes:
parent (str):
Required. The parent resource of the AuthorizationPolicy.
Expand All @@ -267,6 +275,7 @@ class CreateAuthorizationPolicyRequest(proto.Message):

class UpdateAuthorizationPolicyRequest(proto.Message):
r"""Request used by the UpdateAuthorizationPolicy method.
Attributes:
update_mask (google.protobuf.field_mask_pb2.FieldMask):
Optional. Field mask is used to specify the fields to be
Expand All @@ -290,6 +299,7 @@ class UpdateAuthorizationPolicyRequest(proto.Message):

class DeleteAuthorizationPolicyRequest(proto.Message):
r"""Request used by the DeleteAuthorizationPolicy method.
Attributes:
name (str):
Required. A name of the AuthorizationPolicy to delete. Must
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,7 @@ class ClientTlsPolicy(proto.Message):

class ListClientTlsPoliciesRequest(proto.Message):
r"""Request used by the ListClientTlsPolicies method.
Attributes:
parent (str):
Required. The project and location from which the
Expand All @@ -111,6 +112,7 @@ class ListClientTlsPoliciesRequest(proto.Message):

class ListClientTlsPoliciesResponse(proto.Message):
r"""Response returned by the ListClientTlsPolicies method.
Attributes:
client_tls_policies (Sequence[google.cloud.network_security_v1beta1.types.ClientTlsPolicy]):
List of ClientTlsPolicy resources.
Expand All @@ -133,6 +135,7 @@ def raw_page(self):

class GetClientTlsPolicyRequest(proto.Message):
r"""Request used by the GetClientTlsPolicy method.
Attributes:
name (str):
Required. A name of the ClientTlsPolicy to get. Must be in
Expand All @@ -145,6 +148,7 @@ class GetClientTlsPolicyRequest(proto.Message):

class CreateClientTlsPolicyRequest(proto.Message):
r"""Request used by the CreateClientTlsPolicy method.
Attributes:
parent (str):
Required. The parent resource of the ClientTlsPolicy. Must
Expand All @@ -167,6 +171,7 @@ class CreateClientTlsPolicyRequest(proto.Message):

class UpdateClientTlsPolicyRequest(proto.Message):
r"""Request used by UpdateClientTlsPolicy method.
Attributes:
update_mask (google.protobuf.field_mask_pb2.FieldMask):
Optional. Field mask is used to specify the fields to be
Expand All @@ -187,6 +192,7 @@ class UpdateClientTlsPolicyRequest(proto.Message):

class DeleteClientTlsPolicyRequest(proto.Message):
r"""Request used by the DeleteClientTlsPolicy method.
Attributes:
name (str):
Required. A name of the ClientTlsPolicy to delete. Must be
Expand Down
1 change: 1 addition & 0 deletions google/cloud/network_security_v1beta1/types/common.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@

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
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,7 @@ class ServerTlsPolicy(proto.Message):

class MTLSPolicy(proto.Message):
r"""Specification of the MTLSPolicy.
Attributes:
client_validation_ca (Sequence[google.cloud.network_security_v1beta1.types.ValidationCA]):
Required. Defines the mechanism to obtain the
Expand All @@ -106,6 +107,7 @@ class MTLSPolicy(proto.Message):

class ListServerTlsPoliciesRequest(proto.Message):
r"""Request used by the ListServerTlsPolicies method.
Attributes:
parent (str):
Required. The project and location from which the
Expand All @@ -128,6 +130,7 @@ class ListServerTlsPoliciesRequest(proto.Message):

class ListServerTlsPoliciesResponse(proto.Message):
r"""Response returned by the ListServerTlsPolicies method.
Attributes:
server_tls_policies (Sequence[google.cloud.network_security_v1beta1.types.ServerTlsPolicy]):
List of ServerTlsPolicy resources.
Expand All @@ -150,6 +153,7 @@ def raw_page(self):

class GetServerTlsPolicyRequest(proto.Message):
r"""Request used by the GetServerTlsPolicy method.
Attributes:
name (str):
Required. A name of the ServerTlsPolicy to get. Must be in
Expand All @@ -162,6 +166,7 @@ class GetServerTlsPolicyRequest(proto.Message):

class CreateServerTlsPolicyRequest(proto.Message):
r"""Request used by the CreateServerTlsPolicy method.
Attributes:
parent (str):
Required. The parent resource of the ServerTlsPolicy. Must
Expand All @@ -184,6 +189,7 @@ class CreateServerTlsPolicyRequest(proto.Message):

class UpdateServerTlsPolicyRequest(proto.Message):
r"""Request used by UpdateServerTlsPolicy method.
Attributes:
update_mask (google.protobuf.field_mask_pb2.FieldMask):
Optional. Field mask is used to specify the fields to be
Expand All @@ -204,6 +210,7 @@ class UpdateServerTlsPolicyRequest(proto.Message):

class DeleteServerTlsPolicyRequest(proto.Message):
r"""Request used by the DeleteServerTlsPolicy method.
Attributes:
name (str):
Required. A name of the ServerTlsPolicy to delete. Must be
Expand Down
1 change: 1 addition & 0 deletions google/cloud/network_security_v1beta1/types/tls.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@

class GrpcEndpoint(proto.Message):
r"""Specification of the GRPC Endpoint.
Attributes:
target_uri (str):
Required. The target URI of the gRPC
Expand Down
50 changes: 50 additions & 0 deletions tests/unit/gapic/network_security_v1beta1/test_network_security.py
Original file line number Diff line number Diff line change
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.network_security_v1beta1.services.network_security import (
Expand Down Expand Up @@ -4614,6 +4615,9 @@ def test_network_security_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 @@ -5181,3 +5185,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 = NetworkSecurityAsyncClient(
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 = NetworkSecurityClient(
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 = NetworkSecurityClient(
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 173b3db

Please sign in to comment.