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]>
This commit is contained in:
commit
5a61890011
31 files changed
+3576
No files matched your search
@@ -0,0 +1,78 @@
|
||||
"""The read-only guard is the only thing preventing this client from spending
|
||||
the user's money or taking someone's class spot. Test it hard."""
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
|
||||
from wodify import actions
|
||||
|
||||
|
||||
def test_every_registered_action_is_read_only():
|
||||
for key, action in actions.ACTIONS.items():
|
||||
actions.assert_read_only(action.path) # must not raise
|
||||
assert action.key == key, "registry key must match Action.key"
|
||||
assert action.path, f"{key} has no path"
|
||||
assert not action.path.startswith("/"), f"{key} path should be relative"
|
||||
|
||||
|
||||
def test_get_returns_action():
|
||||
assert actions.get("bookings").key == "bookings"
|
||||
|
||||
|
||||
def test_unknown_action_rejected():
|
||||
with pytest.raises(actions.UnknownActionError):
|
||||
actions.get("definitely-not-a-real-action")
|
||||
|
||||
|
||||
# Real mutating endpoint names observed in Wodify's client, plus plausible
|
||||
# variants. None may ever pass the guard.
|
||||
@pytest.mark.parametrize("path", [
|
||||
"WodifyClient_Class/Classes/Class/ServiceAPICreateClassReservation",
|
||||
"WodifyClient_Class/Classes/Class/ActionCancelReservation",
|
||||
"WodifyClient_DataFetch_WB/WOD_Flow/SaveWorkoutResult",
|
||||
"WodifyClient/Common/ActionAcceptTermsAndConditions",
|
||||
"WodifyClient_Class/Classes/Class/ClientActionSignInToClass",
|
||||
"WodifyClient/MainScreens/ActionSubmitAppReview",
|
||||
"WodifyClient_Class/Classes/ActionLeaveWaitlist",
|
||||
"WodifyClient/Account/ActionLogout",
|
||||
"WodifyClient/POS/ActionPurchaseItem",
|
||||
"WodifyClient/WOD/ActionAddResult",
|
||||
])
|
||||
def test_write_endpoints_are_refused(path):
|
||||
with pytest.raises(actions.WriteAttemptError):
|
||||
actions.assert_read_only(path)
|
||||
|
||||
|
||||
def test_guard_is_case_insensitive():
|
||||
with pytest.raises(actions.WriteAttemptError):
|
||||
actions.assert_read_only("Module/Screen/ACTIONCREATERESERVATION")
|
||||
|
||||
|
||||
def test_guard_does_not_block_legitimate_read_paths():
|
||||
"""Guard markers must not false-positive on the reads we actually need.
|
||||
|
||||
'GetClassWaitList' in particular has to stay callable -- reading a waitlist
|
||||
is fine, joining or leaving it is not.
|
||||
"""
|
||||
safe = [
|
||||
"WodifyClient_DataFetch_WB/Schedule_OS/GetClassWaitList_WB/DataActionGetClassWaitList",
|
||||
"WodifyClient_DataFetch_WB/Schedule_OS/GetClassAttendees_WB/DataActionGetClassAttendees",
|
||||
"WodifyClient_DataFetch_WB/WOD_Flow/GetWorkoutData_HasWodLeaderboardComponents"
|
||||
"/DataActionGetWorkoutDataHasWodLeaderboardComponents",
|
||||
"WodifyClient_Class/Classes/Attendance/DataActionGetClasses",
|
||||
]
|
||||
for path in safe:
|
||||
actions.assert_read_only(path)
|
||||
|
||||
|
||||
def test_all_expected_actions_registered():
|
||||
expected = {"bookings", "wodflags", "attendees", "classdetail",
|
||||
"coach", "classes", "waitlist"}
|
||||
assert expected <= set(actions.keys())
|
||||
|
||||
|
||||
def test_get_returns_action_for_workout_probe():
|
||||
"""wodflags is deliberately not called 'workout': it returns a boolean, and
|
||||
naming it 'workout' invited reporting 'no workout' from a probe response."""
|
||||
action = actions.get("wodflags")
|
||||
assert "NOT the workout text" in action.summary
|
||||
@@ -0,0 +1,116 @@
|
||||
"""Attendee parsing.
|
||||
|
||||
The name field is PersonName under Response.ClassDetailAttendee.List. An earlier
|
||||
version looked for "Name", found nothing on a full class, and printed an invented
|
||||
explanation about anonymous members -- a fabricated cause for its own bug. These
|
||||
tests exist so that cannot recur.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from wodify import render
|
||||
|
||||
|
||||
def _att(name, status="Reserved", signed_in=False, no_show=False,
|
||||
waitlisted=False, anonymous=False, rid=None):
|
||||
return {
|
||||
"PersonName": name,
|
||||
"StatusInClass": status,
|
||||
"HasReserved": True,
|
||||
"HasSignedIn": signed_in,
|
||||
"HasNoShow": no_show,
|
||||
"isWaitlisted": waitlisted,
|
||||
"IsAnonymous": anonymous,
|
||||
"MemberSince": "2025-10-17",
|
||||
"ClassReservationId": rid or f"res-{name}",
|
||||
# Traps: nested zeros that must not be mistaken for the real fields.
|
||||
"ClassId": "0",
|
||||
"ProgramId": "0",
|
||||
}
|
||||
|
||||
|
||||
CLASS = {"Response": {"ClassDetailAttendee": {"List": [
|
||||
_att("Alex Rivera"),
|
||||
_att("Sam Okafor", status="Signed In", signed_in=True),
|
||||
_att("Jordan Kim", no_show=True),
|
||||
_att("Wanda Waits", waitlisted=True),
|
||||
]}}}
|
||||
|
||||
|
||||
def test_person_name_field_is_read():
|
||||
"""Regression: reading "Name" yields nothing and looks like an empty class."""
|
||||
names = render.attendee_names(CLASS)
|
||||
assert "Alex Rivera" in names
|
||||
assert len(names) == 4
|
||||
|
||||
|
||||
def test_waitlisted_separated_from_roster():
|
||||
out = render.attendee_block(CLASS)
|
||||
assert "## Attendees — 3" in out, "waitlisted people are not attendees"
|
||||
assert "Waitlist — 1" in out
|
||||
assert "Wanda Waits" in out
|
||||
|
||||
|
||||
def test_signed_in_marked():
|
||||
assert "Sam Okafor [signed in]" in render.attendee_block(CLASS)
|
||||
|
||||
|
||||
def test_no_show_marked():
|
||||
out = render.attendee_block(CLASS)
|
||||
assert "Jordan Kim" in out and "no-show" in out
|
||||
|
||||
|
||||
def test_capacity_shown_when_supplied():
|
||||
out = render.attendee_block(CLASS, booked=12, limit=12)
|
||||
assert "of 12/12 booked" in out
|
||||
|
||||
|
||||
def test_gap_between_booked_and_listed_is_flagged():
|
||||
"""A class the account attended lists one fewer than booked; say so rather
|
||||
than let it read as a miscount."""
|
||||
out = render.attendee_block(CLASS, booked=4, limit=10) # 3 on roster + 1 waitlisted
|
||||
assert "1 booked not listed" in out
|
||||
|
||||
|
||||
def test_no_gap_note_when_counts_agree():
|
||||
out = render.attendee_block(CLASS, booked=3, limit=10)
|
||||
assert "not listed" not in out
|
||||
|
||||
|
||||
def test_duplicate_reservations_deduplicated():
|
||||
dupe = {"Response": {"ClassDetailAttendee": {"List": [
|
||||
_att("Alex Rivera", rid="r1"), _att("Alex Rivera", rid="r1"),
|
||||
]}}}
|
||||
assert render.attendee_names(dupe) == ["Alex Rivera"]
|
||||
|
||||
|
||||
def test_empty_list_does_not_invent_a_reason():
|
||||
"""Say what is true -- nothing was returned -- and do not speculate why."""
|
||||
out = render.attendee_block({"Response": {"ClassDetailAttendee": {"List": []}}})
|
||||
assert "None returned" in out
|
||||
assert "anonymous" not in out.lower()
|
||||
|
||||
|
||||
def test_falls_back_to_first_last_name():
|
||||
data = {"Response": {"ClassDetailAttendee": {"List": [
|
||||
{"Firstname": "Pat", "LastName": "Doyle", "ClassReservationId": "r9"},
|
||||
]}}}
|
||||
assert render.attendee_names(data) == ["Pat Doyle"]
|
||||
|
||||
|
||||
# --- duration ---------------------------------------------------------------
|
||||
|
||||
def test_duration_basic():
|
||||
assert render.duration_minutes("17:30:00", "18:30:00") == 60
|
||||
|
||||
|
||||
def test_duration_across_midnight():
|
||||
assert render.duration_minutes("23:30:00", "00:30:00") == 60
|
||||
|
||||
|
||||
def test_duration_unparseable_is_none():
|
||||
assert render.duration_minutes("", "") is None
|
||||
assert render.duration_minutes("bogus", "18:30:00") is None
|
||||
|
||||
|
||||
def test_hhmm_trims_seconds():
|
||||
assert render._hhmm("17:30:00") == "17:30"
|
||||
@@ -0,0 +1,181 @@
|
||||
"""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())
|
||||
@@ -0,0 +1,104 @@
|
||||
"""Component field coverage.
|
||||
|
||||
Reading only Name/Comment silently dropped the actual movements -- the metcon
|
||||
lives in Description and the strength scheme in MeasureRepScheme. These tests
|
||||
exist so that regression cannot recur quietly.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from wodify import render
|
||||
|
||||
STRENGTH = {
|
||||
"Id": "123372266",
|
||||
"IsWeightlifting": True,
|
||||
"Name": "Shoulder Press",
|
||||
"Comment": "<p>--</p><p>Strict overhead pressing progression.</p>",
|
||||
"MeasureRepScheme": "Strict Press\nEvery 2:30 x 4 Sets\nSet 1: 10 Reps",
|
||||
"WODComponentVariableRepScheme": "(1 x 10) (1 x 8) (1 x 6) (1 x 4)",
|
||||
"WODComponentOrder": 2,
|
||||
}
|
||||
|
||||
METCON = {
|
||||
"Id": "123372267",
|
||||
"IsMetcon": True,
|
||||
"Name": '"Hat Trick"',
|
||||
"Comment": "<p>Goals: ~2:00 per set</p><p>RPE: 9/10</p>",
|
||||
"Description": "<p>For Time</p><p>Every 5:00 x 3 Sets</p><p>21 Wall Balls</p>",
|
||||
"Rounds": 3,
|
||||
"EachRoundTypeLabel": "For Time ↓ Shorter is Better",
|
||||
"WODComponentOrder": 3,
|
||||
}
|
||||
|
||||
SECTION = {"Id": "1", "IsSection": True, "Name": "WARM-UP",
|
||||
"Comment": "<p>2:00 Cardio Choice</p>", "WODComponentOrder": 1}
|
||||
|
||||
|
||||
def _wod(components):
|
||||
return {"Response": {"ResponseWOD": {"ResponseWorkout": {
|
||||
"Id": "25201299", "Name": "CrossFit - Mon, Jul 20", "Notes": "",
|
||||
"WorkoutComponents": {"List": components},
|
||||
}}}}
|
||||
|
||||
|
||||
def test_metcon_description_is_rendered():
|
||||
"""Description carries the movements. Without it the output looks complete
|
||||
but contains no workout."""
|
||||
out = render.workout(_wod([METCON]))
|
||||
assert "21 Wall Balls" in out
|
||||
assert "Every 5:00 x 3 Sets" in out
|
||||
|
||||
|
||||
def test_strength_rep_scheme_is_rendered():
|
||||
out = render.workout(_wod([STRENGTH]))
|
||||
assert "Every 2:30 x 4 Sets" in out
|
||||
assert "Set 1: 10 Reps" in out
|
||||
|
||||
|
||||
def test_variable_rep_scheme_included_when_distinct():
|
||||
assert "(1 x 10) (1 x 8)" in render.workout(_wod([STRENGTH]))
|
||||
|
||||
|
||||
def test_variable_rep_scheme_not_duplicated():
|
||||
comp = dict(STRENGTH, WODComponentVariableRepScheme="Every 2:30 x 4 Sets")
|
||||
out = render.workout(_wod([comp]))
|
||||
assert out.count("Every 2:30 x 4 Sets") == 1
|
||||
|
||||
|
||||
def test_rounds_and_scoring_are_surfaced():
|
||||
out = render.workout(_wod([METCON]))
|
||||
assert "3 rounds" in out
|
||||
assert "Shorter is Better" in out
|
||||
|
||||
|
||||
def test_dash_only_comment_is_dropped():
|
||||
"""Authors use '--' as a spacer; it should not appear as content."""
|
||||
comp = {"Id": "9", "Name": "Press", "Comment": "<p>--</p>", "WODComponentOrder": 1}
|
||||
out = render.workout(_wod([comp]))
|
||||
assert "--" not in out
|
||||
|
||||
|
||||
def test_real_comment_is_kept():
|
||||
assert "RPE: 9/10" in render.workout(_wod([METCON]))
|
||||
|
||||
|
||||
def test_dash_spacer_stripped_but_surrounding_comment_kept():
|
||||
"""Live data has '--' as a leading spacer before real prose."""
|
||||
out = render.workout(_wod([STRENGTH]))
|
||||
assert "Strict overhead pressing progression." in out
|
||||
assert "--" not in out
|
||||
|
||||
|
||||
def test_components_sorted_by_wod_component_order():
|
||||
out = render.workout(_wod([METCON, SECTION, STRENGTH]))
|
||||
assert out.index("WARM-UP") < out.index("Shoulder Press") < out.index("Hat Trick")
|
||||
|
||||
|
||||
def test_section_and_component_heading_levels_differ():
|
||||
out = render.workout(_wod([SECTION, METCON]))
|
||||
assert "## WARM-UP" in out
|
||||
assert '### "Hat Trick"' in out
|
||||
|
||||
|
||||
def test_missing_order_does_not_crash():
|
||||
comp = {k: v for k, v in METCON.items() if k != "WODComponentOrder"}
|
||||
assert "21 Wall Balls" in render.workout(_wod([comp]))
|
||||
@@ -0,0 +1,68 @@
|
||||
"""Rendering exists to keep output small. Verify shaping, not exact prose."""
|
||||
from __future__ import annotations
|
||||
|
||||
from wodify import render
|
||||
|
||||
|
||||
def test_flatten_html_turns_breaks_into_lines():
|
||||
raw = "<p>For Time</p><p>30 Power Cleans<br>30 Toes-to-Bars</p>"
|
||||
out = render.flatten_html(raw)
|
||||
assert "For Time" in out
|
||||
assert "30 Power Cleans" in out
|
||||
assert "<" not in out
|
||||
|
||||
|
||||
def test_flatten_html_unescapes_entities():
|
||||
assert render.flatten_html("<p>135/95lb & 24"</p>") == '135/95lb & 24"'
|
||||
|
||||
|
||||
def test_flatten_html_handles_none_and_empty():
|
||||
assert render.flatten_html(None) == ""
|
||||
assert render.flatten_html("") == ""
|
||||
|
||||
|
||||
def test_flatten_html_collapses_runs_of_blank_lines():
|
||||
assert "\n\n\n" not in render.flatten_html("a<br><br><br><br>b")
|
||||
|
||||
|
||||
def test_find_all_reaches_nested_values():
|
||||
data = {"a": {"b": [{"Description": "x"}, {"c": {"Description": "y"}}]}}
|
||||
assert render.find_all(data, "Description") == ["x", "y"]
|
||||
|
||||
|
||||
def test_first_list_skips_empty_lists():
|
||||
data = {"p": {"List": []}, "q": {"List": [{"Id": 1}]}}
|
||||
assert render.first_list(data) == [{"Id": 1}]
|
||||
|
||||
|
||||
def test_bookings_reports_absence_rather_than_empty_string():
|
||||
assert "No bookings" in render.bookings({"Response": {"List": []}})
|
||||
|
||||
|
||||
def test_bookings_formats_rows():
|
||||
data = {"Response": {"List": [
|
||||
{"Class": {"StartDate": "2026-07-27", "StartTime": "5:30 PM",
|
||||
"ClassName": "CrossFit: 5:30 PM"},
|
||||
"StatusLabel": "Reserved"},
|
||||
]}}
|
||||
out = render.bookings(data)
|
||||
assert "2026-07-27" in out and "CrossFit: 5:30 PM" in out and "[Reserved]" in out
|
||||
|
||||
|
||||
def test_attendees_counts_and_lists():
|
||||
data = {"Response": {"List": [{"Name": "A B"}, {"Name": "C D"}]}}
|
||||
out = render.attendees(data)
|
||||
assert out.startswith("2 attendees:") and "A B" in out and "C D" in out
|
||||
|
||||
|
||||
def test_attendees_reports_absence():
|
||||
assert "No attendees" in render.attendees({"Response": {"List": []}})
|
||||
|
||||
|
||||
def test_workout_reports_absence():
|
||||
assert "No workout content" in render.workout({"Response": {}})
|
||||
|
||||
|
||||
def test_render_falls_back_to_json_for_unmapped_actions():
|
||||
out = render.render("classdetail", {"Response": {"Id": 1}})
|
||||
assert '"Id": 1' in out
|
||||
@@ -0,0 +1,75 @@
|
||||
"""Placeholder filtering is the subtle part: OutSystems returns a single zeroed
|
||||
record for an empty result set, which reads exactly like real data."""
|
||||
from __future__ import annotations
|
||||
|
||||
from wodify import render
|
||||
|
||||
|
||||
def _wod_response(components):
|
||||
return {"Classes": {"ProgramWODList": {"List": [
|
||||
{"Id": "9001", "Name": "CGE8 2009 Remix", "Notes": "",
|
||||
"WorkoutComponents": {"List": components}},
|
||||
]}}}
|
||||
|
||||
|
||||
EMPTY_PLACEHOLDER = {"Classes": {"ProgramWODList": {"List": [
|
||||
{"Id": "0", "Date": "1900-01-01", "Name": "", "Comments": "",
|
||||
"WorkoutComponents": {"List": []}},
|
||||
]}}}
|
||||
|
||||
|
||||
def test_placeholder_record_is_not_reported_as_content():
|
||||
out = render.workout(EMPTY_PLACEHOLDER)
|
||||
assert out.startswith("No workout content")
|
||||
|
||||
|
||||
def test_real_records_filters_zero_ids():
|
||||
rows = [{"Id": "0"}, {"Id": "12"}, {"Id": 0}, {"nope": 1}]
|
||||
assert render._real_records(rows) == [{"Id": "12"}]
|
||||
|
||||
|
||||
def test_workout_renders_title_and_components():
|
||||
data = _wod_response([
|
||||
{"Id": "1", "Name": "<p>Warm-Up</p>", "Comment": "<p>2:00 Cardio</p>"},
|
||||
{"Id": "2", "Name": "For Time", "Comment": "30 Power Cleans<br>30 Box Jumps"},
|
||||
])
|
||||
out = render.workout(data)
|
||||
assert "# CGE8 2009 Remix" in out
|
||||
assert "Warm-Up" in out and "2:00 Cardio" in out
|
||||
assert "30 Power Cleans" in out and "30 Box Jumps" in out
|
||||
assert "<" not in out
|
||||
|
||||
|
||||
def test_workout_skips_placeholder_components():
|
||||
data = _wod_response([{"Id": "0", "Name": "", "Comment": ""}])
|
||||
assert render.workout(data).startswith("# CGE8 2009 Remix")
|
||||
|
||||
|
||||
def test_workout_deduplicates_identical_blocks():
|
||||
data = _wod_response([
|
||||
{"Id": "1", "Name": "For Time", "Comment": "30 Burpees"},
|
||||
{"Id": "2", "Name": "For Time", "Comment": "30 Burpees"},
|
||||
])
|
||||
assert render.workout(data).count("30 Burpees") == 1
|
||||
|
||||
|
||||
def test_classes_reports_absence_for_placeholder_only():
|
||||
assert "No classes found" in render.classes(EMPTY_PLACEHOLDER)
|
||||
|
||||
|
||||
def test_classes_lists_rows_with_capacity():
|
||||
data = {"Schedules": {"ScheduleList": {"List": [
|
||||
{"Id": "5", "ClassName": "CrossFit: 6:00 AM", "StartTime": "6:00am",
|
||||
"ReservationCount": 5, "ClassLimit": 10},
|
||||
]}}}
|
||||
out = render.classes(data)
|
||||
assert "CrossFit: 6:00 AM" in out and "5 | 10" in out
|
||||
|
||||
|
||||
def test_classes_appends_wod_when_present():
|
||||
data = _wod_response([{"Id": "1", "Name": "For Time", "Comment": "30 Burpees"}])
|
||||
data["Schedules"] = {"ScheduleList": {"List": [
|
||||
{"Id": "5", "ClassName": "CrossFit: 6:00 AM", "StartTime": "6:00am"},
|
||||
]}}
|
||||
out = render.classes(data)
|
||||
assert "CrossFit: 6:00 AM" in out and "30 Burpees" in out
|
||||
@@ -0,0 +1,86 @@
|
||||
"""Schedule parsing.
|
||||
|
||||
Shape from a live capture 2026-07-25: Response.ResponseClassList.Class.List.
|
||||
Two bugs are pinned here because both produced plausible-looking wrong output
|
||||
rather than an error.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from wodify import render
|
||||
|
||||
# Abridged real row. GroupMemberReservationStatus.ClassId == "0" is the trap:
|
||||
# flattening nested dicts up clobbers the real Id and collapses every class
|
||||
# into a single row.
|
||||
def _row(cid, name, start, program, booked, coach):
|
||||
return {
|
||||
"Id": cid,
|
||||
"Name": name,
|
||||
"StartTime": start,
|
||||
"EndTime": "13:00:00",
|
||||
"StartDate": "2026-07-20",
|
||||
"ProgramId": program,
|
||||
"ClassLimit": 10,
|
||||
"ReservationCount": booked,
|
||||
"WaitlistCount": 0,
|
||||
"Status": "",
|
||||
"Coaches": {"List": [{"Name": coach, "Id": "5706147"}]},
|
||||
"GroupMemberReservationStatus": {"ClassId": "0", "IsSignedIn": {"List": []}},
|
||||
}
|
||||
|
||||
|
||||
DAY = {"Response": {"ResponseClassList": {"Class": {"List": [
|
||||
_row("190917816", "CrossFit: 5:30 PM", "17:30:00", "133059", 9, "Pat Doyle"),
|
||||
_row("190917671", "CrossFit: 12:00 PM", "12:00:00", "133059", 10, "Chris Nolan"),
|
||||
_row("190918133", "CrossFit Pump: 6:30 PM", "18:30:00", "131311", 7, "Pat Doyle"),
|
||||
]}}}}
|
||||
|
||||
|
||||
def test_all_classes_are_returned_not_collapsed():
|
||||
"""Regression: nested ClassId "0" previously collapsed all rows into one."""
|
||||
rows = render.class_rows(DAY)
|
||||
assert len(rows) == 3
|
||||
assert [r["class_id"] for r in rows] == ["190917671", "190917816", "190918133"]
|
||||
|
||||
|
||||
def test_rows_sorted_by_start_time():
|
||||
assert [r["start"] for r in render.class_rows(DAY)] == \
|
||||
["12:00:00", "17:30:00", "18:30:00"]
|
||||
|
||||
|
||||
def test_real_id_survives_nested_class_id_zero():
|
||||
row = render.class_rows(DAY)[1]
|
||||
assert row["class_id"] == "190917816"
|
||||
assert row["class_id"] != "0"
|
||||
|
||||
|
||||
def test_coach_extracted_from_nested_list():
|
||||
by_id = {r["class_id"]: r for r in render.class_rows(DAY)}
|
||||
assert by_id["190917671"]["coach"] == "Chris Nolan"
|
||||
assert by_id["190918133"]["coach"] == "Pat Doyle"
|
||||
|
||||
|
||||
def test_program_ids_distinguish_workouts():
|
||||
"""Classes in different programs have different WODs, so program_id must
|
||||
survive -- reporting one program's workout for another is a wrong answer."""
|
||||
programs = {r["program_id"] for r in render.class_rows(DAY)}
|
||||
assert programs == {"133059", "131311"}
|
||||
|
||||
|
||||
def test_missing_coach_list_does_not_crash():
|
||||
row = _row("1", "X", "06:00:00", "133059", 1, "Y")
|
||||
row["Coaches"] = {"List": []}
|
||||
assert render.class_rows({"Class": {"List": [row]}})[0]["coach"] == ""
|
||||
|
||||
|
||||
def test_placeholder_rows_dropped():
|
||||
day = {"Class": {"List": [_row("0", "", "00:00:00", "0", 0, "")]}}
|
||||
assert render.class_rows(day) == []
|
||||
|
||||
|
||||
def test_classes_render_includes_capacity_coach_and_id():
|
||||
out = render.classes(DAY)
|
||||
assert "CrossFit: 5:30 PM" in out
|
||||
assert "9 | 10" in out
|
||||
assert "coach=Pat Doyle" in out
|
||||
assert "class_id=190917816" in out
|
||||
assert out.count("\n- ") + 1 == 3, "all three classes should be listed"
|
||||
@@ -0,0 +1,100 @@
|
||||
"""Cache-through behaviour: the second read of the day must not hit the network."""
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
|
||||
from wodify import service, store
|
||||
|
||||
|
||||
@pytest.fixture()
|
||||
def conn(tmp_path, monkeypatch):
|
||||
monkeypatch.setenv("WODIFY_DB", str(tmp_path / "t.db"))
|
||||
c = store.connect()
|
||||
yield c
|
||||
c.close()
|
||||
|
||||
|
||||
SCHEDULE = {"Response": {"ResponseClassList": {"Class": {"List": [
|
||||
{"Id": "190917816", "Name": "CrossFit: 5:30 PM", "StartTime": "17:30:00",
|
||||
"EndTime": "18:30:00", "StartDate": "2026-07-20", "ProgramId": "133059",
|
||||
"ClassLimit": 10, "ReservationCount": 9, "WaitlistCount": 0,
|
||||
"Coaches": {"List": [{"Name": "Pat Doyle"}]}},
|
||||
]}}}}
|
||||
|
||||
|
||||
def test_first_call_hits_network_second_uses_cache(conn, monkeypatch):
|
||||
calls = []
|
||||
|
||||
def fake_call(key, overrides=None, **kw):
|
||||
calls.append(key)
|
||||
return SCHEDULE
|
||||
|
||||
monkeypatch.setattr(service.client, "call", fake_call)
|
||||
|
||||
rows, first = service.day_classes(conn, "2026-07-20")
|
||||
assert first.source == "network" and len(rows) == 1
|
||||
assert calls == ["schedule"]
|
||||
|
||||
rows2, second = service.day_classes(conn, "2026-07-20")
|
||||
assert second.source == "cache" and second.cached
|
||||
assert calls == ["schedule"], "second read must not touch the network"
|
||||
assert rows2 == rows
|
||||
|
||||
|
||||
def test_refresh_forces_a_network_read(conn, monkeypatch):
|
||||
calls = []
|
||||
monkeypatch.setattr(service.client, "call",
|
||||
lambda k, o=None, **kw: calls.append(k) or SCHEDULE)
|
||||
|
||||
service.day_classes(conn, "2026-07-20")
|
||||
service.day_classes(conn, "2026-07-20", refresh=True)
|
||||
assert len(calls) == 2
|
||||
|
||||
|
||||
def test_day_classes_indexes_ids_for_later_lookup(conn, monkeypatch):
|
||||
monkeypatch.setattr(service.client, "call", lambda k, o=None, **kw: SCHEDULE)
|
||||
service.day_classes(conn, "2026-07-20")
|
||||
klass = service.resolve_class(conn, "190917816")
|
||||
assert klass["date"] == "2026-07-20"
|
||||
assert klass["program_id"] == "133059"
|
||||
|
||||
|
||||
def test_cache_key_separates_dates(conn, monkeypatch):
|
||||
seen = []
|
||||
monkeypatch.setattr(service.client, "call",
|
||||
lambda k, o=None, **kw: seen.append(dict(o or {})) or SCHEDULE)
|
||||
service.day_classes(conn, "2026-07-20")
|
||||
service.day_classes(conn, "2026-07-21")
|
||||
assert [s["FromDate"] for s in seen] == ["2026-07-20", "2026-07-21"]
|
||||
|
||||
|
||||
def test_workout_cache_key_separates_programs(conn, monkeypatch):
|
||||
seen = []
|
||||
monkeypatch.setattr(service.client, "call",
|
||||
lambda k, o=None, **kw: seen.append(dict(o or {})) or {"x": 1})
|
||||
service.workout(conn, "2026-07-20", "133059")
|
||||
service.workout(conn, "2026-07-20", "131311")
|
||||
service.workout(conn, "2026-07-20", "133059") # cached
|
||||
assert [s.get("GymProgramId") for s in seen] == ["133059", "131311"]
|
||||
|
||||
|
||||
def test_attendees_raises_maxrecords_for_large_classes(conn, monkeypatch):
|
||||
seen = {}
|
||||
monkeypatch.setattr(service.client, "call",
|
||||
lambda k, o=None, **kw: seen.update(o or {}) or {"x": 1})
|
||||
service.attendees(conn, "190918189", 30)
|
||||
assert seen["MaxRecords"] == 30, "must not silently truncate a large class"
|
||||
|
||||
|
||||
def test_attendees_cached_per_class(conn, monkeypatch):
|
||||
calls = []
|
||||
monkeypatch.setattr(service.client, "call",
|
||||
lambda k, o=None, **kw: calls.append(o) or {"x": 1})
|
||||
service.attendees(conn, "1", 10)
|
||||
service.attendees(conn, "1", 10)
|
||||
service.attendees(conn, "2", 10)
|
||||
assert len(calls) == 2
|
||||
|
||||
|
||||
def test_resolve_unknown_class_returns_none(conn):
|
||||
assert service.resolve_class(conn, "999") is None
|
||||
@@ -0,0 +1,100 @@
|
||||
"""SQLite cache behaviour. No network."""
|
||||
from __future__ import annotations
|
||||
|
||||
import datetime as _dt
|
||||
|
||||
import pytest
|
||||
|
||||
from wodify import store
|
||||
|
||||
|
||||
@pytest.fixture()
|
||||
def conn(tmp_path, monkeypatch):
|
||||
monkeypatch.setenv("WODIFY_DB", str(tmp_path / "t.db"))
|
||||
c = store.connect()
|
||||
yield c
|
||||
c.close()
|
||||
|
||||
|
||||
def test_payload_round_trip(conn):
|
||||
store.put_payload(conn, "k", {"a": 1})
|
||||
hit = store.get_payload(conn, "k")
|
||||
assert hit is not None
|
||||
data, fetched_at = hit
|
||||
assert data == {"a": 1} and fetched_at
|
||||
|
||||
|
||||
def test_payload_miss_returns_none(conn):
|
||||
assert store.get_payload(conn, "absent") is None
|
||||
|
||||
|
||||
def test_payload_from_a_different_day_is_a_miss(conn):
|
||||
"""Freshness is per calendar day: yesterday's copy must not be served."""
|
||||
store.put_payload(conn, "k", {"a": 1})
|
||||
yesterday = (_dt.date.today() - _dt.timedelta(days=1)).isoformat()
|
||||
conn.execute("UPDATE payloads SET fetched_on = ?", (yesterday,))
|
||||
conn.commit()
|
||||
assert store.get_payload(conn, "k") is None
|
||||
|
||||
|
||||
def test_payload_overwrite_updates_in_place(conn):
|
||||
store.put_payload(conn, "k", {"v": 1})
|
||||
store.put_payload(conn, "k", {"v": 2})
|
||||
assert store.get_payload(conn, "k")[0] == {"v": 2}
|
||||
assert conn.execute("SELECT COUNT(*) FROM payloads").fetchone()[0] == 1
|
||||
|
||||
|
||||
ROWS = [
|
||||
{"class_id": "190917816", "name": "CrossFit: 5:30 PM", "start": "17:30:00",
|
||||
"end": "18:30:00", "program_id": "133059", "coach": "Pat Doyle",
|
||||
"booked": 9, "limit": 10, "waitlist": 0},
|
||||
{"class_id": "190918133", "name": "CrossFit Pump: 6:30 PM", "start": "18:30:00",
|
||||
"end": "19:30:00", "program_id": "131311", "coach": "Pat Doyle",
|
||||
"booked": 7, "limit": 10, "waitlist": 0},
|
||||
]
|
||||
|
||||
|
||||
def test_upsert_and_read_back_by_date(conn):
|
||||
assert store.upsert_classes(conn, "2026-07-20", ROWS) == 2
|
||||
rows = store.classes_for_date(conn, "2026-07-20")
|
||||
assert [r["class_id"] for r in rows] == ["190917816", "190918133"]
|
||||
assert rows[0]["class_limit"] == 10
|
||||
|
||||
|
||||
def test_get_class_resolves_date_and_program(conn):
|
||||
"""This is what lets `list workout <id>` work: the id alone carries neither."""
|
||||
store.upsert_classes(conn, "2026-07-20", ROWS)
|
||||
klass = store.get_class(conn, "190918133")
|
||||
assert klass["date"] == "2026-07-20"
|
||||
assert klass["program_id"] == "131311"
|
||||
|
||||
|
||||
def test_get_unknown_class_returns_none(conn):
|
||||
assert store.get_class(conn, "does-not-exist") is None
|
||||
|
||||
|
||||
def test_rows_without_class_id_are_skipped(conn):
|
||||
assert store.upsert_classes(conn, "2026-07-20", [{"name": "no id"}]) == 0
|
||||
|
||||
|
||||
def test_upsert_is_idempotent(conn):
|
||||
store.upsert_classes(conn, "2026-07-20", ROWS)
|
||||
store.upsert_classes(conn, "2026-07-20", ROWS)
|
||||
assert conn.execute("SELECT COUNT(*) FROM classes").fetchone()[0] == 2
|
||||
|
||||
|
||||
def test_classes_for_date_can_ignore_freshness(conn):
|
||||
"""Past days do not change, so a stale index is still useful for id lookup."""
|
||||
store.upsert_classes(conn, "2026-07-20", ROWS)
|
||||
conn.execute("UPDATE classes SET fetched_on = '2020-01-01'")
|
||||
conn.commit()
|
||||
assert store.classes_for_date(conn, "2026-07-20") == []
|
||||
assert len(store.classes_for_date(conn, "2026-07-20", fresh_only=False)) == 2
|
||||
|
||||
|
||||
def test_stats_reports_counts(conn):
|
||||
store.upsert_classes(conn, "2026-07-20", ROWS)
|
||||
store.put_payload(conn, "k", {})
|
||||
st = store.stats(conn)
|
||||
assert st["classes"] == 2 and st["days"] == 1
|
||||
assert st["payloads"] == 1 and st["payloads_fresh_today"] == 1
|
||||
@@ -0,0 +1,114 @@
|
||||
"""GetAllWorkoutData's real response shape, plus bookings range filtering.
|
||||
|
||||
Shape taken from a live capture on 2026-07-25: the workout lives at
|
||||
Response.ResponseWOD.ResponseWorkout, not in ProgramWODList.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from wodify import render
|
||||
|
||||
LIVE_SHAPE = {
|
||||
"Response": {
|
||||
"HasActiveMembership": True,
|
||||
"ErrorMessage": "",
|
||||
"ResponseWOD": {
|
||||
"WorkoutError": {"HasError": False, "ErrorMessage": ""},
|
||||
"ResponseWorkout": {
|
||||
"Id": "25201299",
|
||||
"Date": "2026-07-25",
|
||||
"Name": "CrossFit - Sat, Jul 25",
|
||||
"Notes": "<h2>Saturday July 25</h2><p>Daily Coach's Brief</p>",
|
||||
"WorkoutComponents": {"List": [
|
||||
{"Id": "123372298", "IsSection": True, "Name": "WARM-UP",
|
||||
"Comment": "<p>General Warm-Up</p><p>2 x</p><p>15 Banded Good Mornings</p>"},
|
||||
{"Id": "123372299", "IsSection": False,
|
||||
"Name": "091022 Games Mash-Up",
|
||||
"Comment": "<p>7 Rounds</p><p>3 Wall Walks</p>"},
|
||||
]},
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
UNPOSTED = {
|
||||
"Response": {
|
||||
"ErrorMessage": "",
|
||||
"ResponseWOD": {
|
||||
"WorkoutError": {"HasError": False, "ErrorMessage": ""},
|
||||
"ResponseWorkout": {"Id": "0", "Date": "1900-01-01", "Name": "",
|
||||
"Notes": "", "WorkoutComponents": {"List": []}},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
def test_live_shape_renders_title_and_components():
|
||||
out = render.workout(LIVE_SHAPE)
|
||||
assert out.startswith("# CrossFit - Sat, Jul 25")
|
||||
assert "## WARM-UP" in out, "IsSection components should be marked as sections"
|
||||
assert "15 Banded Good Mornings" in out
|
||||
assert "091022 Games Mash-Up" in out and "3 Wall Walks" in out
|
||||
assert "<" not in out
|
||||
|
||||
|
||||
def test_coach_brief_excluded_by_default():
|
||||
"""Notes runs to thousands of characters; keeping output small is the point."""
|
||||
assert "Daily Coach's Brief" not in render.workout(LIVE_SHAPE)
|
||||
|
||||
|
||||
def test_coach_brief_included_on_request():
|
||||
out = render.workout(LIVE_SHAPE, notes=True)
|
||||
assert "## Coach's brief" in out and "Daily Coach's Brief" in out
|
||||
|
||||
|
||||
def test_unposted_workout_is_reported_as_not_posted():
|
||||
out = render.workout(UNPOSTED)
|
||||
assert "not posted" in out.lower()
|
||||
assert "# " not in out
|
||||
|
||||
|
||||
# --- bookings range filtering -------------------------------------------------
|
||||
|
||||
BOOKINGS = {"Response": {"List": [
|
||||
{"Class": {"StartDate": "2026-07-20", "StartTime": "17:30:00",
|
||||
"ClassName": "CrossFit: 5:30 PM", "ClassId": "101"},
|
||||
"StatusLabel": "Attended"},
|
||||
{"Class": {"StartDate": "2026-07-22", "StartTime": "17:30:00",
|
||||
"ClassName": "CrossFit: 5:30 PM", "ClassId": "102"},
|
||||
"StatusLabel": "Attended"},
|
||||
{"Class": {"StartDate": "2026-07-27", "StartTime": "17:30:00",
|
||||
"ClassName": "CrossFit: 5:30 PM", "ClassId": "103"},
|
||||
"StatusLabel": "Reserved"},
|
||||
]}}
|
||||
|
||||
|
||||
def test_booking_rows_are_sorted_and_expose_class_id():
|
||||
rows = render.booking_rows(BOOKINGS)
|
||||
assert [r["date"] for r in rows] == ["2026-07-20", "2026-07-22", "2026-07-27"]
|
||||
assert rows[0]["class_id"] == "101"
|
||||
|
||||
|
||||
def test_bookings_since_filter():
|
||||
out = render.bookings(BOOKINGS, since="2026-07-22")
|
||||
assert "2026-07-20" not in out and "2026-07-22" in out and "2026-07-27" in out
|
||||
|
||||
|
||||
def test_bookings_until_filter():
|
||||
out = render.bookings(BOOKINGS, until="2026-07-22")
|
||||
assert "2026-07-27" not in out and "2026-07-20" in out
|
||||
|
||||
|
||||
def test_bookings_attended_only_excludes_future_reservations():
|
||||
out = render.bookings(BOOKINGS, attended_only=True)
|
||||
assert "2026-07-27" not in out
|
||||
assert "2026-07-20" in out and "2026-07-22" in out
|
||||
|
||||
|
||||
def test_bookings_exposes_class_id_for_chaining():
|
||||
"""Requirement: list attended classes, then fetch each one's workout."""
|
||||
assert "class_id=101" in render.bookings(BOOKINGS)
|
||||
|
||||
|
||||
def test_empty_filter_result_reports_pre_filter_count():
|
||||
out = render.bookings(BOOKINGS, since="2030-01-01")
|
||||
assert "No bookings found" in out and "3 returned before filtering" in out
|
||||
Reference in new issue
Block a user