Files
the_kurgan/tests/test_web.py
T
paul f717f7a82f Long-term telemetry: hourly rollups in JSONL, a range selector in the UI
- telemetry/record.py: a Recorder subscribed to Telemetry keeps min/avg/max
  per metric for the current hour and appends each finished hour as one JSON
  line to records-YYYY-MM.jsonl in the data dir (~400 days kept; whole months
  older than that are pruned on start). Best effort by design: a failing disk
  logs once and stops recording; nothing else notices. load() merges lines per
  hour (a restart re-writes the current hour; torn last lines are skipped).
- app.py: the recorder runs unless --demo (simulated samples must not mix into
  real records) and flushes the open hour in close(), after the telemetry
  thread has stopped. records(days) validates 1..400.
- Web: GET /api/records?days=N (bad values answer 400 with the reason).
- UI: a range selector above the power/temperature charts switches them
  between the live 10 minutes and hourly averages for 24 h / 7 d / 30 d /
  1 y; the chart window, tick labels (min/h/d), tooltips and table captions
  adapt to the span. Live samples keep accumulating behind a long-range view,
  so switching back is instant.
- Tests: test_record.py (5) and a /api/records case in test_web.py; README
  updated (API table, System section, layout).
2026-12-05 18:04:57 +13:00

152 lines
6.3 KiB
Python

import http.client
import json
import socket
import unittest
from kurgan.web.server import WebServer
class FakeApp:
def __init__(self):
self.calls = []
def state(self):
return {"ok": True}
def history(self):
return {"rows": []}
def config(self):
return {"profiles": []}
def set_lighting(self, zone, mode):
self.calls.append(("lighting", zone, mode))
if mode == "rainbow":
raise ValueError("Unknown lighting mode")
def set_fan_profile(self, profile):
self.calls.append(("profile", profile))
if profile == "full-disk":
raise OSError("disk full")
def set_ai(self, backend, variant):
self.calls.append(("ai", backend, variant))
def ai_model(self, action):
self.calls.append(("model", action))
def records(self, days):
self.calls.append(("records", days))
if not 1 <= days <= 400:
raise ValueError("days must be a whole number from 1 to 400")
return {"metrics": [], "rows": [], "days": days}
def free_port() -> int:
with socket.socket() as s:
s.bind(("127.0.0.1", 0))
return s.getsockname()[1]
class WebServerTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.app = FakeApp()
cls.port = free_port()
cls.server = WebServer(cls.app, cls.port)
cls.server.start()
@classmethod
def tearDownClass(cls):
cls.server.close()
def setUp(self):
self.app.calls.clear()
def request(self, method, path, body=None, headers=None, host=None):
connection = http.client.HTTPConnection("127.0.0.1", self.port, timeout=5)
try:
data = body if isinstance(body, (bytes, type(None))) else json.dumps(body).encode()
base = {"Host": host or f"127.0.0.1:{self.port}"}
if method == "POST":
base.update({"Content-Type": "application/json", "X-Kurgan": "1"})
base.update(headers or {})
connection.request(method, path, body=data, headers={k: v for k, v in base.items() if v is not None})
response = connection.getresponse()
return response.status, response.getheader("Content-Type"), response.read()
finally:
connection.close()
def test_api_and_ui_are_served(self):
status, kind, body = self.request("GET", "/api/state")
self.assertEqual((status, json.loads(body)), (200, {"ok": True}))
status, kind, body = self.request("GET", "/", host=f"localhost:{self.port}")
self.assertEqual(status, 200)
self.assertTrue(kind.startswith("text/html"))
self.assertIn(b"THE KURGAN", body)
status, kind, _ = self.request("GET", "/static/app.js")
self.assertEqual(status, 200)
self.assertIn("javascript", kind)
def test_only_files_in_static_are_served(self):
for path in ("/static/../server.py", "/static/..%2Fserver.py", "/static/missing.js", "/server.py"):
with self.subTest(path=path):
self.assertEqual(self.request("GET", path)[0], 404)
def test_foreign_host_is_refused(self): # DNS rebinding
self.assertEqual(self.request("GET", "/api/state", host="attacker.example")[0], 403)
self.assertEqual(self.request("POST", "/api/ai/model", {"action": "load"}, host="attacker.example")[0], 403)
self.assertEqual(self.app.calls, [])
def test_posts_need_the_header_json_and_our_origin(self):
refused = (({"X-Kurgan": None}, 403), ({"Origin": "https://attacker.example"}, 403),
({"Content-Type": "text/plain"}, 415))
for headers, expected in refused:
with self.subTest(headers=headers):
status, _, _ = self.request("POST", "/api/cooling/profile", {"profile": "quiet"}, headers)
self.assertEqual(status, expected)
self.assertEqual(self.app.calls, [])
status, _, body = self.request("POST", "/api/cooling/profile", {"profile": "quiet"},
{"Origin": f"http://127.0.0.1:{self.port}"})
self.assertEqual((status, json.loads(body)), (200, {"ok": True}))
self.assertEqual(self.app.calls, [("profile", "quiet")])
def test_bad_bodies_and_failures_report_errors(self):
cases = (("/api/lighting", {"zone": "gpu"}, 400, "mode is required"),
("/api/lighting", {"zone": "gpu", "mode": "rainbow"}, 400, "Unknown lighting mode"),
("/api/lighting", [1, 2], 400, "JSON object"),
("/api/lighting", b"{nope", 400, None),
("/api/lighting", b"x" * 20000, 400, "oversized"),
("/api/ai/active", {"backend": 3}, 400, "string or null"),
("/api/cooling/profile", {"profile": "full-disk"}, 500, "disk full"),
("/api/fans", {"x": 1}, 404, None))
for path, body, expected, message in cases:
with self.subTest(path=path, body=body):
status, _, raw = self.request("POST", path, body)
self.assertEqual(status, expected)
if message:
self.assertIn(message, json.loads(raw)["error"])
def test_ai_choice_allows_none(self):
status, _, _ = self.request("POST", "/api/ai/active", {"backend": None})
self.assertEqual(status, 200)
self.request("POST", "/api/ai/active", {"backend": "strata", "variant": "iq3"})
self.assertEqual(self.app.calls, [("ai", None, None), ("ai", "strata", "iq3")])
def test_records_serves_the_long_term_rollups(self):
status, _, body = self.request("GET", "/api/records") # no days: the default week
self.assertEqual((status, json.loads(body)["days"]), (200, 7))
status, _, body = self.request("GET", "/api/records?days=30")
self.assertEqual((status, json.loads(body)["days"]), (200, 30))
self.assertEqual(self.app.calls, [("records", 7), ("records", 30)])
for path in ("/api/records?days=abc", "/api/records?days=0", "/api/records?days=-3",
"/api/records?days=401", "/api/records?days=1.5"):
with self.subTest(path=path):
status, _, raw = self.request("GET", path)
self.assertEqual(status, 400)
self.assertIn("whole number", json.loads(raw)["error"])
if __name__ == "__main__":
unittest.main()