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

552 lines
21 KiB

import errno
import functools
import logging
import os
import signal
import subprocess
import sys
import threading
import time
from datetime import datetime
import pytest
import serial
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)
TIMEOUT_HINT = ("Übertragung ans Display nach Zeitüberschreitung abgebrochen, die Anzeige kann gestört sein – "
"Abhilfe: Display kurz ab- und wieder anstecken")
def write_error():
return OSError("Schreibfehler")
def write_timeout():
return serial.SerialTimeoutException("Write timeout") # so meldet pyserial ein Überschreiten von write_timeout
class FakeLcd:
def __init__(self, open_failures=0, show_failures=(), show_error=write_error):
self.calls = []
self.shown = [] # (x, y, Bild)
self.open_failures = open_failures
self.show_failures = set(show_failures)
self.show_error = show_error
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 self.show_error()
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"
def test_auffrischung_genau_nach_ablauf_des_intervalls():
# fällig 600 s nach dem Verbindungsaufbau, danach 600 s nach der letzten (hier verspäteten) Auffrischung
times = iter([0, 599, 600, 1250, 1849, 1850])
lcd = FakeLcd()
run_fake(lcd, iterations=6, monotonic=lambda: next(times))
assert lcd.calls == [
"open", "orientation", ("brightness", 20), "show", # t=0
"orientation", ("brightness", 20), "show", # t=600
"orientation", ("brightness", 20), "show", # t=1250
"orientation", ("brightness", 20), "show", # t=1850
"show", "close", # Endbildschirm
]
assert sizes(lcd) == [(0, 0, (320, 480))] * 5 # unverändertes Bild trotzdem als Vollbild
def test_nach_neuverbindung_beginnt_auffrischungsintervall_neu():
# Bild 0 scheitert bei t=0, Wiederverbinden bei t=30 → nächste Auffrischung erst bei t=90, nicht bei t=60
times = iter([0, 0, 30, 30, 89, 90]) # Durchlauf, Fehler, Ausfalldauer, dann je Durchlauf
lcd = FakeLcd(show_failures={0})
run_fake(lcd, iterations=4, monotonic=lambda: next(times), full_refresh_interval=60)
assert lcd.calls == [
"open", "orientation", ("brightness", 20), "close",
"open", "orientation", ("brightness", 20), "show", # t=30
"orientation", ("brightness", 20), "show", # t=90
"show", "close",
]
class CommandFailingLcd(FakeLcd):
"""Der n-te Aufruf (ab 0) von Ausrichtung oder Helligkeit scheitert mit einem Schreibfehler."""
def __init__(self, command, index):
super().__init__()
self.failing = (command, index)
self.counts = {"orientation": 0, "brightness": 0}
def _send(self, command):
index = self.counts[command]
self.counts[command] += 1
if (command, index) == self.failing:
raise OSError("Schreibfehler")
def set_orientation_portrait(self):
self._send("orientation")
super().set_orientation_portrait()
def set_brightness(self, percent):
self._send("brightness")
super().set_brightness(percent)
@pytest.mark.parametrize(
("make_lcd", "sent"),
[
(lambda: CommandFailingLcd("orientation", 1), []), # Aufruf 0 gehört zum Verbindungsaufbau
(lambda: CommandFailingLcd("brightness", 1), ["orientation"]),
(lambda: FakeLcd(show_failures={1}), ["orientation", ("brightness", 20)]), # Vollbild scheitert
],
ids=["ausrichtung", "helligkeit", "vollbild"],
)
def test_fehler_bei_auffrischung_fuehrt_zu_neuverbindung(make_lcd, sent):
times = iter([0, 600, 600, 610, 610]) # Durchlauf, Auffrischung, Fehler, Ausfalldauer, Durchlauf
lcd = make_lcd()
run_fake(lcd, iterations=3, monotonic=lambda: next(times))
assert lcd.calls == [
"open", "orientation", ("brightness", 20), "show",
*sent, "close",
"open", "orientation", ("brightness", 20), "show", # Neuverbindung mit Vollbild
"show", "close",
]
class Clock:
"""Gesteuertes monotonic: liefert die zuletzt gesetzte Zeit."""
def __init__(self):
self.t = 0.0
def __call__(self):
return self.t
class ScriptedLcd(FakeLcd):
"""open() stellt die Uhr auf den nächsten Zeitpunkt des Drehbuchs und scheitert mit dessen Meldung (None = Erfolg)."""
def __init__(self, clock, script, **kwargs):
super().__init__(**kwargs)
self.clock = clock
self.script = list(script)
def open(self):
self.calls.append("open")
self.clock.t, error = self.script.pop(0)
if error is not None:
raise OSError(error)
@pytest.mark.parametrize(
("seconds", "text"),
[(0, "0 s"), (42.4, "42 s"), (599.6, "10 min"), (610, "10 min 10 s"), (7200, "2 h"), (7535, "2 h 5 min")],
)
def test_dauer_lesbar(seconds, text):
assert main_module._duration(seconds) == text
def log_lines(caplog):
return [(r.levelname, r.getMessage()) for r in caplog.records if r.name == "ramscreen"]
def test_ausfall_meldet_geaenderten_fehler_und_erinnert_alle_10_minuten(caplog):
clock = Clock()
lcd = ScriptedLcd(clock, [
(0, "kein Gerät"),
(5, "kein Gerät"), # gleicher Fehler → still
(10, "Zugriff verweigert"), # geänderter Fehler → sofort
(609, "Zugriff verweigert"), # noch keine 10 min seit der letzten Meldung
(610, "Zugriff verweigert"), # Erinnerung
(1209, "Zugriff verweigert"),
(1210, "Zugriff verweigert"), # nächste Erinnerung
(1300, None),
])
with caplog.at_level(logging.INFO, logger="ramscreen"):
run_fake(lcd, iterations=1, monotonic=clock)
assert log_lines(caplog) == [
("WARNING", "Display nicht erreichbar (kein Gerät), neuer Versuch in 0 s"),
("WARNING", "Display nicht erreichbar (Zugriff verweigert), neuer Versuch in 0 s"),
("WARNING", "Display weiterhin nicht erreichbar seit 10 min 10 s (letzter Fehler: Zugriff verweigert)"),
("WARNING", "Display weiterhin nicht erreichbar seit 20 min 10 s (letzter Fehler: Zugriff verweigert)"),
("INFO", "Display verbunden (/dev/turing-screen) nach 21 min 40 s Ausfall"),
("INFO", "Beendet"),
]
assert lcd.script == []
def test_wiederverbinden_meldet_ausfalldauer_und_neuer_ausfall_wird_wieder_gemeldet(caplog):
clock = Clock()
# Auffrischung in jedem Durchlauf, damit jeder ein Bild sendet: Bild 0 scheitert, Bild 1 nach dem
# Wiederverbinden gelingt, Bild 2 im nächsten Durchlauf (t=5, noch verbunden) scheitert wieder
lcd = ScriptedLcd(clock, [(0, None), (5, None), (8, None)], show_failures={0, 2})
with caplog.at_level(logging.INFO, logger="ramscreen"):
run_fake(lcd, iterations=4, monotonic=clock, full_refresh_interval=0)
assert log_lines(caplog) == [
("WARNING", "Display nicht erreichbar (Schreibfehler), neuer Versuch in 0 s"), # nie ein Bild durch
("INFO", "Display verbunden (/dev/turing-screen) nach 5 s Ausfall"),
("WARNING", "Display nicht erreichbar (Schreibfehler), neuer Versuch in 0 s"),
("INFO", "Display verbunden (/dev/turing-screen) nach 3 s Ausfall"),
("INFO", "Beendet"),
]
assert lcd.script == []
def test_ausfall_endet_erst_mit_dem_ersten_vollstaendigen_bild(caplog):
# Hängende Firmware, Gerät bleibt am USB: Öffnen, Ausrichtung und Helligkeit gelingen (der Kernel puffert
# die kurzen Befehle), erst das Bild läuft in die Zeitüberschreitung. Das ist ein einziger Ausfall.
clock = Clock()
lcd = ScriptedLcd(clock, [(t, None) for t in (0, 50, 599, 600, 1199, 1200)],
show_failures=range(6), show_error=write_timeout)
with caplog.at_level(logging.INFO, logger="ramscreen"):
run_fake(lcd, iterations=6, monotonic=clock)
assert log_lines(caplog) == [
("WARNING", "Display nicht erreichbar (Write timeout), neuer Versuch in 0 s"),
("WARNING", TIMEOUT_HINT),
("WARNING", "Display weiterhin nicht erreichbar seit 10 min (letzter Fehler: Write timeout)"),
("WARNING", TIMEOUT_HINT),
("WARNING", "Display weiterhin nicht erreichbar seit 20 min (letzter Fehler: Write timeout)"),
("WARNING", TIMEOUT_HINT),
("INFO", "Beendet"),
]
assert lcd.script == []
assert "show" not in lcd.calls # kein Bild durchgegangen, daher auch kein Endbildschirm
class OrientationTimeoutLcd(ScriptedLcd):
"""Zusätzlich scheitern die Ausrichtungs-Aufrufe mit den angegebenen Nummern (ab 0) an einer Zeitüberschreitung."""
def __init__(self, clock, script, orientation_timeouts, **kwargs):
super().__init__(clock, script, **kwargs)
self.orientation_timeouts = set(orientation_timeouts)
self._orientation_count = 0
def set_orientation_portrait(self):
index = self._orientation_count
self._orientation_count += 1
if index in self.orientation_timeouts:
raise write_timeout()
super().set_orientation_portrait()
def test_zeitueberschreitung_meldet_gestoerte_anzeige_mit_der_ausfallmeldung(caplog):
clock = Clock()
lcd = OrientationTimeoutLcd(
clock,
[(0, None), (5, None), (10, "kein Gerät"), (20, None)],
orientation_timeouts={1}, # Aufruf 0 gehört zum ersten Verbindungsaufbau
show_failures={0},
show_error=write_timeout,
)
with caplog.at_level(logging.INFO, logger="ramscreen"):
run_fake(lcd, iterations=2, monotonic=clock)
assert log_lines(caplog) == [
("WARNING", "Display nicht erreichbar (Write timeout), neuer Versuch in 0 s"),
("WARNING", TIMEOUT_HINT),
# t=5: gleicher Fehler im selben Ausfall bleibt still, auch der Hinweis (er kommt mit der Erinnerung)
("WARNING", "Display nicht erreichbar (kein Gerät), neuer Versuch in 0 s"), # z. B. abgesteckt
("INFO", "Display verbunden (/dev/turing-screen) nach 20 s Ausfall"),
("INFO", "Beendet"),
]
assert lcd.script == []
@pytest.mark.parametrize(
"error",
[
OSError(errno.EIO, "Eingabe-/Ausgabefehler"),
serial.SerialException("write failed: [Errno 5] Eingabe-/Ausgabefehler"), # pyserial beim Abstecken
],
ids=["oserror", "serialexception"],
)
def test_andere_schreibfehler_ohne_hinweis_auf_gestoerte_anzeige(caplog, error):
lcd = FakeLcd(show_failures={0}, show_error=lambda: error)
with caplog.at_level(logging.INFO, logger="ramscreen"):
run_fake(lcd, iterations=1)
warnings = [message for level, message in log_lines(caplog) if level == "WARNING"]
assert warnings == [f"Display nicht erreichbar ({error}), neuer Versuch in 0 s"]
def test_zeitueberschreitung_beim_endbildschirm_meldet_gestoerte_anzeige(caplog):
lcd = FakeLcd(show_failures={1}, show_error=write_timeout) # 0 = erstes Bild, 1 = Endbildschirm
with caplog.at_level(logging.INFO, logger="ramscreen"):
run_fake(lcd, iterations=1)
assert log_lines(caplog) == [
("INFO", "Display verbunden (/dev/turing-screen)"),
("WARNING", "Endbildschirm konnte nicht gesendet werden: Write timeout"),
("WARNING", TIMEOUT_HINT),
("INFO", "Beendet"),
]
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)
def test_unerwarteter_fehler_beendet_main_mit_1_und_loggt_traceback(
tmp_path, monkeypatch, caplog, restore_signal_handlers
):
def read_memory():
raise RuntimeError("kaputt")
path = tmp_path / "config.toml"
path.write_text('port = "/dev/nicht-vorhanden"\n', encoding="utf-8")
lcd = FakeLcd()
monkeypatch.setattr(main_module, "Lcd", lambda port: lcd)
monkeypatch.setattr(main_module, "run", functools.partial(
run, read_memory=read_memory, top_apps=lambda n: APPS, now=lambda: NOW))
assert main(["--config", str(path)]) == 1
errors = [r for r in caplog.records if r.levelno >= logging.ERROR]
assert len(errors) == 1
assert errors[0].exc_info[0] is RuntimeError
assert "Traceback" in caplog.text
assert "RuntimeError: kaputt" in caplog.text
# das finally in run() greift weiterhin: Endbildschirm statt eingefrorenem Stand
assert ImageChops.difference(lcd.shown[-1][2], render_stopped(NOW)).getbbox() is None
assert lcd.calls[-1] == "close"
@pytest.mark.parametrize(("journal", "prefix"), [("passend", "<3>"), ("unpassend", "")])
def test_main_logt_mit_prioritaet_nur_wenn_stderr_am_journal_haengt(tmp_path, journal, prefix):
# Eigener Prozess, damit sys.stderr und os.environ wirklich die des Programms sind.
# Ungültige Konfiguration: main() endet, bevor ein Display geöffnet würde.
path = tmp_path / "config.toml"
path.write_text('port = "/dev/nicht-vorhanden"\ntop_n = 0\n', encoding="utf-8")
env = {key: value for key, value in os.environ.items() if key != "JOURNAL_STREAM"}
with open(tmp_path / "stderr", "w+b") as err:
st = os.fstat(err.fileno())
ino = st.st_ino if journal == "passend" else st.st_ino + 1
env["JOURNAL_STREAM"] = f"{st.st_dev}:{ino}"
result = subprocess.run(
[sys.executable, "-m", "ramscreen", "--config", str(path)],
stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=err, env=env, cwd=tmp_path, timeout=30,
)
err.seek(0)
lines = err.read().decode().splitlines()
assert result.returncode == 2
assert len(lines) == 1
assert lines[0].startswith(f"{prefix}ERROR Konfiguration {path} ist ungültig: top_n")