"""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, "Sign into Wodify") 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())