166 lines
5.2 KiB
Python
166 lines
5.2 KiB
Python
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)
|
|
|
|
|
|
def test_open_screen_retries_when_the_library_calls_sys_exit():
|
|
"""The pinned screen library calls sys.exit(0) when the port is missing; that must not end the process."""
|
|
attempts, sleeps = [], []
|
|
|
|
def factory():
|
|
attempts.append(1)
|
|
if len(attempts) < 3:
|
|
raise SystemExit(0)
|
|
return "lcd"
|
|
|
|
assert runner.open_screen(factory, running=lambda: True, sleep=sleeps.append) == "lcd"
|
|
assert sleeps == [30.0, 30.0]
|
|
|
|
|
|
def test_run_counts_library_sys_exit_as_a_failed_draw():
|
|
class ExitingLcd:
|
|
def DisplayPILImage(self, *a, **k):
|
|
raise SystemExit(0)
|
|
|
|
view = StubView(lambda now: "same")
|
|
with pytest.raises(SystemExit): # after max_failures; Docker then restarts and open_screen retries
|
|
runner.run(view, ExitingLcd(), now_fn=clock(T0, 0), running=ticks(50), sleep=lambda s: None, max_failures=3)
|
|
assert view.renders == 3 # it tried three times first
|