You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
TuringSmartScreen/tests/test_main.py

252 lines
8.2 KiB

import logging
import signal
import threading
import time
from datetime import datetime
import pytest
from PIL import ImageChops
import ramscreen.__main__ as main_module
from ramscreen.__main__ import main, run
from ramscreen.config import Config
from ramscreen.meminfo import App, Memory
from ramscreen.render import render, render_stopped
GIB = 2**30
MEM = Memory(total=16 * GIB, available=8 * GIB, swap_total=2 * GIB, swap_free=GIB)
APPS = [App("firefox", GIB)]
NOW = datetime(2026, 10, 14, 12, 0)
FAST = Config(memory_interval=0, apps_interval=10)
class FakeLcd:
def __init__(self, open_failures=0, show_failures=()):
self.calls = []
self.shown = [] # (x, y, Bild)
self.open_failures = open_failures
self.show_failures = set(show_failures)
self._show_count = 0
def open(self):
self.calls.append("open")
if self.open_failures > 0:
self.open_failures -= 1
raise OSError("kein Gerät")
def close(self):
self.calls.append("close")
def set_orientation_portrait(self):
self.calls.append("orientation")
def set_brightness(self, percent):
self.calls.append(("brightness", percent))
def show(self, image, x, y):
index = self._show_count
self._show_count += 1
if index in self.show_failures:
raise OSError("Schreibfehler")
self.calls.append("show")
self.shown.append((x, y, image))
def stop_after(stop, iterations):
count = 0
def read_memory():
nonlocal count
count += 1
if count >= iterations:
stop.set()
return MEM
return read_memory
def run_fake(lcd, iterations, cfg=FAST, **kwargs):
stop = threading.Event()
kwargs.setdefault("top_apps", lambda n: APPS)
run(cfg, lcd, stop, read_memory=stop_after(stop, iterations), now=lambda: NOW,
reconnect_delay=0, **kwargs)
def sizes(lcd):
return [(x, y, img.size) for x, y, img in lcd.shown]
def test_normaler_ablauf():
lcd = FakeLcd()
run_fake(lcd, iterations=2)
assert lcd.calls[:3] == ["open", "orientation", ("brightness", 20)]
# 1. Durchlauf Vollbild, 2. Durchlauf unverändert → nichts, dann Endbildschirm als Vollbild
assert sizes(lcd) == [(0, 0, (320, 480)), (0, 0, (320, 480))]
assert lcd.calls[-1] == "close"
assert lcd.calls.count("open") == 1
def test_schreibfehler_fuehrt_zu_neuverbindung_und_vollbild():
lcd = FakeLcd(show_failures={0})
run_fake(lcd, iterations=2)
assert lcd.calls.count("open") == 2
assert lcd.calls[:6] == ["open", "orientation", ("brightness", 20), "close", "open", "orientation"]
assert sizes(lcd)[0] == (0, 0, (320, 480))
def test_display_beim_start_nicht_da():
lcd = FakeLcd(open_failures=2)
run_fake(lcd, iterations=1)
assert lcd.calls.count("open") == 3
assert sizes(lcd)[0] == (0, 0, (320, 480))
def test_stoppen_waehrend_wartezeit_beendet_sofort():
lcd = FakeLcd(open_failures=10**6)
stop = threading.Event()
t = threading.Thread(
target=run,
args=(FAST, lcd, stop),
kwargs={"read_memory": lambda: MEM, "top_apps": lambda n: APPS, "now": lambda: NOW, "reconnect_delay": 5},
)
t.start()
time.sleep(0.2)
stop.set()
t.join(timeout=2)
assert not t.is_alive()
assert "show" not in lcd.calls # nie verbunden → kein Endbildschirm
def test_programmliste_nur_im_eigenen_intervall():
calls = []
def top_apps(n):
calls.append(n)
return APPS
times = iter([0, 4, 8, 12, 16, 20])
run_fake(FakeLcd(), iterations=6, top_apps=top_apps, monotonic=lambda: next(times))
assert calls == [5, 5] # bei t=0 und t=12
def test_drehung_um_180_grad():
cfg = Config(memory_interval=0, rotate_180=True)
lcd = FakeLcd()
run_fake(lcd, iterations=1, cfg=cfg)
expected = render(MEM, APPS, NOW, cfg).rotate(180)
assert ImageChops.difference(lcd.shown[0][2], expected).getbbox() is None
def test_unerwarteter_fehler_zeigt_endbildschirm_statt_altem_stand():
calls = 0
def top_apps(n):
nonlocal calls
calls += 1
if calls == 2:
raise RuntimeError("unerwartet")
return APPS
times = iter([0, 20])
lcd = FakeLcd()
with pytest.raises(RuntimeError):
run_fake(lcd, iterations=10, top_apps=top_apps, monotonic=lambda: next(times))
# erstes Bild live, danach Endbildschirm als Vollbild, dann geschlossen
assert sizes(lcd) == [(0, 0, (320, 480)), (0, 0, (320, 480))]
assert ImageChops.difference(lcd.shown[-1][2], render_stopped(NOW)).getbbox() is None
assert lcd.calls[-1] == "close"
def test_endbildschirm_fehler_wird_abgefangen():
lcd = FakeLcd(show_failures={1}) # 0 = erstes Bild, 1 = Endbildschirm
run_fake(lcd, iterations=1)
assert lcd.calls[-1] == "close"
@pytest.fixture
def display_calls(monkeypatch):
"""Ersetzt Display und Hauptschleife; ein Eintrag bedeutet, dass main() sie benutzt hätte."""
calls = []
monkeypatch.setattr(main_module, "Lcd", lambda port: calls.append(("Lcd", port)))
monkeypatch.setattr(main_module, "run", lambda *args, **kwargs: calls.append("run"))
return calls
@pytest.mark.parametrize(
("text", "fragment"),
[
('top_n = 2.5\nrotate_180 = "false"\n', "top_n"), # ungültige Werte
("brightness = = 20\n", "line 1"), # TOML-Syntaxfehler
("[port\n", "line 1"),
],
)
def test_ungueltige_konfiguration_beendet_mit_2_ohne_traceback(
tmp_path, caplog, capsys, display_calls, text, fragment
):
path = tmp_path / "config.toml"
path.write_text(text, encoding="utf-8")
with caplog.at_level(logging.INFO):
assert main(["--config", str(path)]) == 2
errors = [r for r in caplog.records if r.levelno == logging.ERROR]
assert len(errors) == 1
assert str(path) in errors[0].getMessage()
assert fragment in errors[0].getMessage()
assert errors[0].exc_info is None
assert "Traceback" not in caplog.text + capsys.readouterr().err
assert display_calls == []
def test_unlesbare_konfiguration_beendet_mit_2_ohne_traceback(tmp_path, caplog, capsys, display_calls):
path = tmp_path / "verzeichnis.toml"
path.mkdir() # existiert, lässt sich aber nicht als Datei lesen
assert main(["--config", str(path)]) == 2
errors = [r for r in caplog.records if r.levelno == logging.ERROR]
assert len(errors) == 1
assert str(path) in errors[0].getMessage()
assert errors[0].exc_info is None
assert "Traceback" not in caplog.text + capsys.readouterr().err
assert display_calls == []
STOP_SIGNALS = (signal.SIGTERM, signal.SIGINT)
@pytest.fixture
def restore_signal_handlers():
saved = {sig: signal.getsignal(sig) for sig in STOP_SIGNALS}
yield
for sig, handler in saved.items():
signal.signal(sig, handler)
@pytest.mark.parametrize("sig", STOP_SIGNALS)
def test_signal_handler_blockiert_nicht_am_lock_des_events(restore_signal_handlers, sig):
original = signal.getsignal(sig)
stop = threading.Event()
main_module._install_signal_handlers(stop)
handler = signal.getsignal(sig)
assert callable(handler) and handler is not original
# Der echte Handler läuft im Hauptthread zwischen zwei Bytecodes, womöglich während stop.wait()
# das nicht reentrante Lock des Events hält. Nachstellen lässt sich das nur über das private _cond.
# Eigener Daemon-Thread: Blockiert der Handler wieder, scheitert nur dieser Test statt die Suite aufzuhängen.
def handler_unter_lock():
with stop._cond:
handler(sig, None)
t = threading.Thread(target=handler_unter_lock, daemon=True)
t.start()
t.join(timeout=2)
assert not t.is_alive(), "Signal-Handler blockiert am Lock des Events"
assert stop.wait(timeout=2)
@pytest.mark.parametrize("sig", STOP_SIGNALS)
def test_signal_stoppt_hauptschleife_von_main(tmp_path, monkeypatch, restore_signal_handlers, sig):
stops = []
monkeypatch.setattr(main_module, "Lcd", lambda port: None)
monkeypatch.setattr(main_module, "run", lambda cfg, lcd, stop: stops.append(stop))
assert main(["--config", str(tmp_path / "fehlt.toml")]) == 0 # fehlende Datei → Standardwerte
signal.getsignal(sig)(sig, None)
assert stops[0].wait(timeout=2)