diff --git a/tests/conftest.py b/tests/conftest.py new file mode 100644 index 0000000..d151711 --- /dev/null +++ b/tests/conftest.py @@ -0,0 +1,20 @@ +from pathlib import Path + +import cv2 as cv +import numpy as np +import pytest + + +@pytest.fixture +def monitor_photo() -> np.ndarray: + """A synthetic photo: dark background with one light, square 'display'.""" + arr = np.full((600, 800, 3), 30, dtype=np.uint8) + cv.rectangle(arr, (300, 200), (500, 400), (200, 200, 200), thickness=-1) + return arr + + +@pytest.fixture +def monitor_photo_path(tmp_path: Path, monitor_photo: np.ndarray) -> Path: + path = tmp_path / "monitor.png" + cv.imwrite(str(path), monitor_photo) + return path diff --git a/tests/test_display.py b/tests/test_display.py new file mode 100644 index 0000000..8a41358 --- /dev/null +++ b/tests/test_display.py @@ -0,0 +1,43 @@ +import numpy as np +import pytest + +from rowing_stats.display import WARPED_SIZE, crop_display, order_points +from rowing_stats.errors import DisplayNotFoundError + + +def test_order_points_returns_tl_tr_br_bl(): + shuffled = np.array([[90, 80], [10, 15], [12, 85], [95, 12]], dtype="float32") + assert order_points(shuffled).tolist() == [[10, 15], [95, 12], [90, 80], [12, 85]] + + +def test_crop_display_warps_square_region(monitor_photo): + warped = crop_display(monitor_photo) + assert warped.shape == (WARPED_SIZE, WARPED_SIZE, 3) + # The crop should be the light display, not the dark background + assert warped[50:350, 50:350].mean() > 150 + + +def test_crop_display_blank_image_raises(): + blank = np.zeros((600, 800, 3), dtype=np.uint8) + with pytest.raises(DisplayNotFoundError): + crop_display(blank) + + +def test_crop_display_ignores_non_square_region(): + arr = np.full((600, 800, 3), 30, dtype=np.uint8) + arr[250:350, 100:700] = 200 # wide banner, 6:1 + with pytest.raises(DisplayNotFoundError): + crop_display(arr) + + +def test_crop_display_ignores_tiny_square(): + arr = np.full((600, 800, 3), 30, dtype=np.uint8) + arr[300:320, 400:420] = 200 # well under 1% of the frame + with pytest.raises(DisplayNotFoundError): + crop_display(arr) + + +def test_crop_display_writes_debug_images(monitor_photo, tmp_path): + crop_display(monitor_photo, debug_prefix=tmp_path / "shot") + assert (tmp_path / "shot_contours.png").is_file() + assert (tmp_path / "shot_warped.png").is_file() diff --git a/tests/test_image_io.py b/tests/test_image_io.py new file mode 100644 index 0000000..34e54ca --- /dev/null +++ b/tests/test_image_io.py @@ -0,0 +1,70 @@ +from datetime import datetime + +import numpy as np +import pytest +from PIL import Image + +from rowing_stats.errors import ImageLoadError +from rowing_stats.image_io import ( + EXIF_DATETIME_TAG, + get_datetime_taken, + load_image, + pil_to_cv, +) + + +def test_load_image_missing_file(tmp_path): + with pytest.raises(ImageLoadError, match="not found"): + load_image(tmp_path / "nope.jpeg") + + +def test_load_image_not_an_image(tmp_path): + path = tmp_path / "notes.jpeg" + path.write_text("this is not a JPEG") + with pytest.raises(ImageLoadError, match="not a recognised image"): + load_image(path) + + +def test_load_image_truncated_file(tmp_path): + whole = tmp_path / "whole.jpeg" + Image.new("RGB", (64, 64), "white").save(whole) + truncated = tmp_path / "truncated.jpeg" + truncated.write_bytes(whole.read_bytes()[:200]) + with pytest.raises(ImageLoadError, match="could not read"): + load_image(truncated) + + +def test_load_image_directory(tmp_path): + with pytest.raises(ImageLoadError): + load_image(tmp_path) + + +def test_pil_to_cv_swaps_channels_to_bgr(): + arr = pil_to_cv(Image.new("RGB", (2, 3), (255, 0, 0))) + assert arr.shape == (3, 2, 3) + assert arr[0, 0].tolist() == [0, 0, 255] + + +def test_pil_to_cv_handles_greyscale_and_alpha(): + assert pil_to_cv(Image.new("L", (2, 2))).shape == (2, 2, 3) + assert pil_to_cv(Image.new("RGBA", (2, 2))).shape == (2, 2, 3) + assert pil_to_cv(Image.new("L", (2, 2))).dtype == np.uint8 + + +def _with_exif_datetime(value: str) -> Image.Image: + img = Image.new("RGB", (2, 2)) + img.getexif()[EXIF_DATETIME_TAG] = value + return img + + +def test_get_datetime_taken(): + img = _with_exif_datetime("2025:11:15 22:16:05") + assert get_datetime_taken(img) == datetime(2025, 11, 15, 22, 16, 5) + + +def test_get_datetime_taken_missing(): + assert get_datetime_taken(Image.new("RGB", (2, 2))) is None + + +def test_get_datetime_taken_malformed(): + assert get_datetime_taken(_with_exif_datetime("yesterday")) is None diff --git a/tests/test_parsing.py b/tests/test_parsing.py new file mode 100644 index 0000000..10b01fd --- /dev/null +++ b/tests/test_parsing.py @@ -0,0 +1,136 @@ +import pytest + +from rowing_stats.parsing import WorkoutStats, clean_ocr_text, parse_stats + +# What a clean read of the calories screen looks like +CALORIES_SCREEN = """ +1:00:33 28 s/m +770 Cal/hr +844 Cal +13879 m +6 split Cal +26911 projected m 2:00:00 +""" + +# What a clean read of the pace screen looks like +PACE_SCREEN = """ +30:06 29 s/m +2:03.5 /500m +7283 m +2:04.1 ave /500m +""" + + +@pytest.mark.parametrize("raw, expected", [ + ("", ""), + (" \n\t ", ""), + ("30:06", "30:06"), + (" 30:06 \n\n 29 s/m\n", "30:06 29 s/m"), + ("a\tb\r\nc", "a b c"), +]) +def test_clean_ocr_text_collapses_whitespace(raw, expected): + assert clean_ocr_text(raw) == expected + + +def test_parses_calories_screen(): + assert parse_stats(CALORIES_SCREEN) == WorkoutStats( + elapsed_time="1:00:33", + stroke_rate_spm=28, + distance_m=13879, + cal_per_hr=770, + calories=844, + projected_m=26911, + ) + + +def test_parses_pace_screen(): + assert parse_stats(PACE_SCREEN) == WorkoutStats( + elapsed_time="30:06", + stroke_rate_spm=29, + distance_m=7283, + split_500m="2:03.5", + avg_split_500m="2:04.1", + ) + + +@pytest.mark.parametrize("text", ["", " \n ", "glgg", ".vMes:AJ", "Egggi::igg"]) +def test_garbage_yields_no_stats(text): + assert parse_stats(text) == WorkoutStats() + assert parse_stats(text).to_dict() == {} + + +@pytest.mark.parametrize("text, expected", [ + ("30:06", "30:06"), + ("1:00:33", "1:00:33"), + ("5:07 29", "5:07"), + ("30:06 then 45:10", "30:06"), # first one wins + ("30:99", None), # seconds out of range + ("2:03 /500m", None), # a pace, not elapsed time + ("2:03.5", None), + ("2:04 ave", None), + ("2:03 /500m 30:06", "30:06"), +]) +def test_elapsed_time(text, expected): + assert parse_stats(text).elapsed_time == expected + + +@pytest.mark.parametrize("text, expected", [ + ("29 s/m", 29), + ("29S/m", 29), + ("29 s\\m", 29), + ("9 s/m", None), + ("29", None), +]) +def test_stroke_rate(text, expected): + assert parse_stats(text).stroke_rate_spm == expected + + +@pytest.mark.parametrize("text, expected", [ + ("7283 m", 7283), + ("13879m", 13879), + ("7283 M", 7283), + ("2:03 /500m", None), # the 500m of a pace label + ("2:03 / 500m", None), + ("2:03 /500m 7283 m", 7283), + ("42 m", None), +]) +def test_distance(text, expected): + assert parse_stats(text).distance_m == expected + + +def test_split_and_average_split_are_distinguished(): + stats = parse_stats("2:03 /500m 2:05.2 ave /500m") + assert stats.split_500m == "2:03" + assert stats.avg_split_500m == "2:05.2" + + +@pytest.mark.parametrize("text, cal_per_hr, calories", [ + ("958 Cal/hr", 958, None), # must not be read as total calories + ("1229 cal/hr 467 Cal", 1229, 467), + ("467 Cal", None, 467), + ("467 Cal 1229 Cal/hr", 1229, 467), + ("958 Cal\\hr", 958, None), +]) +def test_calories_and_cal_per_hr(text, cal_per_hr, calories): + stats = parse_stats(text) + assert stats.cal_per_hr == cal_per_hr + assert stats.calories == calories + + +@pytest.mark.parametrize("text, expected", [ + ("26911 projected m", 26911), + ("9800 projected", 9800), + ("13879 26911", 26911), # unlabelled: last 5-digit number + ("13879 m", None), # already claimed as the distance + ("13879 m 26911", 26911), + ("1234", None), +]) +def test_projected(text, expected): + assert parse_stats(text).projected_m == expected + + +def test_to_dict_omits_missing_fields(): + assert parse_stats("30:06 29 s/m").to_dict() == { + "elapsed_time": "30:06", + "stroke_rate_spm": 29, + } diff --git a/tests/test_pipeline.py b/tests/test_pipeline.py new file mode 100644 index 0000000..eafcf49 --- /dev/null +++ b/tests/test_pipeline.py @@ -0,0 +1,126 @@ +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()