config.toml: Typen und Intervalle prüfen, Fehler ohne Neustartschleife

load_config prüfte bisher nur die Bereiche von brightness und top_n.
Falsche Typen gingen durch: top_n = 2.5 brachte den Dienst zum Absturz,
rotate_180 = "false" drehte die Anzeige (nicht leerer Text ist wahr),
memory_interval = 0 erzeugte eine Busy-Loop. Jetzt werden alle Schlüssel
auf Typ und Wertebereich geprüft (bool zählt nie als Zahl, nan/inf
abgelehnt, Intervalle mindestens 0,5 s, crit_free_percent <= warn).
Alle Fehler einer Datei kommen gesammelt in einem ValueError, damit man
sie in einem Durchgang korrigieren kann. Geprüft wird in load_config,
nicht im Dataclass-Konstruktor, weil Tests bewusst Config(memory_interval=0)
bauen.

main() meldet ungültige oder unlesbare Konfiguration (auch TOML-
Syntaxfehler) als eine Logzeile mit Dateipfad ohne Traceback, öffnet das
Display nicht und endet mit Status 2. Die Unit verhindert mit
RestartPreventExitStatus=2, dass systemd dann alle 5 s neu startet.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
main
AmiPoke 3 weeks ago
parent 71ccc25aaa
commit fb3026f795
  1. 8
      src/ramscreen/__main__.py
  2. 45
      src/ramscreen/config.py
  3. 2
      systemd/ramscreen.service
  4. 73
      tests/test_config.py
  5. 49
      tests/test_main.py

@ -88,7 +88,15 @@ def main(argv: list[str] | None = None) -> int:
args = parser.parse_args(argv) args = parser.parse_args(argv)
logging.basicConfig(level=logging.INFO, format="%(levelname)s %(message)s") logging.basicConfig(level=logging.INFO, format="%(levelname)s %(message)s")
# Rückgabe 2: systemd startet bei Konfigurationsfehlern nicht neu (RestartPreventExitStatus)
try:
cfg = load_config(args.config) cfg = load_config(args.config)
except OSError as exc:
log.error("Konfiguration %s kann nicht gelesen werden: %s", args.config, exc)
return 2
except ValueError as exc: # auch tomllib.TOMLDecodeError und UnicodeDecodeError
log.error("Konfiguration %s ist ungültig: %s", args.config, exc)
return 2
stop = threading.Event() stop = threading.Event()
for sig in (signal.SIGTERM, signal.SIGINT): for sig in (signal.SIGTERM, signal.SIGINT):

@ -1,6 +1,7 @@
"""Konfiguration aus config.toml laden.""" """Konfiguration aus config.toml laden."""
import logging import logging
import math
import tomllib import tomllib
from dataclasses import dataclass, fields from dataclasses import dataclass, fields
from pathlib import Path from pathlib import Path
@ -8,6 +9,7 @@ from pathlib import Path
log = logging.getLogger(__name__) log = logging.getLogger(__name__)
MAX_TOP_N = 5 # mehr Zeilen passen nicht auf das Display MAX_TOP_N = 5 # mehr Zeilen passen nicht auf das Display
MIN_INTERVAL = 0.5 # Sekunden; 0 wäre eine Dauerschleife auf CPU und Display
@dataclass(frozen=True) @dataclass(frozen=True)
@ -22,6 +24,42 @@ class Config:
apps_interval: float = 10 apps_interval: float = 10
def _is_int(value) -> bool:
# bool ist in Python eine Unterklasse von int, zählt hier aber nie als Zahl
return isinstance(value, int) and not isinstance(value, bool)
def _is_number(value) -> bool:
return _is_int(value) or (isinstance(value, float) and math.isfinite(value))
def _percent(value) -> bool:
return _is_number(value) and 0 <= value <= 100
def _errors(cfg: Config) -> list[str]:
errors = []
def check(key: str, ok: bool, expected: str) -> bool:
if not ok:
errors.append(f"{key}: erwartet {expected}, ist {getattr(cfg, key)!r}")
return ok
check("port", isinstance(cfg.port, str) and cfg.port.strip() != "", "nicht leeren Gerätepfad")
check("brightness", _is_int(cfg.brightness) and 0 <= cfg.brightness <= 100, "ganze Zahl von 0 bis 100")
check("rotate_180", isinstance(cfg.rotate_180, bool), "true oder false")
warn_ok = check("warn_free_percent", _percent(cfg.warn_free_percent), "Zahl von 0 bis 100")
crit_ok = check("crit_free_percent", _percent(cfg.crit_free_percent), "Zahl von 0 bis 100")
if warn_ok and crit_ok:
check("crit_free_percent", cfg.crit_free_percent <= cfg.warn_free_percent,
f"höchstens warn_free_percent ({cfg.warn_free_percent!r})")
check("top_n", _is_int(cfg.top_n) and 1 <= cfg.top_n <= MAX_TOP_N, f"ganze Zahl von 1 bis {MAX_TOP_N}")
for key in ("memory_interval", "apps_interval"):
value = getattr(cfg, key)
check(key, _is_number(value) and value >= MIN_INTERVAL, f"Sekunden als Zahl ab {MIN_INTERVAL}")
return errors
def load_config(path: Path) -> Config: def load_config(path: Path) -> Config:
if not path.exists(): if not path.exists():
return Config() return Config()
@ -30,8 +68,7 @@ def load_config(path: Path) -> Config:
for key in sorted(data.keys() - known): for key in sorted(data.keys() - known):
log.warning("Unbekannter Schlüssel in %s ignoriert: %s", path, key) log.warning("Unbekannter Schlüssel in %s ignoriert: %s", path, key)
cfg = Config(**{key: value for key, value in data.items() if key in known}) cfg = Config(**{key: value for key, value in data.items() if key in known})
if not 0 <= cfg.brightness <= 100: # alle Fehler auf einmal melden, damit man nicht für jeden einzeln neu starten muss
raise ValueError(f"brightness muss zwischen 0 und 100 liegen, ist {cfg.brightness}") if errors := _errors(cfg):
if not 1 <= cfg.top_n <= MAX_TOP_N: raise ValueError("; ".join(errors))
raise ValueError(f"top_n muss zwischen 1 und {MAX_TOP_N} liegen, ist {cfg.top_n}")
return cfg return cfg

@ -7,6 +7,8 @@ WorkingDirectory=%h/code/TuringSmartScreen
ExecStart=%h/code/TuringSmartScreen/.venv/bin/python -m ramscreen ExecStart=%h/code/TuringSmartScreen/.venv/bin/python -m ramscreen
Restart=always Restart=always
RestartSec=5 RestartSec=5
# Exit-Status 2 = Konfigurationsfehler: nicht alle 5 s neu starten, sondern config.toml korrigieren
RestartPreventExitStatus=2
[Install] [Install]
WantedBy=default.target WantedBy=default.target

@ -44,3 +44,76 @@ def test_ungueltige_werte_werden_abgelehnt(tmp_path: Path, text: str):
path.write_text(text, encoding="utf-8") path.write_text(text, encoding="utf-8")
with pytest.raises(ValueError): with pytest.raises(ValueError):
load_config(path) load_config(path)
@pytest.mark.parametrize(
("text", "key", "shown"),
[
("top_n = 2.5\n", "top_n", "2.5"),
("top_n = true\n", "top_n", "True"),
('rotate_180 = "false"\n', "rotate_180", "'false'"),
("rotate_180 = 1\n", "rotate_180", "1"),
("memory_interval = 0\n", "memory_interval", "0"),
("memory_interval = -1\n", "memory_interval", "-1"),
("memory_interval = 0.4\n", "memory_interval", "0.4"),
("memory_interval = nan\n", "memory_interval", "nan"),
("memory_interval = inf\n", "memory_interval", "inf"),
("memory_interval = true\n", "memory_interval", "True"),
("apps_interval = 0\n", "apps_interval", "0"),
("apps_interval = -inf\n", "apps_interval", "-inf"),
("brightness = 20.5\n", "brightness", "20.5"),
("brightness = true\n", "brightness", "True"),
('brightness = "20"\n', "brightness", "'20'"),
("port = 5\n", "port", "5"),
('port = ""\n', "port", "''"),
("warn_free_percent = 101\n", "warn_free_percent", "101"),
('warn_free_percent = "20"\n', "warn_free_percent", "'20'"),
("warn_free_percent = nan\n", "warn_free_percent", "nan"),
("crit_free_percent = -1\n", "crit_free_percent", "-1"),
("crit_free_percent = false\n", "crit_free_percent", "False"),
("crit_free_percent = 30\n", "crit_free_percent", "30"), # größer als warn (Standard 20)
("warn_free_percent = 5\ncrit_free_percent = 10\n", "crit_free_percent", "10"),
],
)
def test_falsche_typen_und_intervalle_werden_mit_schluessel_und_wert_gemeldet(
tmp_path: Path, text: str, key: str, shown: str
):
path = tmp_path / "config.toml"
path.write_text(text, encoding="utf-8")
with pytest.raises(ValueError) as info:
load_config(path)
message = str(info.value)
assert f"{key}: " in message
assert f"ist {shown}" in message
@pytest.mark.parametrize(
("text", "expected"),
[
("memory_interval = 0.5\napps_interval = 0.5\n", {"memory_interval": 0.5, "apps_interval": 0.5}),
("memory_interval = 1\napps_interval = 30\n", {"memory_interval": 1, "apps_interval": 30}),
("warn_free_percent = 15\ncrit_free_percent = 7.5\n", {"warn_free_percent": 15, "crit_free_percent": 7.5}),
("warn_free_percent = 10\ncrit_free_percent = 10\n", {"warn_free_percent": 10, "crit_free_percent": 10}),
("warn_free_percent = 0\ncrit_free_percent = 0\n", {"warn_free_percent": 0, "crit_free_percent": 0}),
("warn_free_percent = 100.0\n", {"warn_free_percent": 100.0}),
("brightness = 0\ntop_n = 1\n", {"brightness": 0, "top_n": 1}),
("brightness = 100\ntop_n = 5\n", {"brightness": 100, "top_n": 5}),
("rotate_180 = false\n", {"rotate_180": False}),
],
)
def test_gueltige_grenzfaelle_werden_angenommen(tmp_path: Path, text: str, expected: dict):
path = tmp_path / "config.toml"
path.write_text(text, encoding="utf-8")
cfg = load_config(path)
for key, value in expected.items():
assert getattr(cfg, key) == value
def test_mehrere_fehler_werden_gemeinsam_gemeldet(tmp_path: Path):
path = tmp_path / "config.toml"
path.write_text('top_n = 2.5\nrotate_180 = "false"\nmemory_interval = 0\nport = ""\n', encoding="utf-8")
with pytest.raises(ValueError) as info:
load_config(path)
message = str(info.value)
for fragment in ("top_n: ", "ist 2.5", "rotate_180: ", "ist 'false'", "memory_interval: ", "ist 0", "port: "):
assert fragment in message

@ -1,3 +1,4 @@
import logging
import threading import threading
import time import time
from datetime import datetime from datetime import datetime
@ -5,7 +6,8 @@ from datetime import datetime
import pytest import pytest
from PIL import ImageChops from PIL import ImageChops
from ramscreen.__main__ import run import ramscreen.__main__ as main_module
from ramscreen.__main__ import main, run
from ramscreen.config import Config from ramscreen.config import Config
from ramscreen.meminfo import App, Memory from ramscreen.meminfo import App, Memory
from ramscreen.render import render, render_stopped from ramscreen.render import render, render_stopped
@ -158,3 +160,48 @@ def test_endbildschirm_fehler_wird_abgefangen():
lcd = FakeLcd(show_failures={1}) # 0 = erstes Bild, 1 = Endbildschirm lcd = FakeLcd(show_failures={1}) # 0 = erstes Bild, 1 = Endbildschirm
run_fake(lcd, iterations=1) run_fake(lcd, iterations=1)
assert lcd.calls[-1] == "close" 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 == []

Loading…
Cancel
Save