feat: registry, runner and entry point
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
This commit is contained in:
1 parent
6713e09791
commit
0a395fa735
7 files changed
+487
No files matched your search
@@ -0,0 +1,118 @@
|
||||
import sys
|
||||
import threading
|
||||
import types
|
||||
from enum import Enum
|
||||
|
||||
import pytest
|
||||
from PIL import Image
|
||||
|
||||
import main
|
||||
import registry
|
||||
from lcdkit import BG
|
||||
from view import Patch
|
||||
|
||||
|
||||
class FakeLcd:
|
||||
instances = []
|
||||
|
||||
def __init__(self, com_port="AUTO"):
|
||||
self.com_port = com_port
|
||||
self.calls, self.closed, self.orientation, self.brightness = [], False, None, None
|
||||
FakeLcd.instances.append(self)
|
||||
|
||||
def InitializeComm(self): ...
|
||||
|
||||
def SetOrientation(self, o):
|
||||
self.orientation = o
|
||||
|
||||
def SetBrightness(self, b):
|
||||
self.brightness = b
|
||||
|
||||
def DisplayPILImage(self, image, x=0, y=0, image_width=None, image_height=None):
|
||||
self.calls.append((image.size, x, y))
|
||||
|
||||
def closeSerial(self):
|
||||
self.closed = True
|
||||
|
||||
|
||||
class FakeOrientation(Enum):
|
||||
PORTRAIT = 0
|
||||
REVERSE_PORTRAIT = 1
|
||||
LANDSCAPE = 2
|
||||
REVERSE_LANDSCAPE = 3
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def fake_library(monkeypatch):
|
||||
FakeLcd.instances = []
|
||||
lib = types.ModuleType("library")
|
||||
lcd = types.ModuleType("library.lcd")
|
||||
comm = types.ModuleType("library.lcd.lcd_comm")
|
||||
comm.Orientation = FakeOrientation
|
||||
rev_a = types.ModuleType("library.lcd.lcd_comm_rev_a")
|
||||
rev_a.LcdCommRevA = FakeLcd
|
||||
for name, mod in (("library", lib), ("library.lcd", lcd), ("library.lcd.lcd_comm", comm),
|
||||
("library.lcd.lcd_comm_rev_a", rev_a)):
|
||||
monkeypatch.setitem(sys.modules, name, mod)
|
||||
monkeypatch.setenv("SCREEN_DEVICE", "/dev/fake")
|
||||
|
||||
|
||||
class StubView:
|
||||
name = "stub"
|
||||
|
||||
def __init__(self):
|
||||
self.started = self.stopped = False
|
||||
|
||||
def start(self):
|
||||
self.started = True
|
||||
|
||||
def stop(self):
|
||||
self.stopped = True
|
||||
|
||||
def frame_key(self, now):
|
||||
return "k"
|
||||
|
||||
def render(self, now):
|
||||
return Image.new("RGB", (480, 320), BG)
|
||||
|
||||
def patch(self, now):
|
||||
return None
|
||||
|
||||
|
||||
def stop_soon(seconds=0.4):
|
||||
stop = threading.Event()
|
||||
threading.Timer(seconds, stop.set).start()
|
||||
return stop
|
||||
|
||||
|
||||
def test_unknown_view_shows_error_and_stays_up_until_stopped(monkeypatch):
|
||||
monkeypatch.setenv("VIEW", "bogus")
|
||||
main.main(stop_soon())
|
||||
lcd = FakeLcd.instances[0]
|
||||
assert lcd.calls == [((480, 320), 0, 0)] # the error screen, drawn once
|
||||
assert lcd.closed
|
||||
|
||||
|
||||
def test_missing_view_variable_is_an_error_screen_too(monkeypatch):
|
||||
monkeypatch.delenv("VIEW", raising=False)
|
||||
main.main(stop_soon())
|
||||
assert FakeLcd.instances[0].calls == [((480, 320), 0, 0)]
|
||||
|
||||
|
||||
def test_known_view_runs_and_is_stopped_cleanly(monkeypatch):
|
||||
view = StubView()
|
||||
monkeypatch.setitem(registry.REGISTRY, "stub", lambda: view)
|
||||
monkeypatch.setenv("VIEW", "stub")
|
||||
main.main(stop_soon())
|
||||
lcd = FakeLcd.instances[0]
|
||||
assert view.started and view.stopped and lcd.closed
|
||||
assert lcd.calls[0] == ((480, 320), 0, 0)
|
||||
|
||||
|
||||
def test_settings_reach_the_screen(monkeypatch):
|
||||
monkeypatch.setitem(registry.REGISTRY, "stub", StubView)
|
||||
monkeypatch.setenv("VIEW", "stub")
|
||||
monkeypatch.setenv("SCREEN_BRIGHTNESS", "70")
|
||||
main.main(stop_soon(0.2))
|
||||
lcd = FakeLcd.instances[0]
|
||||
assert (lcd.com_port, lcd.orientation, lcd.brightness) == ("/dev/fake", FakeOrientation.LANDSCAPE, 70)
|
||||
@@ -0,0 +1,24 @@
|
||||
import pytest
|
||||
|
||||
from registry import REGISTRY, UnknownView, make_view
|
||||
|
||||
|
||||
def test_registry_has_both_views():
|
||||
assert sorted(REGISTRY) == ["server", "weather"]
|
||||
|
||||
|
||||
def test_make_view_builds_named_views():
|
||||
assert make_view("weather").name == "weather"
|
||||
assert make_view("server").name == "server"
|
||||
|
||||
|
||||
def test_make_view_unknown_lists_valid_names():
|
||||
with pytest.raises(UnknownView) as err:
|
||||
make_view("bogus")
|
||||
assert err.value.name == "bogus"
|
||||
assert err.value.valid == ["server", "weather"]
|
||||
|
||||
|
||||
def test_make_view_empty_name_is_unknown():
|
||||
with pytest.raises(UnknownView):
|
||||
make_view("")
|
||||
@@ -0,0 +1,140 @@
|
||||
import logging
|
||||
from datetime import datetime, timedelta
|
||||
|
||||
import pytest
|
||||
from PIL import Image
|
||||
|
||||
import runner
|
||||
from lcdkit import BG, INK
|
||||
from tests.helpers import count_colour
|
||||
from view import Patch
|
||||
|
||||
|
||||
class FakeLcd:
|
||||
def __init__(self, fail_first=0, always_fail=False):
|
||||
self.calls = [] # (size, x, y)
|
||||
self._fail_first, self._always_fail = fail_first, always_fail
|
||||
|
||||
def DisplayPILImage(self, image, x=0, y=0, image_width=None, image_height=None):
|
||||
if self._always_fail or self._fail_first > 0:
|
||||
self._fail_first -= 1
|
||||
raise OSError("serial hiccup")
|
||||
self.calls.append((image.size, x, y))
|
||||
|
||||
|
||||
class StubView:
|
||||
name = "stub"
|
||||
|
||||
def __init__(self, keys, with_patch=True):
|
||||
self._keys = keys # callable(now) -> key
|
||||
self._with_patch = with_patch
|
||||
self.renders = 0
|
||||
|
||||
def start(self): ...
|
||||
def stop(self): ...
|
||||
|
||||
def frame_key(self, now):
|
||||
return self._keys(now)
|
||||
|
||||
def render(self, now):
|
||||
self.renders += 1
|
||||
return Image.new("RGB", (480, 320), BG)
|
||||
|
||||
def patch(self, now):
|
||||
return Patch(Image.new("RGB", (10, 5), BG), 100, 50) if self._with_patch else None
|
||||
|
||||
|
||||
def ticks(n):
|
||||
"""running() that is true for the first n calls."""
|
||||
state = {"left": n}
|
||||
|
||||
def running():
|
||||
state["left"] -= 1
|
||||
return state["left"] >= 0
|
||||
|
||||
return running
|
||||
|
||||
|
||||
def clock(start, step_s):
|
||||
state = {"now": start - timedelta(seconds=step_s)}
|
||||
|
||||
def now_fn():
|
||||
state["now"] += timedelta(seconds=step_s)
|
||||
return state["now"]
|
||||
|
||||
return now_fn
|
||||
|
||||
|
||||
T0 = datetime(2026, 10, 22, 14, 32, 0)
|
||||
|
||||
|
||||
def test_run_pushes_full_frame_once_per_key():
|
||||
lcd, view = FakeLcd(), StubView(lambda now: "same", with_patch=False)
|
||||
runner.run(view, lcd, now_fn=clock(T0, 0), running=ticks(3), sleep=lambda s: None)
|
||||
assert lcd.calls == [((480, 320), 0, 0)]
|
||||
|
||||
|
||||
def test_run_pushes_patch_each_new_second_only():
|
||||
lcd, view = FakeLcd(), StubView(lambda now: "same")
|
||||
# ticks at seconds 0, 0, 1, 1, 2 -> full frame, then one patch per *new* second
|
||||
seconds = iter([0, 0, 1, 1, 2])
|
||||
now_fn = lambda: T0.replace(second=next(seconds))
|
||||
runner.run(view, lcd, now_fn=now_fn, running=ticks(5), sleep=lambda s: None)
|
||||
assert lcd.calls == [((480, 320), 0, 0), ((10, 5), 100, 50), ((10, 5), 100, 50)]
|
||||
|
||||
|
||||
def test_run_pushes_full_frame_when_key_changes():
|
||||
lcd, view = FakeLcd(), StubView(lambda now: now.minute)
|
||||
runner.run(view, lcd, now_fn=clock(T0, 60), running=ticks(3), sleep=lambda s: None)
|
||||
assert [c[0] for c in lcd.calls] == [(480, 320)] * 3
|
||||
|
||||
|
||||
def test_run_retries_failed_draw_and_continues():
|
||||
lcd, view = FakeLcd(fail_first=1), StubView(lambda now: "same", with_patch=False)
|
||||
runner.run(view, lcd, now_fn=clock(T0, 0), running=ticks(3), sleep=lambda s: None)
|
||||
assert lcd.calls == [((480, 320), 0, 0)] # failed once, redrawn on the next tick, then stable
|
||||
|
||||
|
||||
def test_run_raises_after_max_failures():
|
||||
lcd, view = FakeLcd(always_fail=True), StubView(lambda now: "same")
|
||||
with pytest.raises(OSError):
|
||||
runner.run(view, lcd, now_fn=clock(T0, 0), running=ticks(50), sleep=lambda s: None, max_failures=3)
|
||||
|
||||
|
||||
def test_open_screen_retries_until_available(caplog):
|
||||
attempts, sleeps = [], []
|
||||
|
||||
def factory():
|
||||
attempts.append(1)
|
||||
if len(attempts) < 3:
|
||||
raise OSError("no such device")
|
||||
return "lcd"
|
||||
|
||||
with caplog.at_level(logging.WARNING):
|
||||
result = runner.open_screen(factory, running=lambda: True, sleep=sleeps.append)
|
||||
assert result == "lcd"
|
||||
assert sleeps == [30.0, 30.0]
|
||||
assert len([r for r in caplog.records if r.levelno == logging.WARNING]) == 1 # logged once
|
||||
|
||||
|
||||
def test_open_screen_returns_none_when_stopped():
|
||||
def factory():
|
||||
raise OSError("no such device")
|
||||
|
||||
assert runner.open_screen(factory, running=ticks(1), sleep=lambda s: None) is None
|
||||
|
||||
|
||||
def test_idle_with_message_draws_once_and_returns_on_stop():
|
||||
lcd = FakeLcd()
|
||||
runner.idle_with_message(lcd, ["UNKNOWN VIEW: bogus"], running=ticks(4), sleep=lambda s: None)
|
||||
assert lcd.calls == [((480, 320), 0, 0)]
|
||||
|
||||
|
||||
def test_render_error_size_and_has_ink():
|
||||
img = runner.render_error(["UNKNOWN VIEW: bogus", "VALID: server, weather"])
|
||||
assert img.size == (480, 320)
|
||||
assert count_colour(img, INK) > 500
|
||||
|
||||
|
||||
def test_render_error_long_line_does_not_raise():
|
||||
assert runner.render_error(["X" * 500]).size == (480, 320)
|
||||
Reference in new issue
Block a user