Files
lucioandClaude Opus 5 5a61890011 feat: read-only Wodify athlete client
A CLI that answers "what classes ran", "who was there" and "what was the
workout" with a single HTTP POST each -- no browser at query time.

Wodify's athlete app is an OutSystems Reactive SPA. Driving it with a headless
browser works but is slow and, for an LLM agent, expensive: a full page render
to read a few lines back out of the DOM. Its data actions are plain JSON
endpoints, so this talks to them directly.

  wodify list date 2026-07-25      time, coach, booked/max, title, duration, ID
  wodify list workout <id>         attendee names + that class's workout

Two phases. `prime` attaches over CDP to a browser that is already logged in and
captures the session cookies, the CSRF token, and each action's apiVersion and
body shape. Everything after that is stdlib HTTP -- the query path has no
third-party dependencies at all.

Three things genuinely require the browser, which is why priming exists:
- the session bearer nr1W_Theme_UI is HttpOnly, so it cannot be exported by hand
- X-CSRFToken is not in cookies, localStorage, or any JS global
- apiVersion is per-action, not global

Read-only is enforced in code, not by the credential (Wodify issues no
read-only token): an explicit allowlist plus a write-marker guard applied even
to allowlisted paths, so a careless registry edit fails closed. Tests assert
that real mutating endpoint names are refused.

Responses are cached in SQLite, keyed by the local date they were fetched on, so
a repeat query the same day touches no network. All fetching funnels through
service.py so a call site cannot forget the cache.

Staleness is explicit rather than silent: responses carry
hasModuleVersionChanged/hasApiVersionChanged, and the client raises
VersionStale/SessionExpired instead of returning a plausible empty result. That
matters because every bug found while building this produced confident wrong
output rather than an error -- see CLAUDE.md for the field-name traps.

History squashed before first publication: earlier commits embedded real gym
members' names in test fixtures. Fixtures now use fictional names.

122 tests, no network required.

Co-Authored-By: Claude Opus 5 <[email protected]>
2026-07-25 09:23:19 -07:00

182 lines
6.5 KiB
Python

"""Cache handling and error mapping. No network."""
from __future__ import annotations
import json
import pytest
from wodify import actions, client
def _cache(**over):
base = {
"host": "example.wodify.com",
"primed_at": "2026-07-25T00:00:00+00:00",
"cookie": "nr1W_Theme_UI=a; nr2W_Theme_UI=b",
"csrf": "c" * 28,
"module_version": "mv",
"actions": {
actions.ACTIONS["bookings"].path: {
"api_version": "av",
"view_name": "MainScreens.Home",
"body_template": {
"viewName": "MainScreens.Home",
"screenData": {"variables": {
"ClientVariables": {"SelectedDate": "1900-01-01",
"GymProgramId": "0"},
}},
},
}
},
}
base.update(over)
return base
def test_cache_round_trip(tmp_path):
path = tmp_path / "session.json"
client.save_cache(_cache(), path)
loaded = client.load_cache(path)
assert loaded["csrf"] == "c" * 28
assert loaded["cache_version"] == client.CACHE_VERSION
def test_missing_cache_raises_not_primed(tmp_path):
with pytest.raises(client.NotPrimedError, match="no session cache"):
client.load_cache(tmp_path / "absent.json")
def test_corrupt_cache_raises_not_primed(tmp_path):
path = tmp_path / "session.json"
path.write_text("{not json", encoding="utf-8")
with pytest.raises(client.NotPrimedError, match="unreadable"):
client.load_cache(path)
@pytest.mark.parametrize("field", ["cookie", "csrf", "module_version", "actions"])
def test_incomplete_cache_rejected(tmp_path, field):
path = tmp_path / "session.json"
data = _cache()
data[field] = "" if field != "actions" else {}
path.write_text(json.dumps(data), encoding="utf-8")
with pytest.raises(client.NotPrimedError, match=field):
client.load_cache(path)
def test_set_field_writes_every_existing_occurrence():
node = {"a": {"SelectedDate": "x"}, "b": [{"SelectedDate": "y"}, {"other": 1}]}
assert client.set_field(node, "SelectedDate", "2026-07-24") == 2
assert node["a"]["SelectedDate"] == "2026-07-24"
assert node["b"][0]["SelectedDate"] == "2026-07-24"
def test_set_field_does_not_invent_keys():
"""OutSystems rejects unknown body keys, so absent fields must stay absent."""
node = {"a": {"Existing": 1}}
assert client.set_field(node, "ClassId", 42) == 0
assert "ClassId" not in node["a"]
def test_overrides_are_applied_to_body(monkeypatch):
sent = {}
def capture(url, body, headers, timeout):
sent["body"] = json.loads(body)
return 200, json.dumps({"versionInfo": {}, "data": {"ok": True}})
monkeypatch.setattr(client, "_post", capture)
client.call("bookings", {"SelectedDate": "2026-07-24"}, cache=_cache())
variables = sent["body"]["screenData"]["variables"]["ClientVariables"]
assert variables["SelectedDate"] == "2026-07-24"
def test_none_overrides_are_skipped(monkeypatch):
sent = {}
def capture(url, body, headers, timeout):
sent["body"] = json.loads(body)
return 200, json.dumps({"versionInfo": {}, "data": {}})
monkeypatch.setattr(client, "_post", capture)
client.call("bookings", {"SelectedDate": None}, cache=_cache())
variables = sent["body"]["screenData"]["variables"]["ClientVariables"]
assert variables["SelectedDate"] == "1900-01-01", "None must not overwrite"
def test_version_info_is_always_rewritten(monkeypatch):
sent = {}
def capture(url, body, headers, timeout):
sent["body"] = json.loads(body)
return 200, json.dumps({"versionInfo": {}, "data": {}})
monkeypatch.setattr(client, "_post", capture)
client.call("bookings", {}, cache=_cache())
assert sent["body"]["versionInfo"] == {"moduleVersion": "mv", "apiVersion": "av"}
def test_template_is_not_mutated_between_calls(monkeypatch):
monkeypatch.setattr(client, "_post",
lambda *a, **k: (200, json.dumps({"versionInfo": {}, "data": {}})))
cache = _cache()
client.call("bookings", {"SelectedDate": "2026-07-24"}, cache=cache)
template = cache["actions"][actions.ACTIONS["bookings"].path]["body_template"]
assert template["screenData"]["variables"]["ClientVariables"]["SelectedDate"] == "1900-01-01"
def test_missing_body_template_raises(tmp_path):
stale = _cache()
entry = stale["actions"][actions.ACTIONS["bookings"].path]
del entry["body_template"]
with pytest.raises(client.NotPrimedError, match="body_template"):
client.call("bookings", {}, cache=stale)
def test_action_without_api_version_raises(tmp_path):
"""apiVersion is per-action; an unprimed action must fail loudly."""
with pytest.raises(client.NotPrimedError, match="per-action"):
client.call("attendees", {}, cache=_cache())
def test_call_refuses_unknown_action():
with pytest.raises(actions.UnknownActionError):
client.call("nope", {}, cache=_cache())
def _stub_post(monkeypatch, status, text):
monkeypatch.setattr(client, "_post", lambda *a, **k: (status, text))
@pytest.mark.parametrize("status", [401, 403])
def test_auth_failure_maps_to_session_expired(monkeypatch, status):
_stub_post(monkeypatch, status, "denied")
with pytest.raises(client.SessionExpiredError):
client.call("bookings", {}, cache=_cache())
def test_html_login_page_maps_to_session_expired(monkeypatch):
_stub_post(monkeypatch, 200, "<html><body>Sign into Wodify</body></html>")
with pytest.raises(client.SessionExpiredError, match="login page"):
client.call("bookings", {}, cache=_cache())
@pytest.mark.parametrize("flag", ["hasModuleVersionChanged", "hasApiVersionChanged"])
def test_version_change_maps_to_version_stale(monkeypatch, flag):
_stub_post(monkeypatch, 200, json.dumps({"versionInfo": {flag: True}, "data": {"x": 1}}))
with pytest.raises(client.VersionStaleError):
client.call("bookings", {}, cache=_cache())
def test_successful_call_returns_data(monkeypatch):
payload = {"versionInfo": {"hasModuleVersionChanged": False,
"hasApiVersionChanged": False},
"data": {"Response": {"List": [{"Id": 1}]}}}
_stub_post(monkeypatch, 200, json.dumps(payload))
assert client.call("bookings", {}, cache=_cache()) == payload["data"]
def test_server_error_surfaces(monkeypatch):
_stub_post(monkeypatch, 500, "boom")
with pytest.raises(RuntimeError, match="HTTP 500"):
client.call("bookings", {}, cache=_cache())