|
7 | 7 |
|
8 | 8 | import io |
9 | 9 | import json |
| 10 | +import os |
| 11 | +import threading |
| 12 | +import time |
10 | 13 |
|
11 | 14 | import pytest |
12 | 15 |
|
@@ -265,3 +268,62 @@ def test_read_message_multiple_messages_in_sequence(self): |
265 | 268 |
|
266 | 269 | result2 = client._read_message() |
267 | 270 | assert result2 == message2 |
| 271 | + |
| 272 | + |
| 273 | +class ClosingStream: |
| 274 | + """Stream that immediately returns empty bytes (simulates process death / EOF).""" |
| 275 | + |
| 276 | + def readline(self): |
| 277 | + return b"" |
| 278 | + |
| 279 | + def read(self, n: int) -> bytes: |
| 280 | + return b"" |
| 281 | + |
| 282 | + |
| 283 | +class TestOnClose: |
| 284 | + """Tests for the on_close callback when the read loop exits unexpectedly.""" |
| 285 | + |
| 286 | + def test_on_close_called_on_unexpected_exit(self): |
| 287 | + """on_close fires when the stream closes while client is still running.""" |
| 288 | + import asyncio |
| 289 | + |
| 290 | + process = MockProcess() |
| 291 | + process.stdout = ClosingStream() |
| 292 | + |
| 293 | + client = JsonRpcClient(process) |
| 294 | + |
| 295 | + called = threading.Event() |
| 296 | + client.on_close = lambda: called.set() |
| 297 | + |
| 298 | + loop = asyncio.new_event_loop() |
| 299 | + try: |
| 300 | + client.start(loop=loop) |
| 301 | + assert called.wait(timeout=2), "on_close was not called within 2 seconds" |
| 302 | + finally: |
| 303 | + loop.close() |
| 304 | + |
| 305 | + def test_on_close_not_called_on_intentional_stop(self): |
| 306 | + """on_close should not fire when stop() is called intentionally.""" |
| 307 | + import asyncio |
| 308 | + |
| 309 | + r_fd, w_fd = os.pipe() |
| 310 | + process = MockProcess() |
| 311 | + process.stdout = os.fdopen(r_fd, "rb") |
| 312 | + |
| 313 | + client = JsonRpcClient(process) |
| 314 | + |
| 315 | + called = threading.Event() |
| 316 | + client.on_close = lambda: called.set() |
| 317 | + |
| 318 | + loop = asyncio.new_event_loop() |
| 319 | + try: |
| 320 | + client.start(loop=loop) |
| 321 | + |
| 322 | + # Intentional stop sets _running = False before the thread sees EOF |
| 323 | + loop.run_until_complete(client.stop()) |
| 324 | + os.close(w_fd) |
| 325 | + |
| 326 | + time.sleep(0.5) |
| 327 | + assert not called.is_set(), "on_close should not be called on intentional stop" |
| 328 | + finally: |
| 329 | + loop.close() |
0 commit comments