Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: closed subscriber as context manager raises #488

Merged
merged 2 commits into from Sep 2, 2021
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
12 changes: 12 additions & 0 deletions google/cloud/pubsub_v1/subscriber/client.py
Expand Up @@ -85,6 +85,7 @@ def __init__(self, **kwargs):
# Instantiate the underlying GAPIC client.
self._api = subscriber_client.SubscriberClient(**kwargs)
self._target = self._api._transport._host
self._closed = False

@classmethod
def from_service_account_file(cls, filename, **kwargs):
Expand Down Expand Up @@ -120,6 +121,14 @@ def api(self):
"""The underlying gapic API client."""
return self._api

@property
def closed(self) -> bool:
"""Return whether the client has been closed and cannot be used anymore.

.. versionadded:: 2.8.0
"""
return self._closed

def subscribe(
self,
subscription,
Expand Down Expand Up @@ -252,8 +261,11 @@ def close(self):
This method is idempotent.
"""
self.api._transport.grpc_channel.close()
self._closed = True

def __enter__(self):
if self._closed:
raise RuntimeError("Closed subscriber cannot be used as context manager.")
return self

def __exit__(self, exc_type, exc_val, exc_tb):
Expand Down
18 changes: 18 additions & 0 deletions tests/unit/pubsub_v1/subscriber/test_subscriber_client.py
Expand Up @@ -50,6 +50,11 @@ def test_init_default_client_info(creds):
assert expected_client_info in user_agent


def test_init_default_closed_state(creds):
client = subscriber.Client(credentials=creds)
assert not client.closed


def test_init_w_custom_transport(creds):
transport = SubscriberGrpcTransport(credentials=creds)
client = subscriber.Client(transport=transport)
Expand Down Expand Up @@ -185,6 +190,7 @@ def test_close(creds):
client.close()

patched_close.assert_called()
assert client.closed


def test_closes_channel_as_context_manager(creds):
Expand All @@ -198,6 +204,18 @@ def test_closes_channel_as_context_manager(creds):
patched_close.assert_called()


def test_context_manager_raises_if_closed(creds):
client = subscriber.Client(credentials=creds)

with mock.patch.object(client.api._transport.grpc_channel, "close"):
client.close()

expetect_msg = r"(?i).*closed.*cannot.*context manager.*"
with pytest.raises(RuntimeError, match=expetect_msg):
with client:
pass


def test_streaming_pull_gapic_monkeypatch(creds):
client = subscriber.Client(credentials=creds)

Expand Down