|
| 1 | +"""Tests for ``modules.demo.router`` (issue #29 / M4.7 memory flex scene). |
| 2 | +
|
| 3 | +Covers the handler's SQL orchestration without touching a live database: |
| 4 | +
|
| 5 | +- Returns 404 when the cell does not exist. |
| 6 | +- Returns 400 when the cell has no vibration signal_def mapped to |
| 7 | + ``kb_threshold_key='vibration_mm_s'``. |
| 8 | +- Happy path inside a transaction: DELETE recent failure_history, INSERT |
| 9 | + one past failure, CANCEL open agent WOs, INSERT the burst of fresh |
| 10 | + readings, returns the expected envelope. |
| 11 | +""" |
| 12 | + |
| 13 | +from __future__ import annotations |
| 14 | + |
| 15 | +from typing import Any |
| 16 | + |
| 17 | +import pytest |
| 18 | +from modules.demo import router as demo_router |
| 19 | + |
| 20 | + |
| 21 | +# --------------------------------------------------------------------------- |
| 22 | +# Fake asyncpg.Connection surface — only the methods the handler uses. |
| 23 | +# --------------------------------------------------------------------------- |
| 24 | + |
| 25 | + |
| 26 | +class _FakeTxn: |
| 27 | + async def __aenter__(self) -> "_FakeTxn": |
| 28 | + return self |
| 29 | + |
| 30 | + async def __aexit__(self, *a: Any) -> None: |
| 31 | + return None |
| 32 | + |
| 33 | + |
| 34 | +class _FakeConn: |
| 35 | + def __init__( |
| 36 | + self, |
| 37 | + *, |
| 38 | + cell_row: dict[str, Any] | None, |
| 39 | + sig_row: dict[str, Any] | None, |
| 40 | + past_id: int = 77, |
| 41 | + ) -> None: |
| 42 | + self._cell_row = cell_row |
| 43 | + self._sig_row = sig_row |
| 44 | + self._past_id = past_id |
| 45 | + self.fetchrow_calls: list[tuple[str, tuple[Any, ...]]] = [] |
| 46 | + self.execute_calls: list[tuple[str, tuple[Any, ...]]] = [] |
| 47 | + |
| 48 | + def transaction(self) -> _FakeTxn: |
| 49 | + return _FakeTxn() |
| 50 | + |
| 51 | + async def fetchrow(self, query: str, *args: Any) -> dict[str, Any] | None: |
| 52 | + self.fetchrow_calls.append((query, args)) |
| 53 | + q = " ".join(query.split()) |
| 54 | + if "FROM cell WHERE name" in q: |
| 55 | + return self._cell_row |
| 56 | + if "FROM process_signal_definition" in q: |
| 57 | + return self._sig_row |
| 58 | + if "INSERT INTO failure_history" in q: |
| 59 | + return {"id": self._past_id} |
| 60 | + return None |
| 61 | + |
| 62 | + async def execute(self, query: str, *args: Any) -> str: |
| 63 | + self.execute_calls.append((query, args)) |
| 64 | + q = " ".join(query.split()) |
| 65 | + if "DELETE FROM failure_history" in q: |
| 66 | + return "DELETE 0" |
| 67 | + if "UPDATE work_order" in q: |
| 68 | + return "UPDATE 1" |
| 69 | + if "INSERT INTO process_signal_data" in q: |
| 70 | + return "INSERT 0 1" |
| 71 | + return "OK" |
| 72 | + |
| 73 | + |
| 74 | +# --------------------------------------------------------------------------- |
| 75 | +# Tests |
| 76 | +# --------------------------------------------------------------------------- |
| 77 | + |
| 78 | + |
| 79 | +@pytest.mark.asyncio |
| 80 | +async def test_returns_404_when_cell_missing() -> None: |
| 81 | + conn = _FakeConn(cell_row=None, sig_row=None) |
| 82 | + with pytest.raises(Exception) as excinfo: |
| 83 | + await demo_router.trigger_memory_scene( |
| 84 | + cell_name="UNKNOWN-99", conn=conn # type: ignore[arg-type] |
| 85 | + ) |
| 86 | + # FastAPI HTTPException — inspect via attribute. |
| 87 | + assert getattr(excinfo.value, "status_code", None) == 404 |
| 88 | + |
| 89 | + |
| 90 | +@pytest.mark.asyncio |
| 91 | +async def test_returns_400_when_signal_def_missing() -> None: |
| 92 | + conn = _FakeConn(cell_row={"id": 2}, sig_row=None) |
| 93 | + with pytest.raises(Exception) as excinfo: |
| 94 | + await demo_router.trigger_memory_scene( |
| 95 | + cell_name="P-02", conn=conn # type: ignore[arg-type] |
| 96 | + ) |
| 97 | + assert getattr(excinfo.value, "status_code", None) == 400 |
| 98 | + # Nothing written when signal lookup fails (we return before the txn). |
| 99 | + assert conn.execute_calls == [] |
| 100 | + |
| 101 | + |
| 102 | +@pytest.mark.asyncio |
| 103 | +async def test_happy_path_orchestrates_all_four_steps() -> None: |
| 104 | + conn = _FakeConn(cell_row={"id": 2}, sig_row={"id": 55}, past_id=99) |
| 105 | + |
| 106 | + resp = await demo_router.trigger_memory_scene( |
| 107 | + cell_name="P-02", conn=conn # type: ignore[arg-type] |
| 108 | + ) |
| 109 | + |
| 110 | + assert resp["ok"] is True |
| 111 | + assert resp["cell_id"] == 2 |
| 112 | + assert resp["cell_name"] == "P-02" |
| 113 | + assert resp["past_failure_id"] == 99 |
| 114 | + assert resp["signal_def_id"] == 55 |
| 115 | + # 5 readings seeded by the handler. |
| 116 | + assert resp["readings_inserted"] == 5 |
| 117 | + assert resp["expect_anomaly_within_seconds"] == 35 |
| 118 | + |
| 119 | + # Step order inside the txn: DELETE, (fetchrow INSERT failure), UPDATE, |
| 120 | + # then 5 x INSERT process_signal_data. |
| 121 | + exec_queries = [" ".join(q.split()) for q, _ in conn.execute_calls] |
| 122 | + assert any(q.startswith("DELETE FROM failure_history") for q in exec_queries) |
| 123 | + assert any(q.startswith("UPDATE work_order") for q in exec_queries) |
| 124 | + readings_inserts = [q for q in exec_queries if "INSERT INTO process_signal_data" in q] |
| 125 | + assert len(readings_inserts) == 5 |
| 126 | + |
| 127 | + |
| 128 | +@pytest.mark.asyncio |
| 129 | +async def test_happy_path_past_failure_row_carries_signal_patterns_jsonb() -> None: |
| 130 | + conn = _FakeConn(cell_row={"id": 2}, sig_row={"id": 55}) |
| 131 | + |
| 132 | + await demo_router.trigger_memory_scene( |
| 133 | + cell_name="P-02", conn=conn # type: ignore[arg-type] |
| 134 | + ) |
| 135 | + |
| 136 | + insert_calls = [ |
| 137 | + (q, args) |
| 138 | + for q, args in conn.fetchrow_calls |
| 139 | + if "INSERT INTO failure_history" in " ".join(q.split()) |
| 140 | + ] |
| 141 | + assert len(insert_calls) == 1 |
| 142 | + _, args = insert_calls[0] |
| 143 | + # args[0] = cell_id, args[1] = jsonb string |
| 144 | + assert args[0] == 2 |
| 145 | + import json as _json |
| 146 | + |
| 147 | + patterns = _json.loads(args[1]) |
| 148 | + assert "vibration_mm_s" in patterns |
| 149 | + assert patterns["vibration_mm_s"]["peak"] == pytest.approx(5.4) |
| 150 | + |
| 151 | + |
| 152 | +@pytest.mark.asyncio |
| 153 | +async def test_readings_all_above_alert_threshold() -> None: |
| 154 | + conn = _FakeConn(cell_row={"id": 2}, sig_row={"id": 55}) |
| 155 | + await demo_router.trigger_memory_scene( |
| 156 | + cell_name="P-02", conn=conn # type: ignore[arg-type] |
| 157 | + ) |
| 158 | + # All seeded readings must exceed the P-02 vibration alert (4.5 mm/s) |
| 159 | + # otherwise Sentinel will not open a work_order and the scene dies. |
| 160 | + reading_values = [ |
| 161 | + args[-1] |
| 162 | + for q, args in conn.execute_calls |
| 163 | + if "INSERT INTO process_signal_data" in " ".join(q.split()) |
| 164 | + ] |
| 165 | + assert reading_values # at least one |
| 166 | + assert all(v > 4.5 for v in reading_values) |
0 commit comments