Signal- und Port-Verhalten war bisher nur mit Fakes getestet. tests/test_cli.py startet den Monitor als echten Prozess (python -m ramscreen, ohne JOURNAL_STREAM): - fehlender Port: läuft weiter, meldet „Display nicht erreichbar“; SIGTERM/SIGINT beenden ihn mit 0 deutlich vor Ablauf der 5 s Wartezeit - ungültige config.toml: Exit 2, Meldung nennt den Schlüssel, kein Traceback - Pseudo-Terminal als Schnittstelle (pyserial öffnet es mit rtscts und exclusive wie das Display): der Bytestrom wird zerlegt und muss exakt aufgehen – Ausrichtung, Helligkeit, Vollbild, am Ende der Endbildschirm, auch wenn SIGTERM mitten in einer Übertragung kommt; die Schnittstelle ist währenddessen exklusiv gesperrt Das echte Display wird nie geöffnet: jede Test-Konfiguration setzt einen Port in tmp_path oder unter /dev/pts. Das Ende des Bytestroms ist deterministisch (EIO auf der Master-Seite, nachdem alle Daten gelesen sind), keine Wartezeit auf Ruhe in der Leitung. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>main
parent
a10e35cc8a
commit
3e7bdd341e
@ -0,0 +1,319 @@ |
||||
"""Der Monitor als echter Prozess: Signale, Konfigurationsfehler und eine echte serielle Schnittstelle. |
||||
|
||||
Als Schnittstelle dient ein Pseudo-Terminal; das echte Display wird nie geöffnet. Jede config.toml setzt |
||||
deshalb ausdrücklich einen Port – ohne ihn gälte der Standard /dev/turing-screen. pyserial öffnet das |
||||
Pseudo-Terminal mit denselben Optionen wie das Display: rtscts wird dort nur gespeichert, nicht ausgewertet, |
||||
exclusive (flock) und der Rohmodus wirken wie beim Display. |
||||
""" |
||||
|
||||
import fcntl |
||||
import os |
||||
import signal |
||||
import subprocess |
||||
import sys |
||||
import threading |
||||
import time |
||||
from datetime import datetime, timedelta |
||||
from pathlib import Path |
||||
|
||||
import pytest |
||||
from PIL import Image |
||||
|
||||
from ramscreen.__main__ import RECONNECT_DELAY |
||||
from ramscreen.lcd import HEIGHT, WIDTH, Cmd, Lcd, encode_brightness, encode_orientation_portrait, to_rgb565le |
||||
from ramscreen.render import render_stopped |
||||
|
||||
TIMEOUT = 15.0 # Sekunden: großzügige Obergrenze für Start, Übertragung und Ende |
||||
# Kürzer als die Wartezeit bis zum nächsten Verbindungsversuch: nur dann beweist ein rechtzeitiges Ende, |
||||
# dass das Signal das Warten abbricht |
||||
STOP_TIMEOUT = RECONNECT_DELAY / 2 |
||||
PAUSE = 0.3 # Sekunden, die der Monitor mitten in einem Bild festhängt, während das Signal eintrifft |
||||
HEADER = 6 |
||||
FULL_FRAME = HEADER + WIDTH * HEIGHT * 2 |
||||
CONNECT = len(encode_orientation_portrait()) + len(encode_brightness(20)) |
||||
STOP_SIGNALS = (signal.SIGTERM, signal.SIGINT) |
||||
|
||||
|
||||
def write_config(tmp_path: Path, port: str, rest: str = "") -> Path: |
||||
# Sicherung: nur eine Datei in tmp_path oder ein Pseudo-Terminal, nie das echte Display |
||||
assert port.startswith((f"{tmp_path}/", "/dev/pts/")), port |
||||
path = tmp_path / "config.toml" |
||||
path.write_text(f'port = "{port}"\n{rest}', encoding="utf-8") |
||||
return path |
||||
|
||||
|
||||
class MonitorProcess: |
||||
"""python -m ramscreen als eigener Prozess; stdout und stderr landen gemeinsam in output.""" |
||||
|
||||
def __init__(self, config: Path): |
||||
env = {key: value for key, value in os.environ.items() if key != "JOURNAL_STREAM"} |
||||
env["PYTHONUNBUFFERED"] = "1" |
||||
self.proc = subprocess.Popen( |
||||
[sys.executable, "-m", "ramscreen", "--config", str(config)], |
||||
stdin=subprocess.DEVNULL, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, env=env, cwd=config.parent, |
||||
) |
||||
self._output = bytearray() |
||||
self._eof = False |
||||
self._cond = threading.Condition() |
||||
self._reader = threading.Thread(target=self._read, daemon=True) |
||||
self._reader.start() |
||||
|
||||
def __enter__(self): |
||||
return self |
||||
|
||||
def __exit__(self, *exc): |
||||
# auch wenn der Test scheitert: nichts weiterlaufen lassen |
||||
if self.proc.poll() is None: |
||||
self.proc.kill() |
||||
self.proc.wait(timeout=5) |
||||
self._reader.join(timeout=5) |
||||
self.proc.stdout.close() |
||||
|
||||
def _read(self): |
||||
while chunk := self.proc.stdout.read1(4096): |
||||
with self._cond: |
||||
self._output += chunk |
||||
self._cond.notify_all() |
||||
with self._cond: |
||||
self._eof = True |
||||
self._cond.notify_all() |
||||
|
||||
@property |
||||
def output(self) -> str: |
||||
with self._cond: |
||||
return self._output.decode("utf-8", "replace") |
||||
|
||||
def wait_for_output(self, text: str, timeout: float = TIMEOUT) -> None: |
||||
with self._cond: |
||||
self._cond.wait_for(lambda: text.encode() in self._output or self._eof, timeout) |
||||
if text not in self.output: |
||||
pytest.fail(f"{text!r} nicht binnen {timeout} s ausgegeben:\n{self.output}") |
||||
|
||||
def wait_for_exit(self, timeout: float) -> int: |
||||
try: |
||||
self.proc.wait(timeout=timeout) |
||||
except subprocess.TimeoutExpired: |
||||
pytest.fail(f"Prozess nicht binnen {timeout} s beendet:\n{self.output}") |
||||
self._reader.join(timeout=5) # Rest der Ausgabe |
||||
return self.proc.returncode |
||||
|
||||
|
||||
@pytest.mark.parametrize("sig", STOP_SIGNALS, ids=lambda sig: sig.name) |
||||
def test_fehlender_port_signal_beendet_sofort_trotz_wartezeit(tmp_path, sig): |
||||
port = f"{tmp_path}/kein-display" |
||||
with MonitorProcess(write_config(tmp_path, port)) as monitor: |
||||
monitor.wait_for_output("Display nicht erreichbar") |
||||
assert monitor.proc.poll() is None # läuft weiter und versucht es später erneut |
||||
monitor.proc.send_signal(sig) |
||||
assert monitor.wait_for_exit(STOP_TIMEOUT) == 0 |
||||
output = monitor.output |
||||
assert port in output |
||||
assert f"neuer Versuch in {RECONNECT_DELAY:.0f} s" in output |
||||
assert "Display verbunden" not in output |
||||
assert output.splitlines()[-1] == "INFO Beendet" |
||||
assert "Traceback" not in output |
||||
|
||||
|
||||
@pytest.mark.parametrize( |
||||
("rest", "fragments"), |
||||
[ |
||||
("top_n = 2.5\nmemory_interval = 0\n", ["top_n: ", "ist 2.5", "memory_interval: ", "ist 0"]), |
||||
("brightness = = 20\n", ["line 2"]), # TOML-Syntaxfehler, Zeile 1 ist der Port |
||||
], |
||||
ids=["ungueltige-werte", "syntaxfehler"], |
||||
) |
||||
def test_ungueltige_konfiguration_exit_2_ohne_traceback(tmp_path, rest, fragments): |
||||
config = write_config(tmp_path, f"{tmp_path}/kein-display", rest) |
||||
with MonitorProcess(config) as monitor: |
||||
assert monitor.wait_for_exit(TIMEOUT) == 2 |
||||
output = monitor.output |
||||
assert f"ERROR Konfiguration {config} ist ungültig: " in output |
||||
for fragment in fragments: |
||||
assert fragment in output |
||||
assert "Traceback" not in output |
||||
assert "Display" not in output # gar nicht erst versucht |
||||
|
||||
|
||||
def decode_header(header: bytes) -> tuple[int, int, int, int, int]: |
||||
"""Umkehrung von encode_header: (Befehl, x, y, ex, ey).""" |
||||
b0, b1, b2, b3, b4, cmd = header |
||||
return cmd, (b0 << 2) | (b1 >> 6), ((b1 & 63) << 4) | (b2 >> 4), ((b2 & 15) << 6) | (b3 >> 2), ((b3 & 3) << 8) | b4 |
||||
|
||||
|
||||
def parse_stream(data: bytes) -> list[tuple]: |
||||
"""Zerlegt den Bytestrom ans Display in Pakete; scheitert an unbekannten Befehlen und am Ende an einer |
||||
unvollständigen Übertragung.""" |
||||
packets = [] |
||||
pos = 0 |
||||
while pos < len(data): |
||||
assert len(data) - pos >= HEADER, f"unvollständiger Befehlskopf ab Byte {pos}" |
||||
cmd, x, y, ex, ey = decode_header(data[pos:pos + HEADER]) |
||||
if cmd == Cmd.SET_ORIENTATION: |
||||
size = len(encode_orientation_portrait()) |
||||
packet = ("ausrichtung", data[pos:pos + size]) |
||||
elif cmd == Cmd.SET_BRIGHTNESS: |
||||
size = HEADER |
||||
packet = ("helligkeit", data[pos:pos + size]) |
||||
elif cmd == Cmd.DISPLAY_BITMAP: |
||||
assert x <= ex < WIDTH and y <= ey < HEIGHT, f"Bildbereich außerhalb des Displays ab Byte {pos}" |
||||
w, h = ex - x + 1, ey - y + 1 |
||||
size = HEADER + w * h * 2 |
||||
packet = ("bild", (x, y, w, h), data[pos + HEADER:pos + size]) |
||||
else: |
||||
raise AssertionError(f"unbekannter Befehl {cmd} ab Byte {pos}") |
||||
missing = pos + size - len(data) |
||||
assert missing <= 0, f"unvollständige Übertragung ab Byte {pos}: {missing} Bytes fehlen" |
||||
packets.append(packet) |
||||
pos += size |
||||
return packets |
||||
|
||||
|
||||
class RecordingSerial: |
||||
def __init__(self): |
||||
self.data = bytearray() |
||||
|
||||
def write(self, data): |
||||
self.data += data |
||||
|
||||
def close(self): |
||||
pass |
||||
|
||||
|
||||
def test_zerleger_erkennt_pakete_und_unvollstaendige_uebertragung(): |
||||
serial = RecordingSerial() |
||||
lcd = Lcd("/dev/test", serial_factory=lambda *args, **kwargs: serial) |
||||
image = Image.new("RGB", (10, 5), (255, 0, 0)) |
||||
lcd.open() |
||||
lcd.set_orientation_portrait() |
||||
lcd.set_brightness(20) |
||||
lcd.show(image, WIDTH - 10, HEIGHT - 5) # rechts unten: alle Bits von x, y, ex, ey belegt |
||||
stream = bytes(serial.data) |
||||
assert parse_stream(stream) == [ |
||||
("ausrichtung", encode_orientation_portrait()), |
||||
("helligkeit", encode_brightness(20)), |
||||
("bild", (WIDTH - 10, HEIGHT - 5, 10, 5), to_rgb565le(image)), |
||||
] |
||||
for cut in (CONNECT + 3, len(stream) - 1): |
||||
with pytest.raises(AssertionError, match="unvollständige"): |
||||
parse_stream(stream[:cut]) |
||||
|
||||
|
||||
class Pty: |
||||
"""Pseudo-Terminal als serielle Schnittstelle. Ein Thread leert ständig die Master-Seite – sonst blockiert |
||||
der Monitor am vollen Puffer – und sammelt den Bytestrom. |
||||
|
||||
Die eigene Slave-Seite bleibt bis finish() offen, damit das Terminal nicht auflegt, wenn der Monitor sie |
||||
schließt. Mit pause_at hört der Thread nach so vielen Bytes auf zu lesen, bis resume() aufgerufen wird. |
||||
""" |
||||
|
||||
def __init__(self, pause_at: int | None = None): |
||||
self._master, self._slave = os.openpty() |
||||
self.port = os.ttyname(self._slave) |
||||
self._pause_at = pause_at |
||||
self._data = bytearray() |
||||
self._cond = threading.Condition() |
||||
self._thread = threading.Thread(target=self._read, daemon=True) |
||||
self._thread.start() |
||||
|
||||
def __enter__(self): |
||||
return self |
||||
|
||||
def __exit__(self, *exc): |
||||
self.finish() |
||||
os.close(self._master) |
||||
|
||||
def _room(self) -> int: |
||||
return 1 << 16 if self._pause_at is None else self._pause_at - len(self._data) |
||||
|
||||
def _read(self): |
||||
while True: |
||||
with self._cond: |
||||
self._cond.wait_for(lambda: self._room() > 0) |
||||
room = self._room() |
||||
try: |
||||
chunk = os.read(self._master, room) |
||||
except OSError: # EIO: keine Slave-Seite mehr offen und alles gelesen |
||||
return |
||||
with self._cond: |
||||
self._data += chunk |
||||
self._cond.notify_all() |
||||
|
||||
def wait_for_bytes(self, count: int, timeout: float = TIMEOUT) -> bool: |
||||
with self._cond: |
||||
return self._cond.wait_for(lambda: len(self._data) >= count, timeout) |
||||
|
||||
def resume(self) -> None: |
||||
with self._cond: |
||||
self._pause_at = None |
||||
self._cond.notify_all() |
||||
|
||||
def finish(self) -> bytes: |
||||
"""Schließt die eigene Slave-Seite und liefert den gesamten Bytestrom. |
||||
|
||||
Ist auch der Monitor beendet, liefert Linux erst alle gepufferten Daten und dann EIO: das Ende des |
||||
Bytestroms steht damit fest, ohne auf Ruhe in der Leitung zu warten. |
||||
""" |
||||
self.resume() |
||||
if self._slave is not None: |
||||
os.close(self._slave) |
||||
self._slave = None |
||||
self._thread.join(timeout=TIMEOUT) |
||||
assert not self._thread.is_alive(), "Bytestrom endet nicht" |
||||
with self._cond: |
||||
return bytes(self._data) |
||||
|
||||
|
||||
def assert_port_locked(port: str) -> None: |
||||
"""Der Monitor hält die Schnittstelle exklusiv (pyserial nutzt dafür flock).""" |
||||
fd = os.open(port, os.O_RDWR | os.O_NOCTTY | os.O_NONBLOCK) |
||||
try: |
||||
with pytest.raises(BlockingIOError): |
||||
fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB) |
||||
finally: |
||||
os.close(fd) |
||||
|
||||
|
||||
def stopped_screens(start: datetime, end: datetime) -> list[bytes]: |
||||
"""Mögliche Endbildschirme: einer je Minute von start bis end, denn er zeigt die Uhrzeit.""" |
||||
minute = start.replace(second=0, microsecond=0) |
||||
screens = [] |
||||
while minute <= end: |
||||
screens.append(to_rgb565le(render_stopped(minute))) |
||||
minute += timedelta(minutes=1) |
||||
return screens |
||||
|
||||
|
||||
@pytest.mark.parametrize("mid_transfer", [False, True], ids=["nach-erstem-bild", "mitten-im-ersten-bild"]) |
||||
def test_echte_schnittstelle_bytestrom_geht_beim_beenden_exakt_auf(tmp_path, mid_transfer): |
||||
# Mitten im ersten Bild nicht mehr lesen: der Monitor blockiert am vollen Puffer, das Signal trifft ihn |
||||
# also mitten in der Übertragung |
||||
pause_at = CONNECT + FULL_FRAME // 2 if mid_transfer else None |
||||
with Pty(pause_at) as pty: |
||||
config = write_config(tmp_path, pty.port, "memory_interval = 0.5\n") |
||||
with MonitorProcess(config) as monitor: |
||||
assert pty.wait_for_bytes(pause_at or CONNECT + FULL_FRAME), monitor.output |
||||
monitor.wait_for_output(f"Display verbunden ({pty.port})") |
||||
assert_port_locked(pty.port) |
||||
start = datetime.now() |
||||
monitor.proc.send_signal(signal.SIGTERM) |
||||
if mid_transfer: |
||||
time.sleep(PAUSE) |
||||
assert monitor.proc.poll() is None # bricht die Übertragung nicht ab, sondern wartet auf das Display |
||||
pty.resume() |
||||
assert monitor.wait_for_exit(TIMEOUT) == 0 |
||||
end = datetime.now() |
||||
data = pty.finish() |
||||
|
||||
packets = parse_stream(data) # scheitert, wenn eine Übertragung nur zur Hälfte gesendet wurde |
||||
assert packets[:2] == [("ausrichtung", encode_orientation_portrait()), ("helligkeit", encode_brightness(20))] |
||||
images = packets[2:] |
||||
assert [packet[0] for packet in images] == ["bild"] * len(images) # Auffrischung erst nach 10 min |
||||
assert images[0][1] == (0, 0, WIDTH, HEIGHT) # erstes Bild nach dem Verbinden: Vollbild |
||||
assert images[-1][1] == (0, 0, WIDTH, HEIGHT) |
||||
assert images[-1][2] in stopped_screens(start, end), "letztes Bild ist nicht der Endbildschirm" |
||||
assert images[0][2] != images[-1][2] |
||||
if mid_transfer: |
||||
assert len(images) == 2 # angefangenes Bild zu Ende, danach sofort der Endbildschirm |
||||
output = monitor.output |
||||
assert output.splitlines()[-1] == "INFO Beendet" |
||||
assert "Traceback" not in output |
||||
Loading…
Reference in new issue