"""Tests for the Claude reader. No Claude call happens here: `claude._client` is replaced with a fake whose `messages.create` returns a canned reply, so what is under test is everything around the call - the request that is built, how the reply is parsed and validated, and how failures are reported. """ import base64 from pathlib import Path from types import SimpleNamespace import pytest from PIL import Image from rowing_stats import claude from rowing_stats.errors import ClaudeUnavailableError, ExtractionError, ImageLoadError GOOD_REPLY = '{"timeMinutes": 30, "timeSeconds": 6, "distance": 7283}' def text_reply(text): return SimpleNamespace(content=[SimpleNamespace(type="text", text=text)]) @pytest.fixture def fake_claude(monkeypatch): """Stand in for the Anthropic client; returns the list of calls it received. Set `fake_claude.reply` to a message-like object, or to an exception instance to have the call raise it. """ pytest.importorskip("anthropic") state = SimpleNamespace(calls=[], reply=text_reply(GOOD_REPLY)) def create(**kwargs): state.calls.append(kwargs) if isinstance(state.reply, Exception): raise state.reply return state.reply client = SimpleNamespace(messages=SimpleNamespace(create=create)) monkeypatch.setattr(claude, "_client", lambda: client) return state @pytest.fixture def dated_photo(tmp_path) -> Path: path = tmp_path / "IMG_5413.jpeg" img = Image.new("RGB", (8, 8), "white") exif = img.getexif() exif[claude.ExifBase.DateTime] = "2025:11:05 12:08:00" img.save(path, exif=exif) return path # --- reply parsing ---------------------------------------------------------- @pytest.mark.parametrize("raw, expected", [ ('{"a": 1}', '{"a": 1}'), (' {"a": 1}\n', '{"a": 1}'), ('```json\n{"a": 1}\n```', '{"a": 1}'), ('```\n{"a": 1}\n```', '{"a": 1}'), ('```json\n{"a": 1}', '{"a": 1}'), ]) def test_strip_markdown_fence(raw, expected): assert claude.strip_markdown_fence(raw) == expected def test_parse_reply(): assert claude.parse_reply(GOOD_REPLY) == (30, 6, 7283) assert claude.parse_reply(f"```json\n{GOOD_REPLY}\n```") == (30, 6, 7283) assert claude.parse_reply('{"timeMinutes": "30", "timeSeconds": 6.0, "distance": 7283}') \ == (30, 6, 7283) @pytest.mark.parametrize("raw", [ "I can't read that display.", "", '{"timeMinutes": 30, "timeSeconds": 6}', # key missing '{"timeMinutes": null, "timeSeconds": 6, "distance": 7283}', '{"timeMinutes": "thirty", "timeSeconds": 6, "distance": 7283}', "[30, 6, 7283]", # not an object ]) def test_parse_reply_rejects_anything_else(raw): with pytest.raises(ExtractionError, match="Unparseable reply"): claude.parse_reply(raw) # --- sanity bounds ---------------------------------------------------------- def test_validate_reading_derives_metrics(): data = claude.validate_reading(30, 6, 7283) assert data.total_seconds == 1806 assert data.time_per_500m == 123.99 assert data.calories == 485.53 assert data.date_taken is None @pytest.mark.parametrize("minutes, seconds, distance, message", [ (30, 6, 0, "Invalid distance: 0"), (0, 25, 99, "Anomalous distance: 99"), (30, 6, 100_001, "Anomalous distance"), (0, 29, 100, "Anomalous time: 29s"), (120, 1, 30_000, "Anomalous time: 7201s"), (30, 6, 12_000, "Anomalous pace"), # 1:15 /500m: faster than anyone rows (30, 6, 5_000, "Anomalous pace"), # 3:01 /500m: a digit was dropped (30, 6, 728, "Anomalous pace"), ]) def test_validate_reading_rejects_implausible_values(minutes, seconds, distance, message): with pytest.raises(ExtractionError, match=message): claude.validate_reading(minutes, seconds, distance) @pytest.mark.parametrize("minutes, seconds, distance", [ (0, 30, 150), # shortest allowed, 1:40 pace (120, 0, 30_000), # two hours exactly, 2:00 pace (40, 0, 15_000), # 1:20 pace exactly (50, 0, 10_000), # 2:30 pace exactly ]) def test_validate_reading_accepts_the_boundaries(minutes, seconds, distance): assert claude.validate_reading(minutes, seconds, distance).distance == distance # --- dates and file selection ----------------------------------------------- @pytest.mark.parametrize("raw, expected", [ ("2025:11:05 12:08:00", "2025-11-05 12:08:00"), (" 2025:11:05 12:08:00 ", "2025-11-05 12:08:00"), ("yesterday", None), ("", None), (None, None), ]) def test_format_exif_date(raw, expected): assert claude.format_exif_date(raw) == expected def test_get_exif_date(dated_photo, tmp_path, corrupt_path): assert claude.get_exif_date(dated_photo) == "2025:11:05 12:08:00" undated = tmp_path / "undated.png" Image.new("RGB", (8, 8)).save(undated) assert claude.get_exif_date(undated) is None with pytest.raises(ImageLoadError): claude.get_exif_date(corrupt_path) def test_keep_latest_versions(): names = ["IMG_1_screen.jpg", "IMG_1_screen (1).jpg", "IMG_1_screen (3).jpg", "IMG_2_screen (10).jpg", "IMG_2_screen (9).jpg", "IMG_3_screen.jpg"] kept = claude._keep_latest_versions([Path(n) for n in names]) assert [p.name for p in kept] == [ "IMG_1_screen (3).jpg", "IMG_2_screen (10).jpg", "IMG_3_screen.jpg"] # --- the call --------------------------------------------------------------- def test_extract_rowing_data_sends_image_then_prompt(fake_claude, dated_photo): data = claude.extract_rowing_data(dated_photo) assert (data.time_minutes, data.time_seconds, data.distance) == (30, 6, 7283) assert data.date_taken == "2025:11:05 12:08:00" (call,) = fake_claude.calls assert call["model"] == claude.MODEL image, prompt = call["messages"][0]["content"] assert image["source"]["media_type"] == "image/jpeg" assert base64.standard_b64decode(image["source"]["data"]) == dated_photo.read_bytes() assert prompt == {"type": "text", "text": claude.PROMPT} def test_bad_images_never_reach_the_api(fake_claude, tmp_path, corrupt_path): heic = tmp_path / "photo.heic" heic.touch() with pytest.raises(ImageLoadError, match="unsupported image type"): claude.extract_rowing_data(heic) with pytest.raises(ImageLoadError, match="not a readable image"): claude.extract_rowing_data(corrupt_path) with pytest.raises(ImageLoadError, match="file not found"): claude.extract_rowing_data(tmp_path / "missing.jpg") assert fake_claude.calls == [] def test_unusable_replies(fake_claude, dated_photo): fake_claude.reply = SimpleNamespace(content=[]) with pytest.raises(ExtractionError, match="Empty response"): claude.extract_rowing_data(dated_photo) fake_claude.reply = text_reply('{"timeMinutes": 30, "timeSeconds": 6, "distance": 728}') with pytest.raises(ExtractionError, match="Anomalous pace"): claude.extract_rowing_data(dated_photo) def _api_error(cls, status): import httpx2 as httpx request = httpx.Request("POST", "https://api.anthropic.com/v1/messages") return cls("nope", response=httpx.Response(status, request=request), body=None) def test_api_failures_are_reported_per_image(fake_claude, dated_photo): import anthropic import httpx2 as httpx fake_claude.reply = _api_error(anthropic.RateLimitError, 429) with pytest.raises(ExtractionError, match="Claude API error 429"): claude.extract_rowing_data(dated_photo) fake_claude.reply = anthropic.APIConnectionError( request=httpx.Request("POST", "https://api.anthropic.com/v1/messages")) with pytest.raises(ExtractionError, match="unreachable"): claude.extract_rowing_data(dated_photo) def test_credential_problems_stop_the_run(fake_claude, dated_photo, capsys): import anthropic fake_claude.reply = _api_error(anthropic.AuthenticationError, 401) with pytest.raises(ClaudeUnavailableError, match="rejected the credentials"): claude.extract_rowing_data(dated_photo) fake_claude.reply = TypeError("Could not resolve authentication method.") with pytest.raises(ClaudeUnavailableError, match="ANTHROPIC_API_KEY"): claude.extract_rowing_data(dated_photo) # From the CLI: reported once, not once per image Image.new("RGB", (8, 8)).save(dated_photo.with_name("second.png")) assert claude.main(["--dir", str(dated_photo.parent)]) == 1 assert len(fake_claude.calls) == 3 assert capsys.readouterr().err.count("ANTHROPIC_API_KEY") == 1 def test_an_unrelated_type_error_is_not_swallowed(fake_claude, dated_photo): fake_claude.reply = TypeError("unexpected keyword argument") with pytest.raises(TypeError): claude.extract_rowing_data(dated_photo) def test_cli_writes_the_results_csv(fake_claude, dated_photo, corrupt_path, capsys): output = dated_photo.parent / "results.csv" code = claude.main(["--dir", str(dated_photo.parent), "--output", str(output)]) out = capsys.readouterr().out assert code == 1 # the corrupt file failed assert "ERROR: corrupt.jpg: not a readable image" in out assert "Time: 30:06" in out and "Pace: 2:04.0 /500m" in out assert output.read_text().splitlines() == [ "image,time,distance_m,pace_per_500m,calories,date_taken", "IMG_5413.jpeg,30:06,7283,2:04.0,486,2025-11-05 12:08:00", ]