Manual:Tests
Hydrofon's automated tests live in tests/ and cover the codebase from notes parsing and signal processing to the GUI suites and CLI protocols. No third-party test runner is required (pytest is not in requirements.txt): every test module is a standalone Python script built on plain assert statements that prints OK as its final line when all checks pass.
Test suites (tests/)¶
tests/ contains 13 runnable test modules plus one frozen reference module (_legacy_91121a7.py).
| Module | Requirements & speed | Coverage |
|---|---|---|
tests.test_app |
Pure Python, fast | Legacy Alarm, settings._merge type validation and corrupt settings.json.bad backup, session.parse / render notes round-trip, session.segments, Recorder -> unsaved/ -> finalize(), and refusing to delete a draft whose WAV is locked open. |
tests.test_events |
Pure Python, fast | EventEngine and EventRule (one event per long pass, window/second confirmation, gaps and NaN windows, time-backwards reset, source change, hysteresis and release, causal smoothing, notification independence), 300 randomised trials comparing LegacyAlarmEngine with verbatim FrozenAlarm (91121a7), and app.replay CSV CLI round-trip. |
tests.test_evaluation |
NumPy + scikit-learn, fast | Interval algebra (union, intersect, subtract), all four layers (multiclass, binary incl. audit confusion matrices, match_events, notifications), negative-time denominators, windows_to_truth, predictions.csv I/O, and exact equivalence of legacy_* metrics against tests._legacy_91121a7 (with mutation checks). |
tests.test_splits |
Synthetic records, fast (--real reads data/) |
Motor vectors, disjointness (recording_id, group, sha256, parent_recording_id), holdout-legacy, check_no_overlap overlap refusal, loeo (single_source, mixture, negative, rotating_3fold_seed9), group-kfold (one row per group), and the equal-duration tie fallback. With --real, also verifies the real Wolfset seed-0 split against wolfset-*-v1. |
tests.test_manifest |
Synthetic 44.1 kHz audio, fast | dataset segment provenance and identities, conflicting-overlap exclusion, shared channel policy read_mono and anti-phase cancellation guard, manifest.jsonl determinism across paths, validate_segments checks, broken WAVs / invalid Wolfset codes, and app.manifest CLI. |
tests.test_annotation |
Synthetic 4 kHz audio, fast | Cohen's kappa math (empty, perfect, degenerate single-label and hand-calculated cases), export blindness, strata, seed determinism and overlap share, plus import CSV validation (UTF-8 / cp1252, , / ;), disputed-clip handling and agreement report. |
tests.test_train |
Synthetic 44.1 kHz audio, bands only, fast | Wolfset and own-recording label rules, dataset.split, feature cache invalidation/recovery, full app.train JSON-lines protocol (data, train, evaluate, split), split.json hash binding, overlap refusal (including identical-SHA-256 copy), legacy model fallback and null undefined metrics. |
tests.test_models |
Loads YAMNet (~10 s); reads data/models/wolfset-*-v1 if present |
Band features (gain invariance, refusal below 35 919 Hz, 44.1 vs 48 kHz tolerance, silence/NaN/multichannel input), pinned v1 feature_spec SHA-256 hashes, model.json v2 validation and atomic crash-safe save, v1 legacy warning, golden-value check against the real baseline models, and YAMNet chunked vs full equivalence. |
tests.test_detector |
Qt QCoreApplication, reads wolfset-bands-v1 and one Wolfset WAV (YAMNet if cached) |
StreamProcessor with random block sizes vs offline model.predict, monotonic times and stride, discontinuity/overload gaps, Detector thread restart and sample-rate change, and checking that band-model warm-up never feeds 16 kHz. |
tests.test_ui |
Qt offscreen, fast (no audio, no YAMNet) | MainWindow and SettingsDialog input-device selection, spin-box minimums (channel >= 0, all others >= 1), startup with an unusable data_dir, and forwarding settings.problems to the log panel. |
tests.test_review |
Qt offscreen (plays silence only) | fmt_time, overview FFT bin and dBFS accuracy, draft autosave, shortcuts vs notes/table editing, blocking invalid saves, moving drafts to recordings/, editing saved files, copying previous fields with undo, and Player seek/pause/restart. |
tests.test_training_tab |
Qt offscreen, fake CLI (no YAMNet) | train_* i18n key parity in both languages, broken/partial model.json tolerance, chunked JSON-line parsing, source checkboxes and row exclusion, live model-name validation, progress bar and confusion matrix, error/crash reporting, cancel() killing the real child PID, and safe model deletion (refusing junctions and external paths). |
tests.test_analysis |
Qt offscreen, loads YAMNet (~10–60 s) | analysis.metrics(), windows_at(), truth_segments(), concurrent multi-model runs on synthetic audio, detail-panel HTML, focus separation for keyboard shortcuts, handoff to tab 2, threshold redraw without rerunning, stale-generation filtering and broken-model isolation. |
Running the tests¶
Run tests from the project root. Set QT_QPA_PLATFORM=offscreen so Qt tests do not open visible windows, and TF_CPP_MIN_LOG_LEVEL=2 to suppress TensorFlow startup info messages.
Running individual fast tests in PowerShell:
$env:TF_CPP_MIN_LOG_LEVEL = "2"
.\.venv\Scripts\python.exe -m tests.test_events
.\.venv\Scripts\python.exe -m tests.test_splits
Running all 13 suites in order (fast pure-Python/synthetic checks first, followed by GUI and YAMNet suites):
$env:QT_QPA_PLATFORM = "offscreen"
$env:TF_CPP_MIN_LOG_LEVEL = "2"
$suites = @(
"test_app", "test_events", "test_evaluation", "test_splits",
"test_manifest", "test_annotation", "test_train",
"test_ui", "test_review", "test_training_tab",
"test_detector", "test_models", "test_analysis"
)
foreach ($t in $suites) {
Write-Host "--- $t ---"
.\.venv\Scripts\python.exe -m "tests.$t"
if ($LASTEXITCODE -ne 0) { break }
}
Optional test flags
.\.venv\Scripts\python.exe -m tests.test_splits --realalso checks the realdata/wolfset/splits againstwolfset-bands-v1,wolfset-yamnet-v1andexperiments/runs/split-feasibility/protocol_a_folds.csv.tests.test_training_tabacceptsTRAINING_SCREENSHOT=<file.png>to capture the Training tab after a mock run (settingQT_QPA_FONTDIR=C:/Windows/Fontsfor offscreen font rendering).
Frozen legacy reference (tests/_legacy_91121a7.py)¶
tests/_legacy_91121a7.py holds verbatim copies of dataset.window_labels, train.metrics and analysis.metrics from baseline commit 91121a7daabbde2c93b01eba007efe87f4c80f0c (marked DO NOT EDIT). tests.test_evaluation verifies legacy_train_metrics and legacy_analysis_metrics directly against this file so baseline equivalence is checked without invoking git during test runs. Likewise, tests.test_events embeds a verbatim FrozenAlarm class from the same baseline commit.
The “tests print OK” convention¶
Every runnable test module ends with print("OK"). Any failed assert aborts immediately with an AssertionError and a non-zero exit code before OK is reached. Some suites print short diagnostic lines along the way (for instance, test_detector prints the maximum stream-vs-offline score difference and test_review reports whether an audio output was available), while a final OK line and exit code 0 always indicate a clean pass.
The QTest.qWait GIL pitfall in PySide6 6.12¶
Do not use QTest.qWait while waiting on Python worker threads
Hydrofon pins PySide6==6.12.1, where QTest.qWait() holds Python's Global Interpreter Lock (GIL) while waiting. When a GUI test waits on background Python threads — such as AnalysisTab's ThreadPoolExecutor model workers — QTest.qWait() starves those threads and causes the test to time out.
To avoid stalling Python workers, tests/test_analysis.py pumps events through a real QEventLoop with a short QTimer, releasing the GIL cleanly:
def wait(cond, timeout=300):
end = time.monotonic() + timeout
while not cond():
assert time.monotonic() < end, "timed out"
loop = QEventLoop()
QTimer.singleShot(50, loop.quit)
loop.exec()
Where no Python worker thread needs the GIL — such as waiting on an external QProcess in test_training_tab.py or a Qt timer / PortAudio callback in test_review.py — QTest.qWait() continues to work normally.
See also¶
- Architecture — map of the modules these tests cover
- Command-line tools — CLI commands exercised by
test_train,test_manifest,test_annotationandtest_events - The baseline — baseline results from commit
91121a7 - The evaluation contract — four-layer metrics verified by
test_evaluation