Files
ai-challenge-tool/tests/conftest.py
T
ScriptSorcerer d3a7f8b07e
Tests / tests (push) Failing after 19s
Tests: Qt am Ende geordnet herunterfahren
Unter Linux stürzte PySide6 nach bestandenen Tests beim Beenden ab
(Fatal Python error: none_dealloc), weil Python beim Aufräumen noch
lebende Qt-Fenster in falscher Reihenfolge löschte. Fenster werden jetzt
nach jedem Test gelöscht, und am Ende der Session wird Qt mit
QApplication.shutdown() beendet.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 22:45:20 +01:00

116 lines
3.9 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""Gemeinsame Hilfen für alle Tests.
- Qt läuft ohne Bildschirm ("offscreen"), damit die Tests auch auf einem
Runner ohne Monitor funktionieren.
- `make_recording` erzeugt eine kleine künstliche Aufnahme (jpg + json) in
einem temporären Ordner. So brauchen die Tests die echten Daten nicht,
die nicht im Git liegen.
"""
from __future__ import annotations
import json
import os
import sys
from pathlib import Path
os.environ.setdefault("QT_QPA_PLATFORM", "offscreen") # muss vor dem ersten Qt-Import stehen
PROJECT = Path(__file__).resolve().parent.parent
sys.path.insert(0, str(PROJECT / "app"))
import numpy as np # noqa: E402
import pytest # noqa: E402
from PySide6.QtGui import QImage # noqa: E402
from PySide6.QtTest import QTest # noqa: E402
from PySide6.QtWidgets import QApplication # noqa: E402
DATA_DIR = PROJECT / "daten"
# Eine QApplication für alle Tests (Qt erlaubt nur eine pro Programm).
APP = QApplication.instance() or QApplication([])
def delete_widget(widget) -> None:
"""Fenster schliessen und sofort löschen (nicht erst beim Beenden von Python)."""
from PySide6.QtCore import QEvent
widget.close()
widget.deleteLater()
QApplication.sendPostedEvents(None, QEvent.DeferredDelete)
def pytest_sessionfinish(session, exitstatus):
# Qt geordnet herunterfahren, solange Python noch voll läuft. Sonst räumt
# Python beim Beenden Qt-Objekte in falscher Reihenfolge weg, und PySide6
# stürzt unter Linux ab ("Fatal Python error: none_dealloc"), obwohl alle
# Tests bestanden haben.
import gc
from shiboken6 import isValid
for widget in QApplication.topLevelWidgets():
if isValid(widget): # z.B. Kontextmenüs sind mit ihrem Fenster schon gelöscht worden
delete_widget(widget)
gc.collect()
APP.shutdown()
def _save_gray_jpg(pixels: np.ndarray, path: Path) -> None:
pixels = np.ascontiguousarray(pixels, dtype=np.uint8)
h, w = pixels.shape
QImage(pixels.data, w, h, w, QImage.Format_Grayscale8).copy().save(str(path), "JPG", 95)
def _blur(pixels: np.ndarray, rounds: int = 4) -> np.ndarray:
"""Weichzeichnen: jedes Pixel wird mehrmals mit seinen 4 Nachbarn gemittelt."""
p = pixels.astype(np.float32)
for _ in range(rounds):
p = (p + np.roll(p, 1, 0) + np.roll(p, -1, 0) + np.roll(p, 1, 1) + np.roll(p, -1, 1)) / 5
return p
@pytest.fixture
def make_recording(tmp_path):
"""Erzeugt eine Aufnahme. Beispiel:
folder = make_recording([0, 5, -5], speeds=[0, 30, 30], blurry={1})
Bilder: 320 × 240, Rauschen (= viele feine Kanten, also scharf);
Frames in `blurry` werden weichgezeichnet.
"""
def make(angles, speeds=None, recording="9", blurry=(), name="aufnahme") -> Path:
folder = tmp_path / name
folder.mkdir(parents=True, exist_ok=True)
rng = np.random.default_rng(0)
for i, angle in enumerate(angles):
pixels = rng.integers(0, 256, (240, 320)).astype(np.float32)
if i in blurry:
pixels = _blur(pixels)
stem = f"{recording}_{i:08d}"
_save_gray_jpg(pixels, folder / f"{stem}.jpg")
speed = speeds[i] if speeds is not None else 30
(folder / f"{stem}.json").write_text(json.dumps({"angle": angle, "speed": speed}))
return folder
return make
def wait_until(condition, timeout_ms: int = 3000) -> bool:
"""Wartet (und lässt Qt arbeiten), bis condition() wahr ist."""
for _ in range(timeout_ms // 20):
if condition():
return True
QTest.qWait(20)
return condition()
def press(window, key, modifier=None) -> None:
"""Taste so senden, wie eine echte Tastatur: an das Widget mit dem Fokus."""
from PySide6.QtCore import Qt
target = QApplication.focusWidget() or window
QTest.keyClick(target, key, modifier if modifier is not None else Qt.NoModifier)
QTest.qWait(10)