Files
rowing_stats/tests/test_pipeline.py
T
adamfandClaude Opus 5.5 3017cac31b Add tests for parsing, image loading, display detection and CLI
Tesseract is stubbed out except in one end-to-end smoke test on a sample
photo, which is skipped when the binary is not installed.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-09 11:46:19 +01:00

127 lines
4.7 KiB
Python

import json
import shutil
from pathlib import Path
import pytesseract
import pytest
from PIL import Image
from rowing_stats import cli, ocr, pipeline
from rowing_stats.errors import (
DisplayNotFoundError,
ImageLoadError,
OcrError,
TesseractNotInstalledError,
)
from rowing_stats.parsing import WorkoutStats
PHOTOS = Path(__file__).parent.parent / "photos"
@pytest.fixture
def fake_ocr(monkeypatch):
"""Replace Tesseract with a canned read so tests don't need the binary."""
monkeypatch.setattr(pipeline, "ocr_image",
lambda warped, debug_prefix=None, psm=0: "30:06 29 s/m\n7283 m\n")
def test_process_file(monitor_photo_path, fake_ocr):
result = pipeline.process_file(monitor_photo_path)
assert result.file == "monitor.png"
assert result.taken_at is None
assert result.stats == WorkoutStats(elapsed_time="30:06", stroke_rate_spm=29,
distance_m=7283)
assert result.to_dict() == {"file": "monitor.png", "elapsed_time": "30:06",
"stroke_rate_spm": 29, "distance_m": 7283}
def test_process_file_unreadable_image(tmp_path, fake_ocr):
path = tmp_path / "broken.jpeg"
path.write_bytes(b"\x00\x01\x02")
with pytest.raises(ImageLoadError):
pipeline.process_file(path)
def test_process_file_no_display(tmp_path, fake_ocr):
path = tmp_path / "blank.png"
Image.new("RGB", (800, 600), "black").save(path)
with pytest.raises(DisplayNotFoundError):
pipeline.process_file(path)
def test_ocr_image_reports_missing_tesseract(monitor_photo, monkeypatch):
def missing(*args, **kwargs):
raise pytesseract.TesseractNotFoundError()
monkeypatch.setattr(ocr.tess, "image_to_string", missing)
with pytest.raises(TesseractNotInstalledError, match="not installed"):
ocr.ocr_image(monitor_photo)
def test_ocr_image_wraps_tesseract_failure(monitor_photo, monkeypatch):
def fail(*args, **kwargs):
raise pytesseract.TesseractError(1, "boom")
monkeypatch.setattr(ocr.tess, "image_to_string", fail)
with pytest.raises(OcrError, match="boom"):
ocr.ocr_image(monitor_photo)
def test_preprocess_for_ocr_is_binary_and_upscaled(monitor_photo):
out = ocr.preprocess_for_ocr(monitor_photo)
assert out.shape == (600 * ocr.UPSCALE, 800 * ocr.UPSCALE)
assert set(out.ravel().tolist()) <= {0, 255}
def test_collect_paths_expands_directories(tmp_path):
for name in ("b.JPEG", "a.jpg", "c.png", "notes.txt"):
(tmp_path / name).touch()
single = tmp_path / "elsewhere.jpeg"
assert cli.collect_paths([tmp_path / "missing.jpeg", single]) == [
tmp_path / "missing.jpeg", single]
assert [p.name for p in cli.collect_paths([tmp_path])] == ["a.jpg", "b.JPEG", "c.png"]
def test_cli_json_output_and_exit_code(monitor_photo_path, tmp_path, fake_ocr,
capsys, caplog):
broken = tmp_path / "broken.jpeg"
broken.write_text("nope")
code = cli.main(["--format", "json", str(monitor_photo_path), str(broken)])
assert code == 1 # one file failed...
assert "broken.jpeg: not a recognised image format" in caplog.text
assert json.loads(capsys.readouterr().out) == [{ # ...but the other is reported
"file": "monitor.png", "elapsed_time": "30:06",
"stroke_rate_spm": 29, "distance_m": 7283,
}]
def test_cli_csv_output_to_file(monitor_photo_path, tmp_path, fake_ocr):
out = tmp_path / "stats.csv"
assert cli.main(["--format", "csv", "-o", str(out), str(monitor_photo_path)]) == 0
header, row = out.read_text().splitlines()
assert header.split(",") == cli.CSV_COLUMNS
assert row == "monitor.png,,30:06,29,7283,,,,,"
def test_cli_no_images(tmp_path, caplog):
assert cli.main([str(tmp_path)]) == 1
assert "no images found" in caplog.text
def test_cli_stops_when_tesseract_missing(monitor_photo_path, monkeypatch, caplog):
def missing(*args, **kwargs):
raise TesseractNotInstalledError("tesseract is not installed or not on PATH")
monkeypatch.setattr(pipeline, "ocr_image", missing)
assert cli.main([str(monitor_photo_path), str(monitor_photo_path)]) == 1
assert caplog.text.count("not installed") == 1
@pytest.mark.skipif(shutil.which("tesseract") is None, reason="tesseract not installed")
def test_real_photo_end_to_end(tmp_path):
"""Smoke test against a real photo with one field Tesseract reads reliably."""
result = pipeline.process_file(PHOTOS / "IMG_5413.JPEG", debug_dir=tmp_path)
assert result.file == "IMG_5413.JPEG"
assert result.taken_at is not None
assert result.stats.elapsed_time == "30:06"
assert (tmp_path / "IMG_5413_ocr_input.png").is_file()