The Kurgan 1.0.0: one process for the LCD, fans, lighting, local LLM servers and the web UI
This commit is contained in:
commit
f631386618
71 files changed
+14616
No files matched your search
@@ -0,0 +1,350 @@
|
||||
import os
|
||||
import tempfile
|
||||
import threading
|
||||
import unittest
|
||||
from unittest.mock import patch
|
||||
|
||||
from kurgan.ai import launcher
|
||||
from kurgan.ai.backends import Backend, LlamaLog
|
||||
from kurgan.ai.service import CLIENT_GONE, AiService, RouteError
|
||||
from kurgan.settings import Settings
|
||||
|
||||
LLAMA_REQUEST = """\
|
||||
slot launch_slot_: id 0 | task 12 | processing task
|
||||
slot update_slots: id 0 | task 12 | prompt processing, n_tokens = 2048, progress = 0.5, t = 1.2 s / 1706.7 tokens per second
|
||||
slot update_slots: id 0 | task 12 | prompt processing, n_tokens = 4096, progress = 1.0, t = 2.4 s / 1706.7 tokens per second
|
||||
slot process_toke: id 0 | task 12 | n_gen = 100, tg = 95.2 t/s, tg_3s = 97.1 t/s
|
||||
slot print_timing: id 0 | task 12 | prompt eval time = 2400.00 ms / 4096 tokens ( 0.59 ms per token, 1706.67 tokens per second)
|
||||
slot print_timing: id 0 | task 12 | eval time = 5000.00 ms / 500 tokens ( 10.00 ms per token, 100.00 tokens per second)
|
||||
slot release: id 0 | task 12 | stop processing: n_tokens = 5096, truncated = 0
|
||||
"""
|
||||
|
||||
|
||||
class LlamaLogTest(unittest.TestCase):
|
||||
def test_request_in_progress_and_finished(self):
|
||||
parser = LlamaLog()
|
||||
lines = LLAMA_REQUEST.splitlines()
|
||||
for line in lines[:2]:
|
||||
parser.feed(line, now=1000.0)
|
||||
live, requests, _ = parser.snapshot()
|
||||
self.assertEqual((live["phase"], live["progress"], live["read"], live["tok_s"]), ("reading", 0.5, 2048, 1706.7))
|
||||
self.assertEqual(requests, [])
|
||||
parser.feed(lines[3], now=1003.0)
|
||||
live, _, _ = parser.snapshot()
|
||||
self.assertEqual((live["phase"], live["generated"], live["tok_s"]), ("generating", 100, 97.1))
|
||||
for line in lines[4:]:
|
||||
parser.feed(line, now=1008.0)
|
||||
live, requests, averages = parser.snapshot()
|
||||
self.assertIsNone(live)
|
||||
self.assertEqual(len(requests), 1)
|
||||
r = requests[0]
|
||||
self.assertEqual((r["status"], r["prompt"], r["reused"], r["output"], r["duration"]), ("ok", 4596, 500, 500, 8.0))
|
||||
self.assertEqual((r["prefill_tps"], r["decode_tps"]), (1706.67, 100.0))
|
||||
self.assertEqual(averages, {"prefill_tps": 1706.7, "decode_tps": 100.0, "requests": 1})
|
||||
|
||||
def test_unrelated_lines_and_lines_before_a_task_are_ignored(self):
|
||||
parser = LlamaLog()
|
||||
parser.feed("srv log_server_r: request: GET /models 127.0.0.1 200")
|
||||
parser.feed("slot update_slots: id 0 | task 3 | n_gen = 5, tg = 1.0 t/s, tg_3s = 1.0 t/s")
|
||||
self.assertEqual(parser.snapshot(), (None, [], {"prefill_tps": None, "decode_tps": None, "requests": 0}))
|
||||
|
||||
|
||||
class FakeChild:
|
||||
def __init__(self, argv):
|
||||
self.argv = argv
|
||||
self.pid = 4000 + len(argv[0])
|
||||
self.token = {"integrity": "medium", "elevated": False}
|
||||
self.code = None
|
||||
|
||||
def poll(self):
|
||||
return self.code
|
||||
|
||||
def wait(self, timeout=None):
|
||||
return self.code
|
||||
|
||||
def kill(self):
|
||||
if self.code is None:
|
||||
self.code = 1
|
||||
|
||||
def close(self):
|
||||
pass
|
||||
|
||||
|
||||
class FakeBackend(Backend):
|
||||
stop_timeout = 0.1
|
||||
|
||||
def __init__(self, settings, key, port, events):
|
||||
self.key, self.label, self._port, self.events = key, key.capitalize(), port, events
|
||||
super().__init__(settings)
|
||||
|
||||
@property
|
||||
def port(self):
|
||||
return self._port
|
||||
|
||||
def variant(self):
|
||||
return self.settings.get("ai", "strata_model") if self.key == "strata" else None
|
||||
|
||||
def model_label(self):
|
||||
return f"{self.key} model"
|
||||
|
||||
def command(self):
|
||||
return [self.key], ".", None
|
||||
|
||||
def request_stop(self, child):
|
||||
self.events.append(("stop", self.key))
|
||||
child.code = 0
|
||||
|
||||
|
||||
class AiServiceTest(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.dir = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(self.dir.cleanup)
|
||||
self.settings = Settings(os.path.join(self.dir.name, "settings.json"), None)
|
||||
self.events = []
|
||||
self.children = []
|
||||
self.service = AiService(self.settings, [FakeBackend(self.settings, "strata", 18082, self.events),
|
||||
FakeBackend(self.settings, "llama", 18083, self.events)])
|
||||
self.external_ports = set()
|
||||
self.clock = [1000.0]
|
||||
|
||||
def launch(argv, cwd, log_path):
|
||||
self.events.append(("start", argv[0]))
|
||||
self.children.append(FakeChild(argv))
|
||||
return self.children[-1]
|
||||
|
||||
for target, fake in (("kurgan.ai.service.launcher.launch", launch),
|
||||
("kurgan.ai.service.port_in_use", lambda port: port in self.external_ports),
|
||||
("kurgan.ai.service.port_owner", lambda port: (1234, "pythonw.exe")),
|
||||
("kurgan.ai.service.time.monotonic", lambda: self.clock[0])):
|
||||
patcher = patch(target, side_effect=fake)
|
||||
patcher.start()
|
||||
self.addCleanup(patcher.stop)
|
||||
self.stop = threading.Event()
|
||||
|
||||
def reconcile(self):
|
||||
self.service._reconcile(self.stop)
|
||||
|
||||
def processes(self):
|
||||
return {b["key"]: b["process"] for b in self.service.snapshot()["backends"]}
|
||||
|
||||
def test_swapping_stops_the_running_server_before_starting_the_other(self):
|
||||
self.reconcile()
|
||||
self.assertEqual(self.events, [])
|
||||
self.service.set_active("llama")
|
||||
self.reconcile()
|
||||
self.service.set_active("strata", "iq3")
|
||||
self.reconcile()
|
||||
self.assertEqual(self.events, [("start", "llama"), ("stop", "llama"), ("start", "strata")])
|
||||
self.assertEqual(self.settings.get("ai", "strata_model"), "iq3")
|
||||
self.service.set_active("strata", "q5") # another Strata model: restart it
|
||||
self.reconcile()
|
||||
self.service.set_active(None)
|
||||
self.reconcile()
|
||||
self.assertEqual(self.events[3:], [("stop", "strata"), ("start", "strata"), ("stop", "strata")])
|
||||
self.assertEqual(self.processes(), {"strata": "stopped", "llama": "stopped"})
|
||||
|
||||
def test_unknown_backend_or_variant_is_rejected_and_not_saved(self):
|
||||
with self.assertRaises(ValueError):
|
||||
self.service.set_active("ollama")
|
||||
with self.assertRaises(ValueError):
|
||||
self.service.set_active("strata", "q8")
|
||||
self.assertIsNone(self.settings.get("ai", "active"))
|
||||
|
||||
def test_crashes_restart_after_a_pause_and_repeated_crashes_hold_off(self):
|
||||
self.service.set_active("llama")
|
||||
self.reconcile()
|
||||
for crash in range(4):
|
||||
self.children[-1].code = 3
|
||||
self.reconcile()
|
||||
self.assertEqual(len(self.children), crash + 1, "no restart during the 5 s pause")
|
||||
self.assertIn("exited (code 3); restarting", self.service.snapshot()["backends"][1]["error"])
|
||||
self.clock[0] += 6
|
||||
self.reconcile()
|
||||
self.assertEqual(len(self.children), crash + 2)
|
||||
self.children[-1].code = 3
|
||||
self.reconcile()
|
||||
self.clock[0] += 60
|
||||
self.reconcile()
|
||||
self.assertEqual(len(self.children), 5)
|
||||
self.assertIn("keeps exiting", self.service.snapshot()["backends"][1]["error"])
|
||||
self.clock[0] += 300
|
||||
self.reconcile()
|
||||
self.assertEqual(len(self.children), 6)
|
||||
|
||||
def test_a_server_started_elsewhere_is_watched_not_duplicated(self):
|
||||
self.external_ports.add(18082)
|
||||
self.service.set_active("strata")
|
||||
self.reconcile()
|
||||
self.assertEqual(self.events, [])
|
||||
snap = self.service.snapshot()
|
||||
self.assertEqual((snap["backends"][0]["process"], snap["backends"][0]["pid"]), ("external", 1234))
|
||||
self.service.set_active("llama")
|
||||
self.reconcile()
|
||||
self.assertEqual(self.events, [("start", "llama")])
|
||||
self.assertIn("Strata is also running outside The Kurgan", self.service.snapshot()["warning"])
|
||||
self.service.set_active(None)
|
||||
self.reconcile()
|
||||
self.assertIn("Strata is running outside The Kurgan, from its own startup task",
|
||||
self.service.snapshot()["warning"])
|
||||
|
||||
def claim_in_background(self, key):
|
||||
result = {}
|
||||
|
||||
def run():
|
||||
try:
|
||||
result["backend"] = self.service.claim(key)
|
||||
except Exception as e:
|
||||
result["error"] = e
|
||||
|
||||
thread = threading.Thread(target=run, daemon=True)
|
||||
thread.start()
|
||||
return thread, result
|
||||
|
||||
def serve(self, key, port):
|
||||
"""Let the supervisor start key's server and have it 'listen'."""
|
||||
for _ in range(100):
|
||||
if self.settings.get("ai", "active") == key:
|
||||
break
|
||||
threading.Event().wait(0.02)
|
||||
self.reconcile()
|
||||
self.external_ports.add(port)
|
||||
|
||||
def test_a_request_starts_its_server_once_the_other_is_idle(self):
|
||||
self.service.set_active("llama")
|
||||
self.reconcile()
|
||||
thread, result = self.claim_in_background("strata")
|
||||
self.serve("strata", 18082)
|
||||
thread.join(5)
|
||||
self.assertEqual(result["backend"].key, "strata")
|
||||
self.assertEqual(self.events, [("start", "llama"), ("stop", "llama"), ("start", "strata")])
|
||||
self.assertEqual(self.service.inflight["strata"], 1)
|
||||
self.service.release("strata")
|
||||
self.assertEqual(self.service.inflight["strata"], 0)
|
||||
# The selected server's own requests go straight through.
|
||||
self.assertEqual(self.service.claim("strata").key, "strata")
|
||||
self.service.release("strata")
|
||||
|
||||
def test_a_request_waits_while_the_other_server_is_busy(self):
|
||||
self.service.set_active("llama")
|
||||
self.reconcile()
|
||||
self.external_ports.add(18083)
|
||||
self.service.claim("llama") # a reply in progress
|
||||
thread, result = self.claim_in_background("strata")
|
||||
thread.join(0.3)
|
||||
self.assertTrue(thread.is_alive())
|
||||
self.assertEqual(self.settings.get("ai", "active"), "llama")
|
||||
self.service.release("llama")
|
||||
self.external_ports.discard(18083)
|
||||
self.serve("strata", 18082)
|
||||
thread.join(5)
|
||||
self.assertEqual(result["backend"].key, "strata")
|
||||
|
||||
def test_a_request_gives_up_if_the_other_server_stays_busy(self):
|
||||
self.service.set_active("llama")
|
||||
self.reconcile()
|
||||
self.external_ports.add(18083)
|
||||
self.service.claim("llama")
|
||||
thread, result = self.claim_in_background("strata")
|
||||
thread.join(0.2)
|
||||
self.clock[0] += AiService.BUSY_WAIT + 1
|
||||
with self.service._cv:
|
||||
self.service._cv.notify_all()
|
||||
thread.join(5)
|
||||
self.assertIn("still busy", str(result["error"]))
|
||||
self.assertEqual(self.service.inflight, {"strata": 0, "llama": 1})
|
||||
|
||||
def test_a_request_whose_client_hangs_up_never_switches_servers(self):
|
||||
self.service.set_active("llama")
|
||||
self.reconcile()
|
||||
self.external_ports.add(18083)
|
||||
self.service.claim("llama") # llama busy
|
||||
hung_up = threading.Event()
|
||||
result = {}
|
||||
|
||||
def run():
|
||||
try:
|
||||
self.service.claim("strata", gone=hung_up.is_set)
|
||||
except RouteError as e:
|
||||
result["error"] = e
|
||||
|
||||
thread = threading.Thread(target=run, daemon=True)
|
||||
thread.start()
|
||||
thread.join(0.2)
|
||||
hung_up.set()
|
||||
self.service.release("llama") # llama now idle: a live request would switch here
|
||||
thread.join(5)
|
||||
self.assertEqual((result["error"].status, str(result["error"])), (CLIENT_GONE, "while waiting for Llama to finish"))
|
||||
self.assertEqual(self.settings.get("ai", "active"), "llama")
|
||||
self.assertEqual(self.service.inflight, {"strata": 0, "llama": 0})
|
||||
|
||||
# Hanging up while its own server starts also gives the place back.
|
||||
self.external_ports.clear() # llama's port closes when it stops
|
||||
self.service.set_active(None)
|
||||
self.reconcile()
|
||||
answers = iter([False] + [True] * 10) # still there when it asks for llama; gone while it starts
|
||||
with self.assertRaises(RouteError) as caught:
|
||||
self.service.claim("llama", gone=lambda: next(answers))
|
||||
self.assertEqual((caught.exception.status, str(caught.exception)), (CLIENT_GONE, "while waiting for Llama to start"))
|
||||
self.assertEqual(self.service.inflight["llama"], 0)
|
||||
|
||||
def test_an_unused_server_stops_after_the_idle_time(self):
|
||||
self.service.set_active("llama")
|
||||
self.reconcile()
|
||||
self.assertEqual(self.service.snapshot()["backends"][1]["idle_stop_in"], 40 * 60)
|
||||
self.clock[0] += 39 * 60
|
||||
self.reconcile()
|
||||
self.assertEqual(self.processes()["llama"], "starting")
|
||||
self.assertEqual(self.service.snapshot()["backends"][1]["idle_stop_in"], 60)
|
||||
self.service.inflight["llama"] = 1 # a long request keeps it running
|
||||
self.clock[0] += 5 * 60
|
||||
self.reconcile()
|
||||
self.assertEqual(self.processes()["llama"], "starting")
|
||||
self.service.release("llama")
|
||||
self.clock[0] += 40 * 60 + 1
|
||||
self.reconcile()
|
||||
self.assertEqual(self.processes()["llama"], "stopped")
|
||||
self.assertIsNone(self.settings.get("ai", "active"))
|
||||
self.settings.update("ai", idle_stop_minutes=0) # never
|
||||
self.service.set_active("llama")
|
||||
self.reconcile()
|
||||
self.clock[0] += 24 * 3600
|
||||
self.reconcile()
|
||||
self.assertEqual(self.processes()["llama"], "starting")
|
||||
|
||||
|
||||
class LauncherTest(unittest.TestCase):
|
||||
def test_child_runs_as_a_normal_user_with_its_output_logged(self):
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
log_path = os.path.join(directory, "logs", "child.log")
|
||||
child = launcher.launch(["cmd.exe", "/d", "/c", "echo hello from the child& exit 7"], directory, log_path)
|
||||
try:
|
||||
self.assertEqual(child.wait(10), 7)
|
||||
self.assertEqual(child.token, {"integrity": "medium", "elevated": False})
|
||||
finally:
|
||||
child.close()
|
||||
with open(log_path, encoding="utf-8", errors="replace") as f:
|
||||
self.assertIn("hello from the child", f.read())
|
||||
|
||||
def test_kill_ends_the_whole_job(self):
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
child = launcher.launch(["cmd.exe", "/d", "/c", "ping -n 30 127.0.0.1"], directory, None)
|
||||
try:
|
||||
self.assertIsNone(child.poll())
|
||||
child.kill()
|
||||
self.assertIsNotNone(child.wait(10))
|
||||
finally:
|
||||
child.close()
|
||||
|
||||
def test_pinned_openblas_setting_is_not_passed_on(self):
|
||||
with patch.dict(os.environ, {"OPENBLAS_NUM_THREADS": "1", "KURGAN_PINNED_OPENBLAS": "1"}):
|
||||
env = launcher.child_environment({"EXTRA": "x"})
|
||||
self.assertNotIn("OPENBLAS_NUM_THREADS", env)
|
||||
self.assertNotIn("KURGAN_PINNED_OPENBLAS", env)
|
||||
self.assertEqual(env["EXTRA"], "x")
|
||||
with patch.dict(os.environ, {"OPENBLAS_NUM_THREADS": "4"}):
|
||||
os.environ.pop("KURGAN_PINNED_OPENBLAS", None)
|
||||
self.assertEqual(launcher.child_environment()["OPENBLAS_NUM_THREADS"], "4")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,79 @@
|
||||
import unittest
|
||||
from unittest.mock import patch
|
||||
|
||||
from PIL import Image
|
||||
|
||||
from kurgan.display.renderer import DashboardRenderer, H, MHZ_BOX, PART_BOX, SS, W
|
||||
from kurgan.telemetry.readings import PowerReadings, Readings
|
||||
|
||||
|
||||
class DashboardLayoutTest(unittest.TestCase):
|
||||
def test_background_is_fitted_and_gauges_are_drawn_on_top(self):
|
||||
background = Image.new("RGB", (20, 10), (160, 12, 24))
|
||||
with patch("kurgan.display.renderer.Image.open", side_effect=lambda path: background.copy()) as opened:
|
||||
renderer = DashboardRenderer()
|
||||
plate = renderer._plate()
|
||||
self.assertTrue(opened.call_args.args[0].endswith("background.png"))
|
||||
self.assertEqual(renderer._static.size, (W * SS, H * SS))
|
||||
self.assertEqual(plate.getpixel((240 * SS, 10 * SS))[:3], (160, 12, 24))
|
||||
self.assertNotEqual(renderer._static.getpixel((52 * SS, 66 * SS))[:3], (160, 12, 24))
|
||||
|
||||
def test_inner_gauges_leave_clear_gaps_to_power_tank(self):
|
||||
renderer = DashboardRenderer()
|
||||
plate = renderer._plate()
|
||||
for x in (211, 269):
|
||||
with self.subTest(x=x):
|
||||
position = (x * SS, 66 * SS)
|
||||
for actual, background in zip(renderer._static.getpixel(position), plate.getpixel(position)):
|
||||
self.assertAlmostEqual(actual, background, delta=3)
|
||||
|
||||
def test_device_readings_ranges_and_power_follow_swapped_sides(self):
|
||||
renderer = DashboardRenderer()
|
||||
cpu = Readings(temp=80, load=25, clock=4200, power=85)
|
||||
gpu = Readings(temp=55, load=75, clock=2700, power=300)
|
||||
power = PowerReadings(cpu=85, gpu=300, other=40)
|
||||
with patch.object(renderer, "_arc_fill") as arcs, \
|
||||
patch.object(renderer, "_digits") as digits, \
|
||||
patch.object(renderer, "_readout") as readouts:
|
||||
renderer.render(cpu, gpu, power)
|
||||
|
||||
self.assertEqual(
|
||||
[call.args[2:6] for call in arcs.call_args_list],
|
||||
[(52.0, 66.0, 0.5, False), (152.0, 66.0, 0.75, False),
|
||||
(428.0, 66.0, 0.75, False), (328.0, 66.0, 0.25, False)],
|
||||
)
|
||||
self.assertEqual(
|
||||
[call.args[2:] for call in digits.call_args_list],
|
||||
[(52.0, 62.0, 55), (152.0, 62.0, 75),
|
||||
(428.0, 62.0, 80), (328.0, 62.0, 25)],
|
||||
)
|
||||
self.assertEqual(
|
||||
[call.args[1:] for call in readouts.call_args_list[:4]],
|
||||
[(renderer.halves[0].box(MHZ_BOX), 2700, "MHz"),
|
||||
(renderer.halves[1].box(MHZ_BOX), 4200, "MHz"),
|
||||
(renderer.halves[0].box(PART_BOX), 300, "W"),
|
||||
(renderer.halves[1].box(PART_BOX), 85, "W")],
|
||||
)
|
||||
self.assertEqual(readouts.call_args_list[2].kwargs["swatch"], renderer.theme.gpu_color)
|
||||
self.assertEqual(readouts.call_args_list[3].kwargs["swatch"], renderer.theme.cpu_color)
|
||||
|
||||
def test_glass_domes_reflect_upper_left_of_each_gauge_and_keep_digits_clear(self):
|
||||
renderer = DashboardRenderer()
|
||||
readings = Readings(temp=60, load=50, clock=3000, power=100)
|
||||
with_glass = renderer.render(readings, readings)
|
||||
renderer._dome_light[:] = 0
|
||||
renderer._dome_shade[:] = 1
|
||||
bare = renderer.render(readings, readings)
|
||||
|
||||
def lum(img, xy):
|
||||
return sum(img.getpixel(xy))
|
||||
|
||||
for cx in (52, 152, 328, 428):
|
||||
with self.subTest(gauge=cx):
|
||||
self.assertGreater(lum(with_glass, (cx - 16, 43)), lum(bare, (cx - 16, 43)) + 150)
|
||||
self.assertLess(abs(lum(with_glass, (cx, 62)) - lum(bare, (cx, 62))), 40)
|
||||
self.assertEqual(with_glass.getpixel((240, 4)), bare.getpixel((240, 4)))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,320 @@
|
||||
import argparse
|
||||
import contextlib
|
||||
import threading
|
||||
import unittest
|
||||
from unittest.mock import Mock, call, mock_open, patch
|
||||
|
||||
from kurgan.cooling.board_fans import Nct6687
|
||||
from kurgan.cooling.control import CaseFanControl, CpuTemperature, TopFanCurve, cpu_duty, gpu_duty, parse_ports
|
||||
from kurgan.telemetry.sensors import CommanderPro, corsair_software_running
|
||||
|
||||
|
||||
class FanCurveTest(unittest.TestCase):
|
||||
def test_cpu_curve_and_failsafe(self):
|
||||
for temp, expected in ((30, 40), (50, 40), (60, 50), (70, 65), (75, 83), (80, 100),
|
||||
(88, 100), (100, 100), (None, 100), (float("nan"), 100)):
|
||||
with self.subTest(temp=temp):
|
||||
self.assertEqual(cpu_duty(temp), expected)
|
||||
|
||||
def test_temperature_curve_and_failsafe(self):
|
||||
for temp, expected in ((20, 40), (40, 40), (50, 50), (55, 58), (60, 65),
|
||||
(68, 93), (70, 100), (75, 100), (95, 100),
|
||||
(None, 100), (float("nan"), 100),
|
||||
(float("inf"), 100), (-1, 100), (111, 100)):
|
||||
with self.subTest(temp=temp):
|
||||
self.assertEqual(gpu_duty(temp), expected)
|
||||
|
||||
def test_only_three_distinct_physical_ports_are_accepted(self):
|
||||
self.assertEqual(parse_ports(" 4, 6, 5 "), (4, 6, 5))
|
||||
for text in ("", "1,2", "1,2,3,4", "1,1,2", "0,1,2", "4,5,7", "a,2,3"):
|
||||
with self.subTest(text=text):
|
||||
with self.assertRaises(argparse.ArgumentTypeError):
|
||||
parse_ports(text)
|
||||
|
||||
|
||||
class TopFanCurveTest(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.board = Mock(spec=Nct6687)
|
||||
self.mask = 0
|
||||
self.duties = []
|
||||
self.board.manual_mask.side_effect = lambda: self.mask
|
||||
|
||||
def manual(ch, duty):
|
||||
self.mask |= 0x24
|
||||
self.duties.append(duty)
|
||||
self.board.set_manual.side_effect = manual
|
||||
self.board.set_auto.side_effect = lambda ch: setattr(self, "mask", self.mask & ~0x24)
|
||||
self.top = TopFanCurve((2, 5), board_factory=lambda: self.board)
|
||||
|
||||
def test_stopped_while_cool_kicks_on_start_and_follows_curve(self):
|
||||
self.top.update(40, 44, 0)
|
||||
self.assertEqual((self.top.duty, self.mask), (0, 0x24))
|
||||
self.top.update(40, 49, 1)
|
||||
self.assertEqual(self.top.duty, 0) # below the start point
|
||||
self.top.update(40, 50, 2)
|
||||
self.assertEqual(self.top.duty, 40) # spin-up kick
|
||||
self.top.update(40, 55, 5)
|
||||
self.assertEqual(self.top.duty, 45)
|
||||
for now, temp, duty in ((6, 60, 60), (7, 65, 80), (8, 70, 100), (9, 90, 100)):
|
||||
self.top.update(40, temp, now)
|
||||
self.assertEqual(self.top.duty, duty)
|
||||
|
||||
def test_stop_has_hysteresis_and_hold_time(self):
|
||||
self.top.update(40, 52, 0)
|
||||
for now in range(3, 40):
|
||||
self.top.update(40, 46, now) # between stop and start: keeps running at minimum
|
||||
self.assertEqual(self.top.duty, 30)
|
||||
self.top.update(40, 44, 40)
|
||||
self.top.update(40, 44, 69)
|
||||
self.assertEqual(self.top.duty, 30)
|
||||
self.top.update(40, 44, 70)
|
||||
self.assertEqual(self.top.duty, 0)
|
||||
|
||||
def test_falls_slowly_and_case_fan_boost_forces_full_speed(self):
|
||||
self.top.update(40, 70, 0)
|
||||
self.top.update(40, 60, 5)
|
||||
self.assertEqual(self.top.duty, 100) # holds after a rise
|
||||
self.top.update(40, 60, 11)
|
||||
self.assertEqual(self.top.duty, 96) # 2% per second
|
||||
self.top.update(85, 40, 12)
|
||||
self.assertEqual((self.top.duty, self.top.boosted), (100, True))
|
||||
self.top.update(66, 40, 13)
|
||||
self.assertTrue(self.top.boosted)
|
||||
self.top.update(65, 40, 14)
|
||||
self.assertFalse(self.top.boosted)
|
||||
|
||||
def test_invalid_temperature_is_failsafe_full_speed(self):
|
||||
with self.assertLogs("kurgan.cooling.control", level="WARNING"):
|
||||
self.top.update(40, None, 0)
|
||||
self.assertEqual(self.top.duty, 100)
|
||||
self.assertIn("FAILSAFE", self.top.status)
|
||||
|
||||
def test_firmware_reset_is_corrected(self):
|
||||
self.top.update(40, 40, 0)
|
||||
self.top.update(40, 40, 1)
|
||||
self.assertEqual(self.board.set_manual.call_count, 1) # unchanged duty is not rewritten
|
||||
self.mask = 0x04 # one channel reverted to the BIOS after sleep
|
||||
self.top.update(40, 40, 2)
|
||||
self.assertEqual(self.board.set_manual.call_count, 2)
|
||||
|
||||
def test_unavailable_board_reports_and_retries_later(self):
|
||||
factory = Mock(side_effect=OSError("run as administrator"))
|
||||
top = TopFanCurve((2, 5), board_factory=factory)
|
||||
with self.assertLogs("kurgan.cooling.control", level="WARNING"):
|
||||
top.update(100, 60, 0)
|
||||
self.assertIn("UNAVAILABLE", top.status)
|
||||
top.update(100, 60, 10)
|
||||
self.assertEqual(factory.call_count, 1)
|
||||
factory.side_effect = None
|
||||
factory.return_value = self.board
|
||||
top.update(100, 60, 31)
|
||||
self.board.set_manual.assert_called_once_with((2, 5), 100)
|
||||
|
||||
def test_gpu_worker_drives_top_fans_and_releases_them_on_exit(self):
|
||||
commander = Mock(spec=CommanderPro)
|
||||
commander.set_duty.return_value = {p: 900 for p in range(1, 7)}
|
||||
control = CaseFanControl(commander, (4, 5, 6), None, self.top)
|
||||
control.update(40, 0) # startup runs the case fans at 100%
|
||||
self.assertTrue(self.top.boosted)
|
||||
stop = threading.Event()
|
||||
stop.set()
|
||||
with patch("kurgan.cooling.control.GpuSensors"):
|
||||
control.run(stop)
|
||||
self.assertEqual(self.mask, 0)
|
||||
self.board.close.assert_called()
|
||||
|
||||
def test_top_fans_follow_the_hotter_side(self):
|
||||
commander = Mock(spec=CommanderPro)
|
||||
commander.set_duty.return_value = {p: 900 for p in range(1, 7)}
|
||||
control = CaseFanControl(commander, (4, 5, 6), (1, 2, 3), self.top)
|
||||
for now in range(70): # startup boost ends, then the top fans stop after the hold time
|
||||
control.update(40, now, 44)
|
||||
self.assertEqual((control.gpu.duty, control.cpu.duty, self.top.boosted), (40, 40, False))
|
||||
self.assertEqual(self.top.duty, 0)
|
||||
control.update(40, 70, 60) # CPU hotter than GPU
|
||||
self.assertEqual(self.top.duty, 60)
|
||||
control.update(40, 71, None)
|
||||
self.assertEqual(self.top.duty, 100)
|
||||
|
||||
def test_cpu_side_follows_cpu_temperature_and_can_boost_alone(self):
|
||||
commander = Mock(spec=CommanderPro)
|
||||
commander.set_duty.return_value = {p: 900 for p in range(1, 7)}
|
||||
control = CaseFanControl(commander, (4, 5, 6), (1, 2, 3), self.top)
|
||||
for now in range(40):
|
||||
control.update(40, now, 50)
|
||||
self.assertEqual((control.gpu.duty, control.cpu.duty), (40, 40))
|
||||
self.assertFalse(self.top.boosted)
|
||||
commander.set_duty.assert_any_call((1, 2, 3), 40)
|
||||
control.update(40, 40, 78) # CPU hot, GPU cool
|
||||
commander.set_duty.assert_any_call((1, 2, 3), 93)
|
||||
self.assertEqual(control.gpu.duty, 40)
|
||||
self.assertTrue(self.top.boosted)
|
||||
control.update(40, 41, None)
|
||||
self.assertIn("FAILSAFE", control.cpu.status)
|
||||
self.assertNotIn("FAILSAFE", control.gpu.status)
|
||||
with self.assertRaises(ValueError):
|
||||
CaseFanControl(commander, (4, 5, 6), (1, 2, 4))
|
||||
|
||||
def test_cpu_temperature_is_averaged_and_gaps_are_not(self):
|
||||
pkg = Mock()
|
||||
pkg.temperature.side_effect = [50, 90, None, 60]
|
||||
cpu = CpuTemperature(factory=lambda: pkg)
|
||||
self.assertEqual(cpu.read(0), 50)
|
||||
self.assertEqual(cpu.read(1), 70)
|
||||
self.assertIsNone(cpu.read(2))
|
||||
self.assertEqual(cpu.read(3), 60)
|
||||
|
||||
|
||||
class Nct6687ControlTest(unittest.TestCase):
|
||||
def test_override_uses_config_handshake_and_keeps_other_channels(self):
|
||||
nct = Nct6687.__new__(Nct6687)
|
||||
nct._bus = contextlib.nullcontext
|
||||
nct.read = Mock(return_value=0x01)
|
||||
nct.write = Mock()
|
||||
with patch("kurgan.cooling.board_fans.time.sleep"):
|
||||
nct.set_manual((2, 5), 100)
|
||||
self.assertEqual(nct.write.call_args_list, [
|
||||
call(0xA01, 0x80), call(0xA00, 0x25), call(0xA2A, 255), call(0xA2D, 255), call(0xA01, 0x40)])
|
||||
nct.write.reset_mock()
|
||||
nct.read.return_value = 0x25
|
||||
nct.set_auto((2, 5))
|
||||
self.assertEqual(nct.write.call_args_list, [call(0xA01, 0x80), call(0xA00, 0x01), call(0xA01, 0x40)])
|
||||
with self.assertRaises(ValueError):
|
||||
nct.set_manual((8,), 100)
|
||||
|
||||
|
||||
class FanWorkerTest(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.commander = Mock(spec=CommanderPro)
|
||||
self.commander.set_duty.return_value = {p: 900 for p in range(1, 7)}
|
||||
self.control = CaseFanControl(self.commander, (4, 5, 6))
|
||||
|
||||
def settle(self, temp=50):
|
||||
for now in range(36):
|
||||
self.control.update(temp, now)
|
||||
|
||||
def test_rises_immediately_and_falls_slowly_after_hold(self):
|
||||
self.control.update(40, 0)
|
||||
self.commander.set_duty.assert_called_with((4, 5, 6), 100)
|
||||
self.control.update(40, 9)
|
||||
self.commander.set_duty.assert_called_with((4, 5, 6), 100)
|
||||
for now in range(10, 45):
|
||||
self.control.update(50, now)
|
||||
self.commander.set_duty.assert_called_with((4, 5, 6), 50)
|
||||
self.control.update(68, 45)
|
||||
self.commander.set_duty.assert_called_with((4, 5, 6), 93)
|
||||
for now in range(46, 55):
|
||||
self.control.update(40, now)
|
||||
self.commander.set_duty.assert_called_with((4, 5, 6), 93)
|
||||
self.control.update(40, 55)
|
||||
self.commander.set_duty.assert_called_with((4, 5, 6), 91)
|
||||
|
||||
def test_missing_sensor_and_delayed_worker_use_full_speed(self):
|
||||
self.settle()
|
||||
self.control.update(None, 36)
|
||||
self.commander.set_duty.assert_called_with((4, 5, 6), 100)
|
||||
self.assertIn("FAILSAFE", self.control.status)
|
||||
for now in range(37, 73):
|
||||
self.control.update(50, now)
|
||||
self.commander.set_duty.assert_called_with((4, 5, 6), 50)
|
||||
self.control.update(40, 85)
|
||||
self.commander.set_duty.assert_called_with((4, 5, 6), 100)
|
||||
|
||||
def test_stalled_selected_fan_forces_full_speed_but_other_side_does_not(self):
|
||||
self.commander.set_duty.return_value = {1: 0, 4: 900, 5: 900, 6: 900}
|
||||
self.settle()
|
||||
self.assertNotIn("FAILSAFE", self.control.status)
|
||||
self.commander.set_duty.return_value = {4: 900, 5: 0, 6: 900}
|
||||
self.control.update(50, 36)
|
||||
self.commander.set_duty.assert_called_with((4, 5, 6), 100)
|
||||
self.assertIn("FAILSAFE", self.control.status)
|
||||
self.assertIn("[5]", self.control.status)
|
||||
|
||||
def test_exit_leaves_selected_ports_at_full_speed_even_without_lcd(self):
|
||||
stop = threading.Event()
|
||||
stop.set()
|
||||
with patch("kurgan.cooling.control.GpuSensors"):
|
||||
self.control.run(stop)
|
||||
self.commander.set_duty.assert_called_once_with((4, 5, 6), 100)
|
||||
self.commander.close.assert_called_once()
|
||||
|
||||
def test_worker_error_is_visible_and_attempts_failsafe(self):
|
||||
stop = threading.Event()
|
||||
gpu = Mock()
|
||||
gpu.read.side_effect = RuntimeError("sensor failure")
|
||||
with patch("kurgan.cooling.control.GpuSensors", return_value=gpu):
|
||||
with self.assertLogs("kurgan.cooling.control", level="ERROR"):
|
||||
self.control.run(stop)
|
||||
self.assertIn("CONTROL ERROR", self.control.status)
|
||||
self.commander.set_duty.assert_called_once_with((4, 5, 6), 100)
|
||||
|
||||
|
||||
class CommanderControlTest(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.commander = CommanderPro()
|
||||
self.commander.ports = list(range(6))
|
||||
self.commander.ch = Mock()
|
||||
self.commander._corsair_software_running = Mock(return_value=False)
|
||||
self.commander._open = Mock()
|
||||
|
||||
def reply(self, op, *args):
|
||||
if op == 0x20:
|
||||
return bytes((0, 0, 2, 2, 2, 2, 2, 2))
|
||||
if op == 0x21:
|
||||
return bytes((0, 0, 3, 132)) # 900 RPM
|
||||
return bytes(4)
|
||||
|
||||
def test_only_confirmed_side_receives_duty_commands(self):
|
||||
self.commander._cmd = Mock(side_effect=self.reply)
|
||||
rpms = self.commander.set_duty((4, 5, 6), 81)
|
||||
writes = [c.args for c in self.commander._cmd.call_args_list if c.args[0] == 0x23]
|
||||
self.assertEqual(writes, [(0x23, 3, 81), (0x23, 4, 81), (0x23, 5, 81)])
|
||||
self.assertEqual(rpms, {p: 900 for p in range(1, 7)})
|
||||
self.commander.controlled = True
|
||||
self.commander._cmd.reset_mock()
|
||||
self.assertEqual(self.commander.read(), [900] * 6)
|
||||
self.commander._cmd.assert_not_called()
|
||||
|
||||
def test_disconnected_or_dc_port_rejected_before_any_write(self):
|
||||
for modes in (bytes((0, 0, 2, 2, 0, 2, 2, 2)),
|
||||
bytes((0, 0, 2, 2, 1, 2, 2, 2)), bytes(4)):
|
||||
self.commander._cmd = Mock(return_value=modes)
|
||||
with self.assertRaises(OSError):
|
||||
self.commander.set_duty((1, 2, 3), 80)
|
||||
self.commander._cmd.assert_called_once_with(0x20)
|
||||
|
||||
def test_competing_software_prevents_all_usb_writes(self):
|
||||
self.commander._corsair_software_running.return_value = True
|
||||
self.commander._cmd = Mock()
|
||||
with self.assertRaisesRegex(OSError, "busy"):
|
||||
self.commander.set_duty((1, 2, 3), 100)
|
||||
self.commander._cmd.assert_not_called()
|
||||
self.assertIsNone(self.commander.ch)
|
||||
|
||||
def test_openrgb_counts_as_released_only_when_detector_disabled_everywhere(self):
|
||||
commander = CommanderPro()
|
||||
disabled = '{"Detectors":{"detectors":{"Corsair Commander Pro":false}}}'
|
||||
configs = {"user": disabled, "service": disabled}
|
||||
|
||||
def fake_open(path, *args, **kwargs):
|
||||
return mock_open(read_data=configs["service" if "service_config" in path else "user"])()
|
||||
|
||||
with patch("kurgan.telemetry.sensors._process_names", return_value=["openrgb.exe"]), \
|
||||
patch("kurgan.telemetry.sensors.os.path.exists", return_value=True), \
|
||||
patch("builtins.open", side_effect=fake_open):
|
||||
self.assertFalse(commander._corsair_software_running())
|
||||
configs["service"] = disabled.replace("false", "true")
|
||||
with self.assertLogs("kurgan.telemetry.sensors", level="WARNING"):
|
||||
self.assertTrue(commander._corsair_software_running())
|
||||
with patch("kurgan.telemetry.sensors._process_names", return_value=["openrgb.exe"]), \
|
||||
patch("kurgan.telemetry.sensors.os.path.exists", return_value=True), \
|
||||
patch("builtins.open", side_effect=OSError("missing config")):
|
||||
with self.assertLogs("kurgan.telemetry.sensors", level="WARNING"):
|
||||
self.assertTrue(commander._corsair_software_running())
|
||||
with patch("kurgan.telemetry.sensors._process_names", return_value=["fancontrol.exe"]):
|
||||
self.assertTrue(commander._corsair_software_running())
|
||||
self.assertFalse(corsair_software_running("Corsair Lighting Node Core", fan_tools=False))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,113 @@
|
||||
import unittest
|
||||
from unittest.mock import Mock, patch
|
||||
|
||||
from kurgan.lighting.gpu import (
|
||||
AsusGpuLeds, GpuLighting, NvidiaI2c, gpu_chase_frame,
|
||||
)
|
||||
from kurgan.lighting.case_fans import ChaseTiming, side_chase_color
|
||||
|
||||
|
||||
class FakeBus(NvidiaI2c):
|
||||
def __init__(self, firmware=b"AUMA0-E6K5-1110"):
|
||||
self.register = 0
|
||||
self.values = {0x1000 + i: value for i, value in enumerate(firmware.ljust(16, b"\0"))}
|
||||
self.values[0x1C03] = 4
|
||||
self.values[0x8020] = 0
|
||||
self.writes = []
|
||||
|
||||
def transfer(self, command, data, *, read=False):
|
||||
if command == 0:
|
||||
self.register = int.from_bytes(data, "big")
|
||||
elif read:
|
||||
return bytes((self.values.get(self.register, 0),))
|
||||
else:
|
||||
self.writes.append((self.register, command, data))
|
||||
return data
|
||||
|
||||
|
||||
class GpuTransportTest(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.conflict = patch("kurgan.lighting.gpu.corsair_software_running", return_value=False)
|
||||
self.conflict.start()
|
||||
self.addCleanup(self.conflict.stop)
|
||||
self.processes = patch("kurgan.lighting.gpu._process_names", return_value=[])
|
||||
self.processes.start()
|
||||
self.addCleanup(self.processes.stop)
|
||||
|
||||
def test_direct_colors_use_rbg_order_skip_unchanged_and_restore_without_saving(self):
|
||||
bus = FakeBus()
|
||||
driver = AsusGpuLeds(lambda: bus)
|
||||
driver.open()
|
||||
self.assertEqual(bus.writes, [])
|
||||
colors = ((24, 0, 0), (255, 48, 0), (24, 0, 0), (24, 0, 0))
|
||||
driver.show_frame(colors)
|
||||
self.assertEqual(bus.writes[1], (0x8103, 3, bytes((3, 255, 0, 48))))
|
||||
self.assertEqual(bus.writes[-2:], [(0x8020, 1, b"\x01"), (0x80A0, 1, b"\x01")])
|
||||
bus.writes.clear()
|
||||
driver.show_frame(colors)
|
||||
self.assertEqual(bus.writes, [])
|
||||
driver.show_frame((colors[0], colors[0], colors[2], colors[3]))
|
||||
self.assertEqual(bus.writes, [(0x8103, 3, bytes((3, 24, 0, 0)))])
|
||||
driver.close()
|
||||
self.assertEqual(bus.writes[-2:], [(0x8020, 1, b"\x00"), (0x80A0, 1, b"\x01")])
|
||||
self.assertFalse(any(data == b"\xaa" for _, _, data in bus.writes))
|
||||
|
||||
def test_unknown_firmware_and_invalid_frames_do_not_write_lighting_registers(self):
|
||||
bus = FakeBus(b"UNKNOWN")
|
||||
driver = AsusGpuLeds(lambda: bus)
|
||||
with self.assertRaises(OSError):
|
||||
driver.open()
|
||||
self.assertEqual(bus.writes, [])
|
||||
bus = FakeBus()
|
||||
driver = AsusGpuLeds(lambda: bus)
|
||||
driver.open()
|
||||
with self.assertRaises(ValueError):
|
||||
driver.show_frame(((256, 0, 0),) * 4)
|
||||
self.assertEqual(bus.writes, [])
|
||||
|
||||
|
||||
class GpuChaseTest(unittest.TestCase):
|
||||
def test_row_reverses_at_each_end_once_per_shared_cycle(self):
|
||||
for count in (4, 30):
|
||||
route_length = 2 * (count - 1)
|
||||
heads = []
|
||||
for step in range(route_length + 1):
|
||||
phase = 6 + step * 36 / route_length + 0.000001
|
||||
frame = gpu_chase_frame(phase, count)
|
||||
heads.append(frame.index(side_chase_color(1)))
|
||||
self.assertEqual(heads, list(range(count - 1, -1, -1)) + list(range(1, count)))
|
||||
self.assertEqual(gpu_chase_frame(6, count), gpu_chase_frame(42, count))
|
||||
|
||||
def test_worker_joins_shared_clock_caps_writes_and_releases_on_off(self):
|
||||
clock = ChaseTiming()
|
||||
clock.reset(6)
|
||||
clock.set_power(550)
|
||||
driver = Mock()
|
||||
driver.led_count = 4
|
||||
lighting = GpuLighting(clock, lambda: driver)
|
||||
writes = []
|
||||
for tick in range(101):
|
||||
now = 100 + tick * 0.01
|
||||
before = driver.show_frame.call_count
|
||||
with patch("kurgan.lighting.gpu.time.monotonic", return_value=now):
|
||||
lighting.update(True)
|
||||
if driver.show_frame.call_count != before:
|
||||
writes.append(now)
|
||||
self.assertAlmostEqual(clock.phase, 46)
|
||||
self.assertTrue(all(b - a >= 0.045 for a, b in zip(writes, writes[1:])))
|
||||
lighting.update(False)
|
||||
driver.close.assert_called_once()
|
||||
self.assertEqual(lighting.status, "off")
|
||||
|
||||
def test_connection_failure_is_visible_and_retries_after_backoff(self):
|
||||
driver = Mock()
|
||||
driver.open.side_effect = OSError("GPU busy")
|
||||
factory = Mock(return_value=driver)
|
||||
lighting = GpuLighting(ChaseTiming(), factory)
|
||||
with patch("kurgan.lighting.gpu.time.monotonic", return_value=100), \
|
||||
self.assertLogs("kurgan.lighting.gpu", level="WARNING"):
|
||||
lighting.update(True)
|
||||
with patch("kurgan.lighting.gpu.time.monotonic", return_value=105):
|
||||
lighting.update(True)
|
||||
factory.assert_called_once()
|
||||
self.assertEqual(lighting.status, "unavailable: GPU busy")
|
||||
@@ -0,0 +1,78 @@
|
||||
import os
|
||||
import tempfile
|
||||
import unittest
|
||||
from unittest.mock import patch
|
||||
|
||||
from kurgan.lighting.service import LightingService
|
||||
from kurgan.settings import Settings
|
||||
from kurgan.theme import Theme
|
||||
|
||||
|
||||
class FakeWorker:
|
||||
status = "running"
|
||||
|
||||
def set_temperature(self, cpu, gpu):
|
||||
pass
|
||||
|
||||
def set_power(self, watts):
|
||||
pass
|
||||
|
||||
|
||||
class LightingServiceTest(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.dir = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(self.dir.cleanup)
|
||||
self.settings = Settings(os.path.join(self.dir.name, "settings.json"), None)
|
||||
|
||||
def service(self, overrides=None):
|
||||
return LightingService(self.settings, Theme(), (0.15, 0.025, 150.0, 550.0), overrides,
|
||||
rgb=FakeWorker(), memory=FakeWorker(), gpu=FakeWorker())
|
||||
|
||||
def active(self, service, zone):
|
||||
return sorted(mode for mode, event in service._events[zone].items() if event.is_set())
|
||||
|
||||
def test_saved_modes_start_and_switch_exclusively(self):
|
||||
self.settings.update("lighting", memory="temperature")
|
||||
service = self.service()
|
||||
self.assertEqual(self.active(service, "memory"), ["temperature"])
|
||||
service.set_mode("memory", "chase")
|
||||
self.assertEqual(self.active(service, "memory"), ["chase"])
|
||||
self.assertEqual(self.active(service, "case_fans"), [])
|
||||
service.set_mode("memory", "off")
|
||||
self.assertEqual(self.active(service, "memory"), [])
|
||||
self.assertEqual(Settings(self.settings.path, None).get("lighting", "memory"), "off")
|
||||
|
||||
def test_failed_save_leaves_the_lights_as_they_were(self):
|
||||
service = self.service()
|
||||
service.set_mode("gpu", "chase")
|
||||
with patch("kurgan.settings.os.replace", side_effect=OSError("disk full")), self.assertRaises(OSError):
|
||||
service.set_mode("gpu", "off")
|
||||
self.assertEqual(service.mode("gpu"), "chase")
|
||||
self.assertEqual(self.active(service, "gpu"), ["chase"])
|
||||
|
||||
def test_unknown_zone_or_mode_is_rejected(self):
|
||||
service = self.service()
|
||||
for zone, mode in (("gpu", "temperature"), ("keyboard", "off"), ("memory", "rainbow")):
|
||||
with self.subTest(zone=zone, mode=mode), self.assertRaises(ValueError):
|
||||
service.set_mode(zone, mode)
|
||||
|
||||
def test_command_line_overrides_are_for_this_run_until_chosen(self):
|
||||
service = self.service({"case_fans": "chase"})
|
||||
zone = service.snapshot()["zones"][0]
|
||||
self.assertEqual((zone["key"], zone["mode"], zone["this_run_only"]), ("case_fans", "chase", True))
|
||||
self.assertEqual(self.settings.get("lighting", "case_fans"), "off")
|
||||
service.set_mode("case_fans", "chase")
|
||||
self.assertFalse(service.snapshot()["zones"][0]["this_run_only"])
|
||||
self.assertEqual(self.settings.get("lighting", "case_fans"), "chase")
|
||||
|
||||
def test_chase_speed_is_reported_only_while_a_chase_runs(self):
|
||||
service = self.service()
|
||||
self.assertIsNone(service.snapshot()["chase_ms_per_led"])
|
||||
service.set_mode("gpu", "chase")
|
||||
self.assertEqual(service.snapshot()["chase_ms_per_led"], 150) # idle pace before any power reading
|
||||
service.on_telemetry(50, 50, 550.0)
|
||||
self.assertEqual(service.snapshot()["chase_ms_per_led"], 25)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,383 @@
|
||||
import unittest
|
||||
import threading
|
||||
from unittest.mock import Mock, patch
|
||||
|
||||
from kurgan.theme import Theme
|
||||
from kurgan.lighting.memory import (
|
||||
MemoryFrame, MemoryLighting, PawnIoSmbus, _crc8, _led_packet, _rgb_bytes,
|
||||
_solid_frame, memory_chase_frame, memory_chase_step,
|
||||
)
|
||||
from kurgan.lighting.case_fans import ChaseTiming, RGBLighting, side_chase_frame
|
||||
|
||||
|
||||
class FakeDriver:
|
||||
def __init__(self):
|
||||
self.open_count = 0
|
||||
self.closed = 0
|
||||
self.frames: list[MemoryFrame] = []
|
||||
self.forced: list[bool] = []
|
||||
|
||||
def open(self):
|
||||
self.open_count += 1
|
||||
|
||||
def show(self, color):
|
||||
self.frames.append(_solid_frame(color))
|
||||
|
||||
def show_frame(self, colors, *, force=False):
|
||||
self.frames.append(colors)
|
||||
self.forced.append(force)
|
||||
|
||||
def close(self):
|
||||
self.closed += 1
|
||||
|
||||
|
||||
class MemoryLightingTest(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.theme = Theme()
|
||||
self.driver = FakeDriver()
|
||||
self.lighting = MemoryLighting(self.theme, driver_factory=lambda: self.driver)
|
||||
|
||||
def test_disabled_start_keeps_ram_dark(self):
|
||||
self.lighting.update(40, False)
|
||||
self.assertEqual(self.lighting.status, "RAM lighting off")
|
||||
self.assertEqual(self.driver.open_count, 1)
|
||||
self.assertEqual(self.driver.frames, [_solid_frame((0, 0, 0))])
|
||||
|
||||
def test_temperature_control_updates_all_modules_and_stays_dark_when_disabled(self):
|
||||
color = (24, 0, 0)
|
||||
hot = (255, 48, 0)
|
||||
with patch("kurgan.lighting.memory.time.monotonic", return_value=100.0):
|
||||
self.lighting.update(40, True)
|
||||
self.assertEqual(self.driver.open_count, 1)
|
||||
self.assertEqual(self.driver.frames, [_solid_frame(color)])
|
||||
self.assertEqual(self.lighting.status, "RAM temperature lighting active (CPU 40 °C)")
|
||||
|
||||
with patch("kurgan.lighting.memory.time.monotonic", return_value=101.0):
|
||||
self.lighting.update(85, True)
|
||||
self.assertEqual(self.driver.frames, [_solid_frame(color), _solid_frame(hot)])
|
||||
|
||||
with patch("kurgan.lighting.memory.time.monotonic", return_value=102.0):
|
||||
self.lighting.update(85, False)
|
||||
self.assertEqual(self.driver.frames[-1], _solid_frame((0, 0, 0)))
|
||||
self.assertEqual(self.lighting.status, "RAM lighting off")
|
||||
|
||||
with patch("kurgan.lighting.memory.time.monotonic", return_value=107.0):
|
||||
self.lighting.update(None, False)
|
||||
self.assertEqual(self.driver.frames, [_solid_frame(c) for c in (color, hot, (0, 0, 0), (0, 0, 0))])
|
||||
|
||||
self.lighting.close()
|
||||
self.assertEqual(self.driver.frames[-1], _solid_frame((0, 0, 0)))
|
||||
self.assertEqual(self.driver.closed, 1)
|
||||
|
||||
def test_missing_temperature_neither_claims_the_bus_nor_replaces_a_live_color(self):
|
||||
with patch("kurgan.lighting.memory.time.monotonic", return_value=100.0):
|
||||
self.lighting.update(None, True)
|
||||
self.assertEqual(self.lighting.status, "RAM temperature lighting waiting for CPU/GPU temperature")
|
||||
self.assertEqual(self.driver.open_count, 0)
|
||||
|
||||
with patch("kurgan.lighting.memory.time.monotonic", return_value=101.0):
|
||||
self.lighting.update(60, True)
|
||||
color = self.driver.frames[-1]
|
||||
with patch("kurgan.lighting.memory.time.monotonic", return_value=102.0):
|
||||
self.lighting.update(None, True)
|
||||
self.assertEqual(self.driver.frames, [color])
|
||||
self.assertEqual(self.lighting.status, "RAM temperature lighting waiting for CPU/GPU temperature")
|
||||
|
||||
def test_red_orange_ramp_uses_hottest_valid_sensor_and_clamps_at_thresholds(self):
|
||||
cases = (
|
||||
(40, 35, (24, 0, 0), "CPU 40"),
|
||||
(40, 65, (140, 24, 0), "GPU 65"),
|
||||
(80, 65, (255, 48, 0), "CPU 80"),
|
||||
(60, 95, (255, 48, 0), "GPU 95"),
|
||||
(None, 50, (24, 0, 0), "GPU 50"),
|
||||
(float("nan"), 65, (140, 24, 0), "GPU 65"),
|
||||
(65, float("inf"), (140, 24, 0), "CPU 65"),
|
||||
)
|
||||
for cpu, gpu, expected, source in cases:
|
||||
with self.subTest(cpu=cpu, gpu=gpu):
|
||||
self.lighting.update(cpu, True, gpu_temp=gpu)
|
||||
self.assertEqual(self.driver.frames[-1], _solid_frame(expected))
|
||||
self.assertIn(source, self.lighting.status)
|
||||
self.lighting.update(float("nan"), True, gpu_temp=float("inf"))
|
||||
self.assertEqual(self.driver.frames[-1], _solid_frame((140, 24, 0)))
|
||||
self.assertEqual(self.lighting.status, "RAM temperature lighting waiting for CPU/GPU temperature")
|
||||
|
||||
def test_worker_uses_both_temperatures_from_sensor_handoff(self):
|
||||
stop, enabled = Mock(), Mock()
|
||||
stop.is_set.side_effect = [False, True]
|
||||
enabled.is_set.return_value = True
|
||||
self.lighting.set_temperature(40, 80)
|
||||
self.lighting.run(stop, enabled)
|
||||
self.assertEqual(self.driver.frames, [_solid_frame((255, 48, 0)), _solid_frame((0, 0, 0))])
|
||||
|
||||
def test_invalid_temperature_range_is_rejected(self):
|
||||
for warn, hot in ((80, 80), (90, 80), (float("nan"), 80), (50, float("inf"))):
|
||||
with self.subTest(warn=warn, hot=hot), self.assertRaises(ValueError):
|
||||
MemoryLighting(Theme(temp_warn=warn, temp_hot=hot))
|
||||
|
||||
def test_failed_connection_retries_after_backoff(self):
|
||||
factory = Mock(side_effect=[OSError("PawnIO denied"), self.driver])
|
||||
self.lighting = MemoryLighting(self.theme, driver_factory=factory)
|
||||
with patch("kurgan.lighting.memory.time.monotonic", return_value=100.0):
|
||||
with self.assertLogs("kurgan.lighting.memory", level="WARNING"):
|
||||
self.lighting.update(40, True)
|
||||
self.assertEqual(self.lighting.status, "PawnIO denied")
|
||||
with patch("kurgan.lighting.memory.time.monotonic", return_value=105.0):
|
||||
self.lighting.update(40, True)
|
||||
self.assertEqual(factory.call_count, 1)
|
||||
with patch("kurgan.lighting.memory.time.monotonic", return_value=110.0):
|
||||
self.lighting.update(40, True)
|
||||
self.assertEqual(factory.call_count, 2)
|
||||
self.assertEqual(len(self.driver.frames), 1)
|
||||
|
||||
def test_chase_uses_elapsed_time_with_capped_writes_and_power_acceleration(self):
|
||||
self.lighting.set_power(550)
|
||||
with patch("kurgan.lighting.memory.time.monotonic", return_value=100):
|
||||
self.lighting.update(None, False, side_chase=True)
|
||||
for index in range(1, 50):
|
||||
with patch("kurgan.lighting.memory.time.monotonic", return_value=100 + index * 0.01):
|
||||
self.lighting.update(None, False, side_chase=True)
|
||||
with patch("kurgan.lighting.memory.time.monotonic", return_value=100.5):
|
||||
self.lighting.update(None, False, side_chase=True)
|
||||
self.assertGreaterEqual(len(self.driver.frames), 10)
|
||||
self.assertLessEqual(len(self.driver.frames), 12)
|
||||
self.assertAlmostEqual(self.lighting._chase_timing.phase, 26)
|
||||
self.assertIn(self.driver.frames[-1], tuple(memory_chase_frame(step) for step in range(23, 26)))
|
||||
self.assertEqual(self.lighting.status, "RAM red side chase active (0.9 s/cycle at 550 W)")
|
||||
|
||||
self.lighting = MemoryLighting(self.theme, lambda: self.driver)
|
||||
self.lighting.set_power(150)
|
||||
with patch("kurgan.lighting.memory.time.monotonic", return_value=200):
|
||||
self.lighting.update(None, False, side_chase=True)
|
||||
with patch("kurgan.lighting.memory.time.monotonic", return_value=200.5):
|
||||
self.lighting.update(None, False, side_chase=True)
|
||||
self.lighting.set_power(550)
|
||||
with patch("kurgan.lighting.memory.time.monotonic", return_value=200.6):
|
||||
self.lighting.update(None, False, side_chase=True)
|
||||
self.assertAlmostEqual(self.lighting._chase_timing.rate, 10)
|
||||
self.assertAlmostEqual(self.lighting._chase_timing.phase, 6 + 13 / 3)
|
||||
|
||||
def test_pattern_switches_and_off_bypass_chase_frame_cap(self):
|
||||
with patch("kurgan.lighting.memory.time.monotonic", return_value=100):
|
||||
self.lighting.update(None, False, side_chase=True)
|
||||
with patch("kurgan.lighting.memory.time.monotonic", return_value=100.01):
|
||||
self.lighting.update(65, True)
|
||||
with patch("kurgan.lighting.memory.time.monotonic", return_value=100.02):
|
||||
self.lighting.update(None, False)
|
||||
with patch("kurgan.lighting.memory.time.monotonic", return_value=100.03):
|
||||
self.lighting.update(None, False, side_chase=True)
|
||||
self.assertEqual(self.driver.frames, [
|
||||
memory_chase_frame(5), _solid_frame((140, 24, 0)),
|
||||
_solid_frame((0, 0, 0)), memory_chase_frame(5),
|
||||
])
|
||||
with patch("kurgan.lighting.memory.time.monotonic", return_value=105.03):
|
||||
self.lighting.update(None, False, side_chase=True)
|
||||
self.assertTrue(self.driver.forced[-1])
|
||||
self.lighting.close()
|
||||
self.assertEqual(self.driver.frames[-1], _solid_frame((0, 0, 0)))
|
||||
|
||||
def test_fast_chase_worker_avoids_large_position_jumps_with_fan_refresh_budget(self):
|
||||
now = [100.0]
|
||||
stop = Mock()
|
||||
stop.is_set.side_effect = lambda: now[0] > 101
|
||||
stop.wait.side_effect = lambda delay: now.__setitem__(0, now[0] + delay)
|
||||
chase = threading.Event()
|
||||
chase.set()
|
||||
self.lighting.set_power(550)
|
||||
writes = []
|
||||
show_frame = self.driver.show_frame
|
||||
|
||||
def record(colors, *, force=False):
|
||||
writes.append((now[0], int(self.lighting._chase_timing.phase)))
|
||||
show_frame(colors, force=force)
|
||||
|
||||
with patch("kurgan.lighting.memory.time.monotonic", side_effect=lambda: now[0]), \
|
||||
patch.object(self.driver, "show_frame", side_effect=record):
|
||||
self.lighting.run(stop, threading.Event(), chase)
|
||||
self.assertGreaterEqual(len(writes), 16)
|
||||
self.assertLessEqual(len(writes), 23)
|
||||
self.assertTrue(all(b[0] - a[0] >= 0.045 for a, b in zip(writes, writes[1:])))
|
||||
self.assertLessEqual(max(b[1] - a[1] for a, b in zip(writes, writes[1:])), 3)
|
||||
self.assertGreaterEqual(writes[-1][1], 42)
|
||||
|
||||
def test_worker_accepts_chase_without_temperature_readings(self):
|
||||
stop = Mock()
|
||||
stop.is_set.side_effect = [False, True]
|
||||
chase = threading.Event()
|
||||
chase.set()
|
||||
self.lighting.run(stop, threading.Event(), chase)
|
||||
self.assertEqual(self.driver.frames, [memory_chase_frame(5), _solid_frame((0, 0, 0))])
|
||||
|
||||
def test_moving_chase_still_refreshes_unchanged_sticks_every_five_seconds(self):
|
||||
for index in range(11):
|
||||
with patch("kurgan.lighting.memory.time.monotonic", return_value=100 + index * 0.5):
|
||||
self.lighting.update(None, False, side_chase=True)
|
||||
self.assertEqual(self.driver.forced, [True] + [False] * 9 + [True])
|
||||
|
||||
class MemoryChaseTest(unittest.TestCase):
|
||||
def test_mirrored_heads_follow_six_visits_without_repeating_end_sticks(self):
|
||||
positions = (
|
||||
(0, 3, 0), (5, 3, 5), (6, 2, 5), (11, 2, 0),
|
||||
(12, 1, 0), (17, 1, 5), (18, 0, 5), (23, 0, 0),
|
||||
(24, 1, 0), (29, 1, 5), (30, 2, 5), (35, 2, 0),
|
||||
(36, 3, 0), (41, 3, 5),
|
||||
)
|
||||
for step, stick, left in positions:
|
||||
with self.subTest(step=step):
|
||||
frame = memory_chase_frame(step)
|
||||
heads = [(row, led) for row, colors in enumerate(frame)
|
||||
for led, color in enumerate(colors) if color == (255, 48, 0)]
|
||||
self.assertEqual(heads, [(stick, left), (stick, 11 - left)])
|
||||
for step in range(36):
|
||||
frame = memory_chase_frame(step)
|
||||
self.assertEqual(len(frame), 4)
|
||||
for colors in frame:
|
||||
self.assertEqual(len(colors), 12)
|
||||
self.assertEqual(colors[:6], colors[6:][::-1])
|
||||
self.assertEqual(frame, memory_chase_frame(step + 36))
|
||||
|
||||
def test_four_led_fading_trail_matches_fan_palette(self):
|
||||
frame = memory_chase_frame(10)
|
||||
self.assertEqual(frame[2][1:6], ((255, 48, 0), (209, 38, 0), (163, 29, 0),
|
||||
(116, 19, 0), (70, 10, 0)))
|
||||
self.assertEqual(frame[3], ((24, 0, 0),) * 12)
|
||||
|
||||
|
||||
class SharedChaseTest(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.clock = ChaseTiming(0.125)
|
||||
self.clock.reset(6)
|
||||
self.node = Mock()
|
||||
self.node.firmware = "0.9.16"
|
||||
self.driver = FakeDriver()
|
||||
self.fans = RGBLighting(Theme(), node_factory=lambda: self.node, chase_timing=self.clock)
|
||||
self.memory = MemoryLighting(Theme(), lambda: self.driver, self.clock)
|
||||
self.fans.set_power(150)
|
||||
|
||||
def test_whole_cycles_share_physical_bottom_and_top_anchors(self):
|
||||
for index, (now, fan_step, ram_step) in enumerate(((100, 6, 5), (102.25, 24, 23), (104.5, 42, 41))):
|
||||
with self.subTest(now=now), patch("time.monotonic", return_value=now):
|
||||
if index % 2:
|
||||
self.memory.update(None, False, side_chase=True)
|
||||
self.fans.update(None, False, side_chase=True)
|
||||
else:
|
||||
self.fans.update(None, False, side_chase=True)
|
||||
self.memory.update(None, False, side_chase=True)
|
||||
self.assertEqual(self.node.show.call_args.args[1], side_chase_frame(fan_step))
|
||||
self.assertEqual(self.driver.frames[-1], memory_chase_frame(ram_step))
|
||||
self.assertEqual(self.memory.status, "RAM red side chase active (4.5 s/cycle)")
|
||||
|
||||
def test_joining_and_switching_patterns_never_resets_shared_phase(self):
|
||||
with patch("time.monotonic", return_value=100):
|
||||
self.fans.update(None, False, side_chase=True)
|
||||
with patch("time.monotonic", return_value=102.25):
|
||||
self.fans.update(None, False, side_chase=True)
|
||||
self.memory.update(None, False, side_chase=True)
|
||||
self.assertEqual(self.driver.frames[-1], memory_chase_frame(23))
|
||||
with patch("time.monotonic", return_value=102.26):
|
||||
self.memory.update(65, True)
|
||||
with patch("time.monotonic", return_value=102.75):
|
||||
self.fans.update(None, False, side_chase=True)
|
||||
self.memory.update(None, False, side_chase=True)
|
||||
self.assertEqual(self.clock.phase, 28)
|
||||
self.assertEqual(self.driver.frames[-1], memory_chase_frame(memory_chase_step(28)))
|
||||
with patch("time.monotonic", return_value=103):
|
||||
self.fans.update(None, False)
|
||||
with patch("time.monotonic", return_value=103.5):
|
||||
self.memory.update(None, False, side_chase=True)
|
||||
self.assertEqual(self.clock.phase, 34)
|
||||
|
||||
def test_out_of_order_worker_timestamps_do_not_double_count_elapsed_time(self):
|
||||
self.clock.sample(100)
|
||||
self.clock.sample(100.5)
|
||||
phase, _ = self.clock.sample(100.25)
|
||||
self.assertEqual(phase, 10)
|
||||
phase, _ = self.clock.sample(101)
|
||||
self.assertEqual(phase, 14)
|
||||
|
||||
def test_load_change_has_one_acceleration_and_phase_for_both_patterns(self):
|
||||
with patch("time.monotonic", return_value=100):
|
||||
self.fans.update(None, False, side_chase=True)
|
||||
self.memory.update(None, False, side_chase=True)
|
||||
self.memory.set_power(550)
|
||||
with patch("time.monotonic", return_value=100.5):
|
||||
self.memory.update(None, False, side_chase=True)
|
||||
self.fans.update(None, False, side_chase=True)
|
||||
self.assertEqual(self.clock.rate, 24)
|
||||
self.assertEqual(self.clock.phase, 18)
|
||||
self.assertEqual(self.node.show.call_args.args[1], side_chase_frame(18))
|
||||
self.assertEqual(self.driver.frames[-1], memory_chase_frame(17))
|
||||
|
||||
|
||||
class CorsairDramPacketTest(unittest.TestCase):
|
||||
def test_direct_packet_contains_twelve_rgb_leds_and_crc8(self):
|
||||
color = (12, 34, 56)
|
||||
packet = _led_packet((color,) * 12)
|
||||
payload = bytes((12,)) + bytes(color) * 12
|
||||
self.assertEqual(len(packet), 38)
|
||||
self.assertEqual(packet[:-1], payload)
|
||||
self.assertEqual(packet[-1], _crc8(payload))
|
||||
self.assertEqual(_crc8(b"123456789"), 0xF4)
|
||||
|
||||
def test_direct_frame_only_writes_all_four_controllers_without_saving_effects(self):
|
||||
bus = PawnIoSmbus()
|
||||
calls = []
|
||||
bus._write_block = lambda address, register, data: calls.append((address, register, data))
|
||||
with patch("kurgan.lighting.memory.PawnIoSmbus._bus"):
|
||||
bus.show((255, 0, 0))
|
||||
self.assertEqual([call[:2] for call in calls],
|
||||
[(address, register) for address in (0x18, 0x19, 0x1A, 0x1B)
|
||||
for register in (0x31, 0x32)])
|
||||
self.assertTrue(all(len(data) == size for (_, _, data), size
|
||||
in zip(calls, (32, 6) * 4)))
|
||||
for index in range(0, len(calls), 2):
|
||||
self.assertEqual(calls[index][2] + calls[index + 1][2], _led_packet(((255, 0, 0),) * 12))
|
||||
|
||||
def test_smbus_block_write_encodes_payload_length_and_zero_padding(self):
|
||||
bus = PawnIoSmbus()
|
||||
bus._execute = Mock()
|
||||
data = bytes(range(32))
|
||||
bus._write_block(0x1B, 0x31, data)
|
||||
operation, args = bus._execute.call_args.args
|
||||
packed = b"".join(cell.to_bytes(8, "little") for cell in args[4:])
|
||||
self.assertEqual(operation, b"ioctl_smbus_xfer")
|
||||
self.assertEqual(args[:4], (0x1B, 0, 0x31, 5))
|
||||
self.assertEqual(packed, bytes((32,)) + data + bytes(7))
|
||||
|
||||
def test_invalid_rgb_values_are_rejected(self):
|
||||
for color in ((-1, 0, 0), (0, 256, 0), (1.5, 0, 0), (1, 2)):
|
||||
with self.subTest(color=color), self.assertRaises(ValueError):
|
||||
_rgb_bytes(color)
|
||||
|
||||
def test_per_led_packets_and_only_changed_sticks_are_written(self):
|
||||
frame = memory_chase_frame(0)
|
||||
packet = _led_packet(frame[3])
|
||||
self.assertEqual(packet[:-1], bytes((12,)) + bytes(channel for color in frame[3] for channel in color))
|
||||
self.assertEqual(packet[-1], _crc8(packet[:-1]))
|
||||
bus = PawnIoSmbus()
|
||||
bus._write_block = Mock()
|
||||
with patch("kurgan.lighting.memory.PawnIoSmbus._bus"):
|
||||
bus.show_frame(frame)
|
||||
self.assertEqual(bus._write_block.call_count, 8)
|
||||
bus._write_block.reset_mock()
|
||||
bus.show_frame(frame)
|
||||
bus._write_block.assert_not_called()
|
||||
changed = frame[:3] + (((255, 0, 0),) * 12,)
|
||||
bus.show_frame(changed)
|
||||
self.assertEqual([c.args[:2] for c in bus._write_block.call_args_list], [(0x1B, 0x31), (0x1B, 0x32)])
|
||||
bus._write_block.reset_mock()
|
||||
bus.show_frame(changed, force=True)
|
||||
self.assertEqual(bus._write_block.call_count, 8)
|
||||
|
||||
def test_invalid_frame_is_rejected_before_any_hardware_write(self):
|
||||
bus = PawnIoSmbus()
|
||||
bus._write_block = Mock()
|
||||
frame = _solid_frame((0, 0, 0))
|
||||
for invalid in (frame[:3], frame[:3] + (frame[3][:11],)):
|
||||
with self.subTest(frame=invalid), self.assertRaises(ValueError):
|
||||
bus.show_frame(invalid)
|
||||
bus._write_block.assert_not_called()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,80 @@
|
||||
import unittest
|
||||
from unittest.mock import Mock
|
||||
|
||||
from kurgan.cooling import control
|
||||
from kurgan.cooling.board_fans import Nct6687
|
||||
from kurgan.cooling.control import CaseFanControl, TopFanCurve
|
||||
from kurgan.cooling.profiles import BALANCED, FULL, PERFORMANCE, PROFILES, QUIET, validate_curve
|
||||
|
||||
|
||||
class ProfileTest(unittest.TestCase):
|
||||
def test_balanced_keeps_the_original_curves(self):
|
||||
self.assertEqual(control.CURVE, ((40, 40), (50, 50), (60, 65), (70, 100)))
|
||||
self.assertEqual(control.CPU_CURVE, ((50, 40), (60, 50), (70, 65), (80, 100)))
|
||||
self.assertEqual((control.TOP_START, control.TOP_STOP), (50, 45))
|
||||
self.assertEqual(list(PROFILES), ["quiet", "balanced", "performance", "full"])
|
||||
|
||||
def test_profiles_are_ordered_quiet_to_full_at_every_temperature(self):
|
||||
for temp in range(0, 111, 5):
|
||||
for side in ("gpu_curve", "cpu_curve", "top_curve"):
|
||||
duties = [control._curve_duty(getattr(p, side), temp) for p in (QUIET, BALANCED, PERFORMANCE, FULL)]
|
||||
with self.subTest(temp=temp, side=side):
|
||||
self.assertEqual(duties, sorted(duties))
|
||||
|
||||
def test_invalid_curves_are_rejected(self):
|
||||
for curve in (((50, 100),), ((50, 40), (50, 100)), ((40, 60), (60, 50), (70, 100)),
|
||||
((40, 40), (60, 90)), ((-5, 40), (60, 100))):
|
||||
with self.subTest(curve=curve), self.assertRaises(ValueError):
|
||||
validate_curve(curve)
|
||||
|
||||
|
||||
class ProfileSwitchTest(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.commander = Mock()
|
||||
self.commander.set_duty.side_effect = lambda ports, duty: {p: 1200 for p in ports}
|
||||
board = Mock(spec=Nct6687)
|
||||
board.manual_mask.return_value = 0x24
|
||||
self.top = TopFanCurve((2, 5), board_factory=lambda: board)
|
||||
self.fans = CaseFanControl(self.commander, (4, 5, 6), (1, 2, 3), top=self.top, profile=BALANCED)
|
||||
self.now = 0.0
|
||||
|
||||
def run_for(self, seconds, gpu=60.0, cpu=60.0):
|
||||
for _ in range(seconds):
|
||||
self.now += 1
|
||||
self.fans.update(gpu, self.now, cpu)
|
||||
|
||||
def test_rises_apply_at_once_and_falls_ramp_down(self):
|
||||
self.run_for(40)
|
||||
self.assertEqual((self.fans.gpu.duty, self.fans.cpu.duty), (65, 50))
|
||||
self.fans.apply_profile(PERFORMANCE)
|
||||
self.run_for(1)
|
||||
self.assertEqual((self.fans.gpu.duty, self.fans.cpu.duty), (90, 70))
|
||||
self.fans.apply_profile(QUIET)
|
||||
self.run_for(9)
|
||||
self.assertEqual(self.fans.gpu.duty, 90) # held 10 s after the last rise
|
||||
self.run_for(30)
|
||||
self.assertEqual((self.fans.gpu.duty, self.fans.cpu.duty), (55, 40))
|
||||
|
||||
def test_top_fans_take_the_profile_start_temperature(self):
|
||||
self.fans.apply_profile(QUIET)
|
||||
self.run_for(90, gpu=45, cpu=40) # start-up boost, ramp-down, then 30 s below Quiet's 50 C stop
|
||||
self.assertFalse(self.top.running)
|
||||
self.fans.apply_profile(PERFORMANCE) # starts the top fans at 45 C
|
||||
self.run_for(1, gpu=45, cpu=40)
|
||||
self.assertTrue(self.top.running)
|
||||
self.fans.apply_profile(FULL)
|
||||
self.run_for(1, gpu=30, cpu=30)
|
||||
self.assertEqual((self.fans.gpu.duty, self.fans.cpu.duty, self.top.duty), (100, 100, 100))
|
||||
|
||||
def test_snapshot_names_the_profile_and_each_group(self):
|
||||
self.run_for(1)
|
||||
self.fans.apply_profile(PERFORMANCE)
|
||||
snap = self.fans.snapshot()
|
||||
self.assertEqual(snap["profile"], "performance")
|
||||
self.assertEqual([g["name"] for g in snap["groups"]], ["GPU", "CPU"])
|
||||
self.assertEqual(snap["groups"][0]["rpms"], {"4": 1200, "5": 1200, "6": 1200})
|
||||
self.assertEqual(snap["top"]["channels"], [2, 5])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,310 @@
|
||||
import http.client
|
||||
import json
|
||||
import socket
|
||||
import threading
|
||||
import time
|
||||
import unittest
|
||||
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import patch
|
||||
|
||||
from kurgan.ai.service import CLIENT_GONE, RouteError
|
||||
from kurgan.web import proxy
|
||||
from kurgan.web.server import WebServer
|
||||
|
||||
|
||||
def free_port() -> int:
|
||||
with socket.socket() as s:
|
||||
s.bind(("127.0.0.1", 0))
|
||||
return s.getsockname()[1]
|
||||
|
||||
|
||||
class Upstream:
|
||||
"""A stand-in LLM server: records each request; /stream sends one event, waits, then another."""
|
||||
|
||||
def __init__(self):
|
||||
self.requests = []
|
||||
self.release_stream = threading.Event()
|
||||
self.release_slow = threading.Event()
|
||||
upstream = self
|
||||
|
||||
class Handler(BaseHTTPRequestHandler):
|
||||
def log_message(self, *args):
|
||||
pass
|
||||
|
||||
def _any(self):
|
||||
length = int(self.headers.get("Content-Length", "0"))
|
||||
body = self.rfile.read(length) if length else b""
|
||||
upstream.requests.append({"method": self.command, "path": self.path,
|
||||
"headers": dict(self.headers.items()), "body": body})
|
||||
if self.path.endswith("/stream"):
|
||||
self.send_response(200)
|
||||
self.send_header("Content-Type", "text/event-stream")
|
||||
self.end_headers()
|
||||
self.wfile.write(b"data: one\n\n")
|
||||
self.wfile.flush()
|
||||
upstream.release_stream.wait(5)
|
||||
self.wfile.write(b"data: two\n\n")
|
||||
return
|
||||
if self.path.endswith("/slow"): # a queued request: nothing until the server gets to it
|
||||
upstream.release_slow.wait(10)
|
||||
if self.path.endswith("/moved"):
|
||||
self.send_response(302)
|
||||
self.send_header("Location", f"http://127.0.0.1:{upstream.port}{upstream.prefix}/elsewhere")
|
||||
self.send_header("Content-Length", "0")
|
||||
self.end_headers()
|
||||
return
|
||||
data = json.dumps({"path": self.path}).encode()
|
||||
self.send_response(200)
|
||||
self.send_header("Content-Type", "application/json")
|
||||
self.send_header("Content-Length", str(len(data)))
|
||||
self.end_headers()
|
||||
self.wfile.write(data)
|
||||
|
||||
do_GET = do_POST = do_DELETE = do_HEAD = _any
|
||||
|
||||
self.prefix = ""
|
||||
self.httpd = ThreadingHTTPServer(("127.0.0.1", 0), Handler)
|
||||
self.httpd.daemon_threads = True
|
||||
self.httpd.handle_error = lambda request, address: None # a reply to a dropped request fails; expected
|
||||
self.port = self.httpd.server_address[1]
|
||||
threading.Thread(target=self.httpd.serve_forever, daemon=True).start()
|
||||
|
||||
def close(self):
|
||||
self.release_stream.set()
|
||||
self.release_slow.set()
|
||||
self.httpd.shutdown()
|
||||
self.httpd.server_close()
|
||||
|
||||
|
||||
class FakeBackend:
|
||||
def __init__(self, key, port, prefix, model):
|
||||
self.key, self.label, self.port, self.prefix, self.model = key, key.capitalize(), port, prefix, model
|
||||
|
||||
def model_ids(self):
|
||||
return [self.model]
|
||||
|
||||
def proxy_headers(self):
|
||||
return {"Authorization": "Bearer sk-local"} if self.key == "llama" else {}
|
||||
|
||||
|
||||
class FakeAi:
|
||||
def __init__(self, backends):
|
||||
self.slots = {b.key: SimpleNamespace(backend=b) for b in backends}
|
||||
self.up = {b.key: True for b in backends}
|
||||
self.calls = []
|
||||
self.error = None
|
||||
self.wait_for_client = False # act like a claim waiting for the other server
|
||||
|
||||
def running(self, key):
|
||||
return self.up[key]
|
||||
|
||||
def claim(self, key, gone=None):
|
||||
self.calls.append(("claim", key))
|
||||
if self.error is not None:
|
||||
raise self.error
|
||||
deadline = time.monotonic() + 10
|
||||
while self.wait_for_client and time.monotonic() < deadline:
|
||||
if gone():
|
||||
raise RouteError("while waiting for Strata to finish", CLIENT_GONE)
|
||||
time.sleep(0.05)
|
||||
return self.slots[key].backend
|
||||
|
||||
def release(self, key):
|
||||
self.calls.append(("release", key))
|
||||
|
||||
|
||||
class FakeApp:
|
||||
def __init__(self, ai):
|
||||
self.ai = ai
|
||||
|
||||
def state(self):
|
||||
return {"ok": True}
|
||||
|
||||
|
||||
class ProxyTest(unittest.TestCase):
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
cls.upstream = Upstream()
|
||||
cls.upstream.prefix = "/llama"
|
||||
cls.llama = FakeBackend("llama", cls.upstream.port, "/llama", "qwen")
|
||||
cls.strata = FakeBackend("strata", cls.upstream.port, "", "orca")
|
||||
cls.ai = FakeAi([cls.strata, cls.llama])
|
||||
cls.port = free_port()
|
||||
cls.server = WebServer(FakeApp(cls.ai), cls.port)
|
||||
cls.server.start()
|
||||
|
||||
@classmethod
|
||||
def tearDownClass(cls):
|
||||
cls.server.close()
|
||||
cls.upstream.close()
|
||||
|
||||
def setUp(self):
|
||||
self.upstream.requests.clear()
|
||||
self.ai.calls.clear()
|
||||
self.ai.up = {"strata": True, "llama": True}
|
||||
self.ai.error = None
|
||||
self.ai.wait_for_client = False
|
||||
self.llama.port = self.upstream.port
|
||||
self.upstream.release_slow.clear()
|
||||
|
||||
def request(self, method, path, body=None, headers=None, chunked=False):
|
||||
connection = http.client.HTTPConnection("127.0.0.1", self.port, timeout=10)
|
||||
try:
|
||||
base = {"Host": f"127.0.0.1:{self.port}", **(headers or {})}
|
||||
connection.request(method, path, body=body, headers=base, encode_chunked=chunked)
|
||||
response = connection.getresponse()
|
||||
return response.status, dict(response.getheaders()), response.read()
|
||||
finally:
|
||||
connection.close()
|
||||
|
||||
def test_a_request_is_relayed_under_the_server_s_own_path(self):
|
||||
body = json.dumps({"model": "qwen", "messages": []}).encode()
|
||||
status, _, raw = self.request("POST", "/llama/v1/chat/completions?x=1", body,
|
||||
{"Content-Type": "application/json", "Authorization": "Bearer whatever",
|
||||
"Origin": f"http://127.0.0.1:{self.port}"})
|
||||
self.assertEqual(status, 200)
|
||||
self.assertEqual(json.loads(raw), {"path": "/llama/v1/chat/completions?x=1"})
|
||||
seen = self.upstream.requests[0]
|
||||
self.assertEqual((seen["method"], seen["body"]), ("POST", body))
|
||||
self.assertEqual(seen["headers"]["Host"], f"127.0.0.1:{self.upstream.port}")
|
||||
self.assertEqual(seen["headers"]["Authorization"], "Bearer sk-local") # the server's key, whatever was sent
|
||||
self.assertNotIn("Origin", seen["headers"]) # our own page: the server sees a plain local client
|
||||
self.assertEqual(self.ai.calls, [("claim", "llama"), ("release", "llama")])
|
||||
|
||||
self.assertEqual(json.loads(self.request("GET", "/strata/")[2]), {"path": "/"}) # Strata serves from the root
|
||||
self.assertNotIn("Authorization", self.upstream.requests[-1]["headers"])
|
||||
self.assertEqual(json.loads(self.request("DELETE", "/strata/v1/x")[2]), {"path": "/v1/x"})
|
||||
|
||||
def test_a_chunked_request_body_is_passed_on_whole(self):
|
||||
status, _, _ = self.request("POST", "/strata/v1/completions", iter([b'{"prompt":', b'"hi"}']),
|
||||
{"Content-Type": "application/json"}, chunked=True)
|
||||
self.assertEqual(status, 200)
|
||||
seen = self.upstream.requests[0]
|
||||
self.assertEqual((seen["body"], seen["headers"]["Content-Length"]), (b'{"prompt":"hi"}', "15"))
|
||||
|
||||
def test_bare_route_redirects_and_redirects_are_mapped_back(self):
|
||||
status, headers, _ = self.request("GET", "/llama")
|
||||
self.assertEqual((status, headers["Location"]), (308, "/llama/"))
|
||||
self.assertEqual(self.ai.calls, [])
|
||||
status, headers, _ = self.request("GET", "/llama/moved")
|
||||
self.assertEqual((status, headers["Location"]), (302, "/llama/elsewhere"))
|
||||
|
||||
def test_other_sites_are_refused_before_anything_starts(self):
|
||||
refused = ({"Origin": "https://attacker.example"}, {"Origin": "null"},
|
||||
{"Sec-Fetch-Site": "cross-site", "Sec-Fetch-Dest": "image"},
|
||||
{"Host": "attacker.example"})
|
||||
for headers in refused:
|
||||
with self.subTest(headers=headers):
|
||||
status, _, raw = self.request("POST", "/llama/v1/chat/completions", b"{}", headers)
|
||||
self.assertEqual(status, 403)
|
||||
self.assertIn("error", json.loads(raw))
|
||||
self.assertEqual((self.ai.calls, self.upstream.requests), ([], []))
|
||||
# Following a link from another site to the chat page is fine.
|
||||
status, _, _ = self.request("GET", "/llama/", headers={"Sec-Fetch-Site": "cross-site",
|
||||
"Sec-Fetch-Dest": "document"})
|
||||
self.assertEqual(status, 200)
|
||||
|
||||
def test_model_list_is_answered_here_while_the_server_is_stopped(self):
|
||||
self.ai.up["llama"] = False
|
||||
status, _, raw = self.request("GET", "/llama/v1/models")
|
||||
self.assertEqual(status, 200)
|
||||
self.assertEqual([m["id"] for m in json.loads(raw)["data"]], ["qwen"])
|
||||
self.assertEqual(json.loads(self.request("GET", "/llama/v1/models/qwen")[2])["id"], "qwen")
|
||||
self.assertEqual(self.request("GET", "/llama/v1/models/other")[0], 404)
|
||||
self.assertEqual((self.ai.calls, self.upstream.requests), ([], []))
|
||||
self.ai.up["llama"] = True # running: the server answers for itself
|
||||
self.assertEqual(json.loads(self.request("GET", "/llama/v1/models")[2]), {"path": "/llama/v1/models"})
|
||||
|
||||
def test_errors_are_reported_openai_style(self):
|
||||
self.ai.error = RouteError("Strata is still busy with another request", 503)
|
||||
status, _, raw = self.request("POST", "/llama/v1/chat/completions", b"{}")
|
||||
self.assertEqual((status, json.loads(raw)["error"]["message"]), (503, "Strata is still busy with another request"))
|
||||
self.assertEqual(self.ai.calls, [("claim", "llama")]) # a failed claim releases itself
|
||||
|
||||
self.ai.error = None
|
||||
self.ai.calls.clear()
|
||||
self.llama.port = free_port() # nothing listening
|
||||
status, _, raw = self.request("POST", "/llama/v1/chat/completions", b"{}")
|
||||
self.assertEqual(status, 502)
|
||||
self.assertIn("isn't answering", json.loads(raw)["error"]["message"])
|
||||
self.assertEqual(self.ai.calls, [("claim", "llama"), ("release", "llama")])
|
||||
|
||||
with patch.object(proxy, "MAX_BODY", 10):
|
||||
self.assertEqual(self.request("POST", "/llama/v1/chat/completions", b"x" * 11)[0], 413)
|
||||
|
||||
def test_replies_are_streamed_as_they_are_generated(self):
|
||||
self.upstream.release_stream.clear()
|
||||
connection = http.client.HTTPConnection("127.0.0.1", self.port, timeout=10)
|
||||
try:
|
||||
connection.request("POST", "/llama/v1/stream", b"{}", {"Host": f"127.0.0.1:{self.port}"})
|
||||
response = connection.getresponse()
|
||||
self.assertEqual(response.getheader("Content-Type"), "text/event-stream")
|
||||
self.assertEqual(response.read1(1024), b"data: one\n\n") # before the server sends the rest
|
||||
self.upstream.release_stream.set()
|
||||
self.assertEqual(response.read(), b"data: two\n\n")
|
||||
finally:
|
||||
connection.close()
|
||||
self.assertEqual(self.ai.calls, [("claim", "llama"), ("release", "llama")])
|
||||
|
||||
def hang_up_after_sending(self, path):
|
||||
"""Send a request, then close the connection without reading the reply."""
|
||||
sock = socket.create_connection(("127.0.0.1", self.port), timeout=5)
|
||||
sock.sendall(f"POST {path} HTTP/1.1\r\nHost: 127.0.0.1:{self.port}\r\nContent-Type: application/json\r\n"
|
||||
f"Content-Length: 2\r\n\r\n{{}}".encode())
|
||||
time.sleep(0.3)
|
||||
sock.close()
|
||||
|
||||
def wait_for_log(self, logs, text):
|
||||
deadline = time.monotonic() + 5
|
||||
while time.monotonic() < deadline and not any(text in line for line in logs.output):
|
||||
time.sleep(0.05)
|
||||
return [line for line in logs.output if text in line]
|
||||
|
||||
def test_a_client_that_hangs_up_while_queued_is_noticed_and_the_server_told(self):
|
||||
with self.assertLogs("kurgan.web", "INFO") as logs:
|
||||
self.hang_up_after_sending("/llama/v1/slow")
|
||||
lines = self.wait_for_log(logs, "gave up")
|
||||
self.assertEqual(len(lines), 1)
|
||||
self.assertRegex(lines[0], r"POST /llama/v1/slow: the client gave up after [01] s, before Llama started its reply")
|
||||
self.assertEqual(self.ai.calls, [("claim", "llama"), ("release", "llama")]) # before the server answered
|
||||
self.assertFalse(any("ERROR" in line for line in logs.output))
|
||||
|
||||
def test_a_client_that_hangs_up_while_waiting_for_its_server_gives_up_its_place(self):
|
||||
self.ai.wait_for_client = True
|
||||
with self.assertLogs("kurgan.web", "INFO") as logs:
|
||||
self.hang_up_after_sending("/strata/v1/chat/completions")
|
||||
lines = self.wait_for_log(logs, "gave up")
|
||||
self.assertRegex(lines[0], r"the client gave up after [01] s, while waiting for Strata to finish")
|
||||
self.assertEqual(self.ai.calls, [("claim", "strata")]) # nothing reserved, so nothing to release
|
||||
self.assertEqual(self.upstream.requests, [])
|
||||
|
||||
def test_other_methods_elsewhere_are_not_allowed(self):
|
||||
self.assertEqual(self.request("DELETE", "/api/state")[0], 405)
|
||||
self.assertEqual(self.request("PUT", "/api/lighting", b"{}")[0], 405)
|
||||
self.assertEqual(self.request("OPTIONS", "/api/state")[0], 405)
|
||||
|
||||
def test_without_ai_management_the_routes_say_so(self):
|
||||
port = free_port()
|
||||
server = WebServer(SimpleNamespace(), port)
|
||||
server.start()
|
||||
try:
|
||||
connection = http.client.HTTPConnection("127.0.0.1", port, timeout=5)
|
||||
connection.request("GET", "/llama/v1/models", headers={"Host": f"127.0.0.1:{port}"})
|
||||
response = connection.getresponse()
|
||||
self.assertEqual(response.status, 503)
|
||||
self.assertIn("--no-ai", json.loads(response.read())["error"]["message"])
|
||||
connection.close()
|
||||
finally:
|
||||
server.close()
|
||||
|
||||
def test_match(self):
|
||||
self.assertEqual(proxy.match("/llama/v1/models?x=1"), ("llama", "/v1/models?x=1"))
|
||||
self.assertEqual(proxy.match("/strata"), ("strata", None))
|
||||
self.assertEqual(proxy.match("/strata?x"), ("strata", None))
|
||||
self.assertIsNone(proxy.match("/stratax/v1"))
|
||||
self.assertIsNone(proxy.match("/api/state"))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,254 @@
|
||||
import unittest
|
||||
from unittest.mock import patch
|
||||
|
||||
from kurgan.theme import Theme
|
||||
from kurgan.lighting.lighting_node import LightingNodeBusy, LightingNodeCore, direct_packets
|
||||
from kurgan.lighting.case_fans import RGBLighting, _SIDE_CHASE_ROUTES, side_chase_frame
|
||||
|
||||
|
||||
class FakeChannel:
|
||||
def __init__(self):
|
||||
self.sent: list[bytes] = []
|
||||
self.closed = False
|
||||
|
||||
def drain(self):
|
||||
pass
|
||||
|
||||
def send(self, payload):
|
||||
self.sent.append(payload)
|
||||
|
||||
def read(self, timeout_ms):
|
||||
return bytes((0, 0, 0, 9, 16)) + bytes(12)
|
||||
|
||||
def close(self):
|
||||
self.closed = True
|
||||
|
||||
|
||||
def open_node() -> tuple[LightingNodeCore, FakeChannel]:
|
||||
node, ch = LightingNodeCore(), FakeChannel()
|
||||
node.ch = ch
|
||||
return node, ch
|
||||
|
||||
|
||||
class LightingNodeProtocolTest(unittest.TestCase):
|
||||
def test_packets_split_colour_channels_in_fifties_and_skip_unchanged(self):
|
||||
colors = [(i % 256, 2, 3) for i in range(204)]
|
||||
packets = direct_packets(0, colors)
|
||||
self.assertEqual([p[:5] for p in packets[:3]],
|
||||
[bytes((0x32, 0, 0, 50, c)) for c in range(3)])
|
||||
self.assertEqual(packets[0][5:], bytes(range(50)))
|
||||
self.assertEqual(packets[-1][:5], bytes((0x32, 0, 200, 4, 2)))
|
||||
self.assertEqual(len(packets), 15)
|
||||
changed = list(colors)
|
||||
changed[120] = (0, 2, 3)
|
||||
self.assertEqual(direct_packets(0, changed, colors), [direct_packets(0, changed)[6]])
|
||||
|
||||
def test_show_takes_software_control_once_then_sends_only_changes(self):
|
||||
node, ch = open_node()
|
||||
frame = side_chase_frame(0)
|
||||
with patch("kurgan.lighting.lighting_node.time.monotonic", return_value=10.0):
|
||||
node.show(0, frame)
|
||||
self.assertEqual(ch.sent[0], bytes((0x38, 0, 0x02)))
|
||||
self.assertEqual(len(ch.sent), 1 + 15 + 1)
|
||||
self.assertEqual(ch.sent[-1], bytes((0x33, 0xFF)))
|
||||
ch.sent.clear()
|
||||
node.show(0, frame)
|
||||
self.assertEqual(ch.sent, [])
|
||||
node.show(0, side_chase_frame(1))
|
||||
self.assertTrue(0 < len(ch.sent) - 1 <= 10) # only changed red/green chunks + commit, no port state
|
||||
self.assertTrue(all(p[0] == 0x32 and p[4] in (0, 1) for p in ch.sent[:-1]))
|
||||
|
||||
def test_keepalive_recommits_and_close_returns_to_hardware_effect(self):
|
||||
node, ch = open_node()
|
||||
with patch("kurgan.lighting.lighting_node.time.monotonic", return_value=10.0):
|
||||
node.show(0, [(1, 2, 3)] * 204)
|
||||
ch.sent.clear()
|
||||
with patch("kurgan.lighting.lighting_node.time.monotonic", return_value=14.0):
|
||||
node.keepalive()
|
||||
self.assertEqual(ch.sent, [])
|
||||
with patch("kurgan.lighting.lighting_node.time.monotonic", return_value=15.5):
|
||||
node.keepalive()
|
||||
self.assertEqual(ch.sent, [bytes((0x33, 0xFF))])
|
||||
node.close()
|
||||
self.assertEqual(ch.sent[-1], bytes((0x38, 0, 0x01)))
|
||||
self.assertTrue(ch.closed)
|
||||
|
||||
def test_rejected_command_raises(self):
|
||||
node, ch = open_node()
|
||||
ch.read = lambda timeout_ms: bytes((0, 1)) + bytes(15)
|
||||
with self.assertRaisesRegex(OSError, "0x38"):
|
||||
node.show(0, [(0, 0, 0)])
|
||||
|
||||
def test_steps_aside_for_competing_corsair_software_before_opening(self):
|
||||
with patch("kurgan.lighting.lighting_node.corsair_software_running", return_value=True) as running, \
|
||||
patch("kurgan.lighting.lighting_node.hid_device_paths") as paths:
|
||||
with self.assertRaises(LightingNodeBusy):
|
||||
LightingNodeCore().open()
|
||||
running.assert_called_once_with("Corsair Lighting Node Core", fan_tools=False)
|
||||
paths.assert_not_called()
|
||||
|
||||
|
||||
class FakeNode:
|
||||
def __init__(self):
|
||||
self.opened = 0
|
||||
self.closed = 0
|
||||
self.frames: list[list[tuple[int, int, int]]] = []
|
||||
self.firmware = "0.9.16"
|
||||
|
||||
def open(self):
|
||||
self.opened += 1
|
||||
|
||||
def close(self):
|
||||
self.closed += 1
|
||||
|
||||
def show(self, channel, colors):
|
||||
assert channel == 0
|
||||
self.frames.append(list(colors))
|
||||
|
||||
def keepalive(self):
|
||||
pass
|
||||
|
||||
|
||||
class RGBLightingTest(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.node = FakeNode()
|
||||
self.lighting = RGBLighting(Theme(), node_factory=lambda: self.node)
|
||||
|
||||
def test_temperature_colours_each_side_by_its_own_part_and_releases_when_off(self):
|
||||
theme = Theme()
|
||||
color = lambda t: theme.level_color(t, theme.temp_warn, theme.temp_hot)
|
||||
self.lighting.update(40, True, gpu_temp=85)
|
||||
self.assertEqual(self.node.frames[-1], [color(85)] * 102 + [color(40)] * 102)
|
||||
for led in _SIDE_CHASE_ROUTES[0]: # the CPU-side chase route lies in the CPU colour half
|
||||
self.assertEqual(self.node.frames[-1][led], color(40))
|
||||
self.assertEqual(self.lighting.status, "Temperature lighting active (GPU 85 \u00b0C, CPU 40 \u00b0C)")
|
||||
self.lighting.update(85, True) # no GPU reading: GPU side follows the CPU
|
||||
self.assertEqual(self.node.frames[-1], [color(85)] * 204)
|
||||
self.lighting.update(85, False)
|
||||
self.assertEqual(self.node.closed, 1)
|
||||
self.assertIsNone(self.lighting.node)
|
||||
self.assertEqual(self.lighting.status, "off")
|
||||
|
||||
def test_busy_or_failed_node_retries_later_without_spinning(self):
|
||||
self.node.open = lambda: (_ for _ in ()).throw(LightingNodeBusy("Lighting Node CORE busy: exit iCUE"))
|
||||
with patch("kurgan.lighting.case_fans.time.monotonic", return_value=100.0):
|
||||
self.lighting.update(40, True)
|
||||
self.assertEqual(self.lighting.status, "Lighting Node CORE busy: exit iCUE")
|
||||
self.node.open = lambda: None
|
||||
with patch("kurgan.lighting.case_fans.time.monotonic", return_value=105.0):
|
||||
self.lighting.update(40, True)
|
||||
self.assertEqual(self.node.frames, [])
|
||||
with patch("kurgan.lighting.case_fans.time.monotonic", return_value=111.0):
|
||||
self.lighting.update(40, True)
|
||||
self.assertEqual(len(self.node.frames), 1)
|
||||
self.node.show = lambda channel, colors: (_ for _ in ()).throw(OSError("unplugged"))
|
||||
with self.assertLogs("kurgan.lighting.case_fans", level="WARNING"):
|
||||
self.lighting.update(90, True)
|
||||
self.assertEqual(self.lighting.status, "Lighting Node CORE connection lost")
|
||||
self.assertIsNone(self.lighting.node)
|
||||
|
||||
def test_chase_uses_elapsed_time(self):
|
||||
for now, expected in ((100.0, 1), (100.05, 1), (100.31, 2)):
|
||||
with patch("kurgan.lighting.case_fans.time.monotonic", return_value=now):
|
||||
self.lighting.update(None, False, side_chase=True)
|
||||
self.assertEqual(len(self.node.frames), expected)
|
||||
self.assertEqual(self.node.frames, [side_chase_frame(0), side_chase_frame(2)])
|
||||
self.lighting.update(None, False)
|
||||
self.assertEqual(self.node.closed, 1)
|
||||
def test_chase_cpu_route_and_mirrored_gpu_route(self):
|
||||
cpu, gpu = _SIDE_CHASE_ROUTES
|
||||
expected_cpu = (
|
||||
list(range(147, 158)) + [146]
|
||||
+ [183, 182, 181, 180, 191, 190]
|
||||
+ list(range(116, 124)) + list(range(112, 116))
|
||||
+ list(range(189, 183, -1))
|
||||
)
|
||||
self.assertEqual(list(cpu), expected_cpu)
|
||||
for route in (cpu, gpu):
|
||||
self.assertEqual(len(route), 36)
|
||||
self.assertEqual(len(set(route)), 36)
|
||||
self.assertTrue(all(10 <= index % 34 < 22 for index in route))
|
||||
# Compare physical clock positions, not raw indices, because mounts differ.
|
||||
cpu_right = {4: 11, 5: 20, 3: 20}
|
||||
gpu_fan = {4: 0, 5: 1, 3: 2}
|
||||
for cpu_led, gpu_led in zip(cpu, gpu):
|
||||
fan, local = divmod(cpu_led, 34)
|
||||
self.assertEqual(gpu_led // 34, gpu_fan[fan])
|
||||
cpu_clock = (local - cpu_right[fan]) % 12
|
||||
gpu_clock = (gpu_led % 34 - 17) % 12
|
||||
self.assertEqual(gpu_clock, 11 - cpu_clock)
|
||||
|
||||
def test_chase_has_one_head_per_side_and_four_fading_trail_leds(self):
|
||||
for step in (0, 1, 12, 18, 30, 35, 36, 1000):
|
||||
with self.subTest(step=step):
|
||||
frame = side_chase_frame(step)
|
||||
self.assertEqual(len(frame), 204)
|
||||
for route in _SIDE_CHASE_ROUTES:
|
||||
lit = {led: frame[led] for led in route if frame[led] != (24, 0, 0)}
|
||||
expected = {
|
||||
route[(step - age) % 36]: color
|
||||
for age, color in enumerate(((255, 48, 0), (209, 38, 0), (163, 29, 0),
|
||||
(116, 19, 0), (70, 10, 0)))
|
||||
}
|
||||
self.assertEqual(lit, expected)
|
||||
inner_lit = {
|
||||
index: frame[index]
|
||||
for fan in {led // 34 for led in route}
|
||||
for index in range(fan * 34 + 22, fan * 34 + 34)
|
||||
if frame[index] != (24, 0, 0)
|
||||
}
|
||||
self.assertEqual(len(inner_lit), 5)
|
||||
for outer, color in expected.items():
|
||||
fan, local = divmod(outer, 34)
|
||||
right = (17, 17, 17, 20, 11, 20)[fan]
|
||||
outer_clock = (local - right) % 12
|
||||
inner = next(index for index, value in inner_lit.items() if value == color)
|
||||
self.assertEqual(inner // 34, fan)
|
||||
inner_clock = (inner % 34 - 22 - (right - 10)) % 12
|
||||
self.assertEqual(inner_clock, 11 - outer_clock)
|
||||
for index, color in enumerate(frame):
|
||||
if index % 34 < 10:
|
||||
self.assertEqual(color, (48, 0, 0))
|
||||
self.assertEqual(side_chase_frame(0), side_chase_frame(36))
|
||||
|
||||
def test_chase_speeds_up_with_power_without_jumping(self):
|
||||
self.assertAlmostEqual(self.lighting.chase_rate(None), 1 / 0.15)
|
||||
self.assertAlmostEqual(self.lighting.chase_rate(100), 1 / 0.15)
|
||||
self.assertAlmostEqual(self.lighting.chase_rate(350), (1 / 0.15 + 1 / 0.025) / 2)
|
||||
self.assertAlmostEqual(self.lighting.chase_rate(900), 1 / 0.025)
|
||||
|
||||
steps = []
|
||||
|
||||
def tick(now, watts=None):
|
||||
if watts is not None:
|
||||
self.lighting.set_power(watts)
|
||||
with patch("kurgan.lighting.case_fans.time.monotonic", return_value=now):
|
||||
self.lighting.update(None, False, side_chase=True)
|
||||
steps.append(self.lighting._last_chase_step)
|
||||
|
||||
self.lighting.set_power(120)
|
||||
tick(100.0)
|
||||
for i in range(1, 31): # 1.5 s at idle: 10 LEDs
|
||||
tick(100.0 + i * 0.05)
|
||||
self.assertEqual(steps[-1], 10)
|
||||
for i in range(1, 121): # power jumps to 600 W for 6 s
|
||||
tick(101.5 + i * 0.05, 600)
|
||||
self.assertEqual(max(b - a for a, b in zip(steps, steps[1:])), 2)
|
||||
self.assertGreater(steps[-1] - steps[30], 180) # mostly at 40 LEDs/s once eased in
|
||||
self.assertEqual(self.lighting.status, "Red side chase active (25 ms/LED at 600 W)")
|
||||
|
||||
def test_fast_chase_caps_core_frames_but_keeps_its_speed(self):
|
||||
self.lighting.set_power(900)
|
||||
self.lighting._chase_timing.rate = 40.0
|
||||
with patch("kurgan.lighting.case_fans.time.monotonic", return_value=100.0):
|
||||
self.lighting.update(None, False, side_chase=True)
|
||||
self.lighting._chase_timing.rate = 40.0
|
||||
for i in range(1, 101): # polled every 10 ms for 1 s
|
||||
with patch("kurgan.lighting.case_fans.time.monotonic", return_value=100.0 + i * 0.01):
|
||||
self.lighting.update(None, False, side_chase=True)
|
||||
self.assertLessEqual(len(self.node.frames), 23)
|
||||
self.assertIn(self.lighting._last_chase_step, (39, 40))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,103 @@
|
||||
import json
|
||||
import os
|
||||
import tempfile
|
||||
import unittest
|
||||
from unittest.mock import patch
|
||||
|
||||
from kurgan.settings import DEFAULTS, Settings, SettingsError, validate
|
||||
|
||||
|
||||
class ValidateTest(unittest.TestCase):
|
||||
def test_empty_file_gets_defaults(self):
|
||||
self.assertEqual(validate({}), DEFAULTS)
|
||||
|
||||
def test_fan_ports_are_checked_like_the_command_line(self):
|
||||
ok = validate({"cooling": {"gpu_ports": [4, 5, 6], "cpu_ports": [1, 2, 3], "top_channels": [5, 2]}})
|
||||
self.assertEqual(ok["cooling"]["top_channels"], [2, 5])
|
||||
for cooling in ({"gpu_ports": [4, 5]}, {"gpu_ports": [4, 4, 5]}, {"gpu_ports": [4, 5, 7]},
|
||||
{"gpu_ports": "4,5,6"}, {"gpu_ports": [4, 5, 6.0]},
|
||||
{"cpu_ports": [1, 2, 3]}, # CPU side without the GPU side
|
||||
{"gpu_ports": [4, 5, 6], "cpu_ports": [3, 4, 1]}, # overlap
|
||||
{"gpu_ports": [4, 5, 6], "top_channels": [9]},
|
||||
{"profile": "turbo"}):
|
||||
with self.subTest(cooling=cooling), self.assertRaises(SettingsError):
|
||||
validate({"cooling": cooling})
|
||||
|
||||
def test_lighting_modes_follow_each_zone(self):
|
||||
self.assertEqual(validate({"lighting": {"memory": "chase"}})["lighting"]["memory"], "chase")
|
||||
for lighting in ({"gpu": "temperature"}, {"case_fans": "rainbow"}, {"keyboard": "off"}):
|
||||
with self.subTest(lighting=lighting), self.assertRaises(SettingsError):
|
||||
validate({"lighting": lighting})
|
||||
|
||||
def test_ai_choices_and_ports(self):
|
||||
self.assertEqual(validate({"ai": {"active": "llama"}})["ai"]["active"], "llama")
|
||||
for ai in ({"active": "ollama"}, {"strata_model": "q8"}, {"strata_port": 80},
|
||||
{"strata_port": 9000, "llama_port": 9000}, {"llama_server": ""}):
|
||||
with self.subTest(ai=ai), self.assertRaises(SettingsError):
|
||||
validate({"ai": ai})
|
||||
|
||||
def test_unknown_sections_and_keys_are_errors_not_ignored(self):
|
||||
for data in ([], {"extra": {}}, {"web": {"port": 8080, "host": "0.0.0.0"}}, {"web": 8080}):
|
||||
with self.subTest(data=data), self.assertRaises(SettingsError):
|
||||
validate(data)
|
||||
|
||||
|
||||
class SettingsFileTest(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.dir = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(self.dir.cleanup)
|
||||
self.path = os.path.join(self.dir.name, "Kurgan", "settings.json")
|
||||
self.legacy = os.path.join(self.dir.name, "TTLcdDashboard")
|
||||
os.makedirs(self.legacy)
|
||||
|
||||
def write_legacy(self, name, data):
|
||||
with open(os.path.join(self.legacy, name), "w", encoding="utf-8") as f:
|
||||
json.dump(data, f)
|
||||
|
||||
def test_first_start_imports_the_dashboard_settings_and_the_seed(self):
|
||||
self.write_legacy("fan-control.json", {"gpu_ports": [4, 5, 6], "cpu_ports": [1, 2, 3], "top_channels": [2, 5]})
|
||||
self.write_legacy("memory-lighting.json", {"mode": "temperature"})
|
||||
self.write_legacy("gpu-lighting.json", {"mode": "off"})
|
||||
settings = Settings(self.path, self.legacy, seed={"lighting": {"case_fans": "chase"}})
|
||||
self.assertTrue(settings.created)
|
||||
self.assertEqual(settings.section("cooling"), {"profile": "balanced", "gpu_ports": [4, 5, 6],
|
||||
"cpu_ports": [1, 2, 3], "top_channels": [2, 5]})
|
||||
self.assertEqual(settings.section("lighting"), {"case_fans": "chase", "memory": "temperature", "gpu": "off"})
|
||||
with open(self.path, encoding="utf-8") as f:
|
||||
self.assertEqual(json.load(f)["lighting"]["case_fans"], "chase")
|
||||
|
||||
def test_seed_applies_only_when_the_file_is_created(self):
|
||||
Settings(self.path, None).update("lighting", case_fans="temperature")
|
||||
settings = Settings(self.path, None, seed={"lighting": {"case_fans": "chase"}})
|
||||
self.assertFalse(settings.created)
|
||||
self.assertEqual(settings.get("lighting", "case_fans"), "temperature")
|
||||
|
||||
def test_corrupt_legacy_or_settings_file_stops_startup(self):
|
||||
self.write_legacy("memory-lighting.json", {"mode": "rainbow"})
|
||||
with self.assertRaises(SettingsError):
|
||||
Settings(self.path, self.legacy)
|
||||
os.makedirs(os.path.dirname(self.path))
|
||||
with open(self.path, "w", encoding="utf-8") as f:
|
||||
f.write("{not json")
|
||||
with self.assertRaises(SettingsError):
|
||||
Settings(self.path, self.legacy)
|
||||
|
||||
def test_invalid_or_failed_update_changes_nothing(self):
|
||||
settings = Settings(self.path, None)
|
||||
settings.update("cooling", profile="quiet")
|
||||
with self.assertRaises(SettingsError):
|
||||
settings.update("cooling", profile="turbo")
|
||||
with patch("kurgan.settings.os.replace", side_effect=OSError("denied")), self.assertRaises(OSError):
|
||||
settings.update("cooling", profile="performance")
|
||||
self.assertEqual(settings.get("cooling", "profile"), "quiet")
|
||||
self.assertEqual(Settings(self.path, None).get("cooling", "profile"), "quiet")
|
||||
self.assertEqual(sorted(os.listdir(os.path.dirname(self.path))), ["settings.json"])
|
||||
|
||||
def test_returned_sections_are_copies(self):
|
||||
settings = Settings(self.path, None)
|
||||
settings.section("lighting")["memory"] = "chase"
|
||||
self.assertEqual(settings.get("lighting", "memory"), "off")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,132 @@
|
||||
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 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")])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
Reference in new issue
Block a user