Skip to content

Commit 17b2fc5

Browse files
Verify client context managers close on exceptions
Co-authored-by: Shri Sukhani <shrisukhani@users.noreply.github.com>
1 parent cde0fb1 commit 17b2fc5

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed

tests/test_client_lifecycle.py

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
import asyncio
22

3+
import pytest
4+
35
from hyperbrowser.client.async_client import AsyncHyperbrowser
46
from hyperbrowser.client.managers.async_manager.session import SessionEventLogsManager
57
from hyperbrowser.client.sync import Hyperbrowser
@@ -43,6 +45,45 @@ async def tracked_close() -> None:
4345
asyncio.run(run())
4446

4547

48+
def test_sync_client_context_manager_closes_transport_on_exception():
49+
client = Hyperbrowser(api_key="test-key")
50+
close_calls = {"count": 0}
51+
original_close = client.transport.close
52+
53+
def tracked_close() -> None:
54+
close_calls["count"] += 1
55+
original_close()
56+
57+
client.transport.close = tracked_close
58+
59+
with pytest.raises(RuntimeError, match="sync boom"):
60+
with client:
61+
raise RuntimeError("sync boom")
62+
63+
assert close_calls["count"] == 1
64+
65+
66+
def test_async_client_context_manager_closes_transport_on_exception():
67+
async def run() -> None:
68+
client = AsyncHyperbrowser(api_key="test-key")
69+
close_calls = {"count": 0}
70+
original_close = client.transport.close
71+
72+
async def tracked_close() -> None:
73+
close_calls["count"] += 1
74+
await original_close()
75+
76+
client.transport.close = tracked_close
77+
78+
with pytest.raises(RuntimeError, match="async boom"):
79+
async with client:
80+
raise RuntimeError("async boom")
81+
82+
assert close_calls["count"] == 1
83+
84+
asyncio.run(run())
85+
86+
4687
def test_async_session_event_logs_annotation_is_response_model():
4788
assert (
4889
SessionEventLogsManager.list.__annotations__["return"]

0 commit comments

Comments
 (0)