|
| 1 | +import pytest |
| 2 | +import json |
| 3 | +import time |
| 4 | +from queue import Queue |
| 5 | +from unittest.mock import patch |
| 6 | +from httpx import AsyncClient, ASGITransport |
| 7 | +import pytest_asyncio |
| 8 | + |
| 9 | +from inkwell.app import create_app |
| 10 | +from inkwell.routes.api_scan import _scan_state |
| 11 | + |
| 12 | +# ------------------------------------------------------------------ |
| 13 | +# Fixtures |
| 14 | +# ------------------------------------------------------------------ |
| 15 | + |
| 16 | + |
| 17 | +@pytest_asyncio.fixture |
| 18 | +async def client(): |
| 19 | + _scan_state["running"] = False |
| 20 | + _scan_state["started_at"] = None |
| 21 | + _scan_state["current_subreddit"] = None |
| 22 | + _scan_state["cancel"] = False |
| 23 | + _scan_state["queue"] = None |
| 24 | + |
| 25 | + app = create_app() |
| 26 | + transport = ASGITransport(app=app) |
| 27 | + async with AsyncClient(transport=transport, base_url="http://test") as c: |
| 28 | + yield c |
| 29 | + |
| 30 | + |
| 31 | +# ------------------------------------------------------------------ |
| 32 | +# Tests for GET /api/scan/status |
| 33 | +# ------------------------------------------------------------------ |
| 34 | +@pytest.mark.asyncio |
| 35 | +async def test_get_scan_status_idle(client): |
| 36 | + response = await client.get("/api/scan/status") |
| 37 | + assert response.status_code == 200 |
| 38 | + data = response.json() |
| 39 | + assert data["running"] is False |
| 40 | + assert data["current_subreddit"] is None |
| 41 | + |
| 42 | + |
| 43 | +@pytest.mark.asyncio |
| 44 | +async def test_get_scan_status_running(client): |
| 45 | + _scan_state["running"] = True |
| 46 | + _scan_state["current_subreddit"] = "r/python" |
| 47 | + |
| 48 | + response = await client.get("/api/scan/status") |
| 49 | + data = response.json() |
| 50 | + assert data["running"] is True |
| 51 | + assert data["current_subreddit"] == "r/python" |
| 52 | + |
| 53 | + |
| 54 | +# ------------------------------------------------------------------ |
| 55 | +# Tests for POST /api/scan |
| 56 | +# ------------------------------------------------------------------ |
| 57 | + |
| 58 | + |
| 59 | +@pytest.mark.asyncio |
| 60 | +@patch("inkwell.routes.api_scan._run_scan_with_emit") |
| 61 | +async def test_start_scan_success(mock_run, client): |
| 62 | + |
| 63 | + def mock_emit_logic(emit, options): |
| 64 | + emit({"kind": "start", "subreddit_count": 2}) |
| 65 | + emit({"kind": "done", "scanned": 2, "new_signals": 0}) |
| 66 | + |
| 67 | + mock_run.side_effect = mock_emit_logic |
| 68 | + |
| 69 | + response = await client.post("/api/scan", json={"limit_subreddits": 2}) |
| 70 | + |
| 71 | + assert response.status_code == 200 |
| 72 | + assert "text/event-stream" in response.headers["content-type"] |
| 73 | + |
| 74 | + events = response.text.strip().split("\n\n") |
| 75 | + assert 'data: {"kind": "start", "subreddit_count": 2}' in events[0] |
| 76 | + assert 'data: {"kind": "done"' in events[1] |
| 77 | + |
| 78 | + assert _scan_state["running"] is False |
| 79 | + |
| 80 | + |
| 81 | +@pytest.mark.asyncio |
| 82 | +async def test_start_scan_conflict(client): |
| 83 | + _scan_state["running"] = True |
| 84 | + |
| 85 | + response = await client.post("/api/scan", json={}) |
| 86 | + assert response.status_code == 409 |
| 87 | + assert "already running" in response.json()["detail"] |
| 88 | + |
| 89 | + |
| 90 | +@patch("inkwell.routes.api_scan.logger") |
| 91 | +@patch("inkwell.routes.api_scan._run_scan_with_emit") |
| 92 | +@pytest.mark.asyncio |
| 93 | +async def test_start_scan_exception_handling(mock_run, mock_logger, client): |
| 94 | + mock_run.side_effect = Exception("Reddit API Down/Timeout") |
| 95 | + |
| 96 | + response = await client.post("/api/scan", json={}) |
| 97 | + |
| 98 | + assert 'data: {"kind": "error", "message": "Reddit API Down/Timeout"}' in response.text |
| 99 | + assert _scan_state["running"] is False |
| 100 | + |
| 101 | + |
| 102 | +@patch("inkwell.routes.api_scan._run_scan_with_emit") |
| 103 | +@pytest.mark.asyncio |
| 104 | +async def test_scan_heartbeat_precedes_completion_on_stall(mock_run, client): |
| 105 | + def stalling_scan(emit, options): |
| 106 | + # 7s stall > 5s heartbeat interval |
| 107 | + time.sleep(7.0) |
| 108 | + emit({"kind": "done", "scanned": 1}) |
| 109 | + |
| 110 | + mock_run.side_effect = stalling_scan |
| 111 | + |
| 112 | + response = await client.post("/api/scan", json={"limit_subreddits": 1}) |
| 113 | + |
| 114 | + events = [ev for ev in response.text.strip().split("\n\n") if ev.startswith("data:")] |
| 115 | + |
| 116 | + heartbeat_index = next((i for i, ev in enumerate(events) if '"kind": "heartbeat"' in ev), -1) |
| 117 | + done_index = next((i for i, ev in enumerate(events) if '"kind": "done"' in ev), -1) |
| 118 | + |
| 119 | + assert heartbeat_index != -1, "No heartbeat detected" |
| 120 | + assert done_index != -1, "Scan never finished" |
| 121 | + |
| 122 | + assert heartbeat_index < done_index, ( |
| 123 | + f"Heartbeat (pos {heartbeat_index}) should have arrived " |
| 124 | + f"before scan completion (pos {done_index})" |
| 125 | + ) |
| 126 | + |
| 127 | + heartbeat_data = json.loads(events[heartbeat_index].replace("data: ", "")) |
| 128 | + assert heartbeat_data["elapsed_s"] >= 5.0 |
| 129 | + |
| 130 | + |
| 131 | +@patch("inkwell.routes.api_scan._run_scan_with_emit") |
| 132 | +@pytest.mark.asyncio |
| 133 | +async def test_rapid_restart(mock_run, client): |
| 134 | + await client.post("/api/scan") |
| 135 | + response = await client.post("/api/scan") |
| 136 | + assert response.status_code == 200 # Should NOT be 409 |
| 137 | + |
| 138 | + |
| 139 | +# ------------------------------------------------------------------ |
| 140 | +# Tests for POST /api/scan/stop |
| 141 | +# ------------------------------------------------------------------ |
| 142 | + |
| 143 | + |
| 144 | +@pytest.mark.asyncio |
| 145 | +async def test_stop_scan_not_running(client): |
| 146 | + response = await client.post("/api/scan/stop") |
| 147 | + assert response.json() == {"ok": False, "detail": "No scan is running."} |
| 148 | + |
| 149 | + |
| 150 | +@pytest.mark.asyncio |
| 151 | +async def test_stop_scan_success(client): |
| 152 | + """Verify stop sets cancel flag and injects event into queue.""" |
| 153 | + mock_queue = Queue() |
| 154 | + _scan_state["running"] = True |
| 155 | + _scan_state["queue"] = mock_queue |
| 156 | + |
| 157 | + response = await client.post("/api/scan/stop") |
| 158 | + |
| 159 | + assert response.status_code == 200 |
| 160 | + assert response.json()["ok"] is True |
| 161 | + assert _scan_state["cancel"] is True |
| 162 | + |
| 163 | + # Verify the 'cancelled' event was pushed to wake up the SSE stream |
| 164 | + injected_event = mock_queue.get() |
| 165 | + assert injected_event["kind"] == "cancelled" |
0 commit comments