|
| 1 | +import logging |
| 2 | +import types |
| 3 | +import threading |
| 4 | + |
| 5 | + |
| 6 | +def test_server_shutdown_audit_logs_active_stream_context(monkeypatch, caplog): |
| 7 | + import server |
| 8 | + from api import models |
| 9 | + |
| 10 | + monkeypatch.setattr(server, "_SHUTDOWN_AUDIT_LOGGED", False) |
| 11 | + monkeypatch.setitem( |
| 12 | + models.SESSIONS, |
| 13 | + "session-1", |
| 14 | + types.SimpleNamespace(active_stream_id="stream-1", pending_user_message="hello"), |
| 15 | + ) |
| 16 | + monkeypatch.setitem( |
| 17 | + models.SESSIONS, |
| 18 | + "session-2", |
| 19 | + types.SimpleNamespace(active_stream_id=None, pending_user_message=None), |
| 20 | + ) |
| 21 | + |
| 22 | + caplog.set_level(logging.INFO, logger="server") |
| 23 | + server._log_shutdown_audit(reason="test-exit") |
| 24 | + |
| 25 | + logged = "\n".join(record.getMessage() for record in caplog.records) |
| 26 | + assert "[shutdown-audit]" in logged |
| 27 | + assert "reason=test-exit" in logged |
| 28 | + assert "sid=session-1 stream=stream-1 pending=True" in logged |
| 29 | + assert "session-2" not in logged |
| 30 | + |
| 31 | + |
| 32 | +def test_shutdown_route_logs_request_context_without_starting_real_shutdown(monkeypatch, caplog): |
| 33 | + from api import routes |
| 34 | + |
| 35 | + responses = [] |
| 36 | + monkeypatch.setattr(routes, "j", lambda handler, payload, **kw: responses.append(payload) or True) |
| 37 | + |
| 38 | + started_threads = [] |
| 39 | + |
| 40 | + class FakeThread: |
| 41 | + def __init__(self, target, daemon=False): |
| 42 | + self.target = target |
| 43 | + self.daemon = daemon |
| 44 | + |
| 45 | + def start(self): |
| 46 | + started_threads.append((self.target, self.daemon)) |
| 47 | + |
| 48 | + monkeypatch.setattr(threading, "Thread", FakeThread) |
| 49 | + |
| 50 | + handler = types.SimpleNamespace( |
| 51 | + client_address=("127.0.0.1", 12345), |
| 52 | + command="POST", |
| 53 | + path="/api/shutdown", |
| 54 | + headers={"User-Agent": "pytest-agent"}, |
| 55 | + ) |
| 56 | + |
| 57 | + caplog.set_level(logging.INFO, logger="api.routes") |
| 58 | + assert routes._handle_shutdown(handler) is True |
| 59 | + |
| 60 | + logged = "\n".join(record.getMessage() for record in caplog.records) |
| 61 | + assert "[shutdown-request]" in logged |
| 62 | + assert "remote=127.0.0.1" in logged |
| 63 | + assert "method=POST" in logged |
| 64 | + assert "path=/api/shutdown" in logged |
| 65 | + assert "ua=pytest-agent" in logged |
| 66 | + assert responses == [{"status": "shutting_down"}] |
| 67 | + assert started_threads and started_threads[0][1] is True |
0 commit comments