Skip to content

Commit 7d0e48c

Browse files
committed
Clean up logic surrounding session auto-creation
1 parent 1b18a88 commit 7d0e48c

2 files changed

Lines changed: 13 additions & 10 deletions

File tree

nanokvm/client.py

Lines changed: 4 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -152,7 +152,7 @@ def __init__(
152152
"""
153153
self.url = yarl.URL(url)
154154
self._session: ClientSession | None = session
155-
self._auto_close_session = session is None
155+
self._external_session_provided = session is not None
156156
self._token = token
157157
self._request_timeout = request_timeout
158158
self._ws: aiohttp.ClientWebSocketResponse | None = None
@@ -203,7 +203,7 @@ def token(self) -> str | None:
203203

204204
async def __aenter__(self) -> NanoKVMClient:
205205
"""Async context manager entry."""
206-
if self._session is None:
206+
if self._session is None and not self._external_session_provided:
207207
self._session = ClientSession()
208208

209209
self._ssl_config = await asyncio.to_thread(self._create_ssl_context)
@@ -217,10 +217,8 @@ async def __aexit__(self, exc_type: Any, exc_val: Any, exc_tb: Any) -> None:
217217
self._ws = None
218218

219219
# Close HTTP session
220-
if self._session is not None:
221-
if self._auto_close_session:
222-
await self._session.close()
223-
220+
if self._session is not None and not self._external_session_provided:
221+
await self._session.close()
224222
self._session = None
225223

226224
@contextlib.asynccontextmanager

tests/test_client.py

Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -85,18 +85,23 @@ async def test_client_context_manager() -> None:
8585
async def test_client_context_manager_external_session() -> None:
8686
"""Test that client properly deals with an external session."""
8787
async with ClientSession() as session:
88-
# Both clients connect with the same external session
88+
client3 = NanoKVMClient("http://localhost:8888/api/", session=session)
89+
90+
# All clients connect with the same external session
8991
async with (
9092
NanoKVMClient("http://localhost:8888/api/", session=session) as client1,
9193
NanoKVMClient("http://localhost:8888/api/", session=session) as client2,
94+
client3,
9295
):
9396
# Verify session is created
9497
assert client1._session is session
9598
assert client2._session is session
99+
assert client3._session is session
100+
101+
# Reusing a client with an external session should not close the session
102+
async with client3:
103+
assert client3._session is session
96104

97-
# Both exit but the session is still open
98105
assert not session.closed
99-
assert client1._session is None
100-
assert client2._session is None
101106

102107
assert session.closed

0 commit comments

Comments
 (0)