|
| 1 | +"""The cases of event-sourced-ledger-typescript expect balances and versions that the store's |
| 2 | +history adds up to: the events the baseline migration seeds, and the hidden ones `grade_setup` |
| 3 | +appends. These tests fold that history the way the statement defines a balance, check that each |
| 4 | +case reading an account it did not change expects what the events say, and check that the history |
| 5 | +is one a ledger could have written.""" |
| 6 | + |
| 7 | +import json |
| 8 | +import re |
| 9 | +from collections.abc import Mapping |
| 10 | +from datetime import datetime |
| 11 | +from itertools import accumulate |
| 12 | +from typing import Any |
| 13 | + |
| 14 | +import pytest |
| 15 | + |
| 16 | +from tests.helpers import REPOSITORY_ROOT |
| 17 | + |
| 18 | +PROBLEM = REPOSITORY_ROOT / "problems" / "0287-event-sourced-ledger-typescript" |
| 19 | +STARTER_BASELINE = PROBLEM / "starter" / "migrations" / "0001_baseline.sql" |
| 20 | +GRADING_BASELINE = PROBLEM / "grading" / "baseline" / "0001_baseline.sql" |
| 21 | +SEED_ROW_START = " (" |
| 22 | +SEED_ROW = re.compile( |
| 23 | + r"^ {4}\('([^']+)', (\d+), '([^']+)', '([a-z_]+)', '(\{[^']*\})', '([^']+)'\)" |
| 24 | +) |
| 25 | +CREDITS = {"deposited", "transferred_in"} |
| 26 | +HIDDEN_PREFIX = "x-" |
| 27 | +ACCOUNT_PATH = re.compile(r"^/accounts/([^/]+)$") |
| 28 | +EVENTS_PATH = re.compile(r"^/accounts/([^/]+)/events$") |
| 29 | + |
| 30 | +type Event = Mapping[str, Any] |
| 31 | +type Case = Mapping[str, Any] |
| 32 | + |
| 33 | + |
| 34 | +def seed_rows() -> list[str]: |
| 35 | + lines = STARTER_BASELINE.read_text(encoding="utf-8").splitlines() |
| 36 | + return [line for line in lines if line.startswith(SEED_ROW_START)] |
| 37 | + |
| 38 | + |
| 39 | +def seed_events() -> list[Event]: |
| 40 | + events: list[Event] = [] |
| 41 | + for row in seed_rows(): |
| 42 | + found = SEED_ROW.match(row) |
| 43 | + if found is None: |
| 44 | + continue |
| 45 | + stream_id, version, event_id, kind, data, recorded_at = found.groups() |
| 46 | + events.append( |
| 47 | + { |
| 48 | + "stream_id": stream_id, |
| 49 | + "version": int(version), |
| 50 | + "event_id": event_id, |
| 51 | + "type": kind, |
| 52 | + "data": json.loads(data), |
| 53 | + "recorded_at": recorded_at, |
| 54 | + } |
| 55 | + ) |
| 56 | + return events |
| 57 | + |
| 58 | + |
| 59 | +SEED = seed_events() |
| 60 | +HIDDEN: list[Event] = json.loads( |
| 61 | + (PROBLEM / "grading" / "hidden_events.json").read_text(encoding="utf-8") |
| 62 | +) |
| 63 | +HISTORY = SEED + HIDDEN |
| 64 | +CASES: list[Case] = json.loads((PROBLEM / "tests.json").read_text(encoding="utf-8"))["cases"] |
| 65 | +STREAMS = sorted({event["stream_id"] for event in HISTORY}) |
| 66 | + |
| 67 | + |
| 68 | +def moment(text: str) -> datetime: |
| 69 | + return datetime.fromisoformat(text) |
| 70 | + |
| 71 | + |
| 72 | +def stream(account: str) -> list[Event]: |
| 73 | + events = [event for event in HISTORY if event["stream_id"] == account] |
| 74 | + return sorted(events, key=lambda event: event["version"]) |
| 75 | + |
| 76 | + |
| 77 | +def signed_amount(event: Event) -> int: |
| 78 | + amount: int = event["data"]["amount"] |
| 79 | + return amount if event["type"] in CREDITS else -amount |
| 80 | + |
| 81 | + |
| 82 | +def account_as_of(account: str, as_of: str | None) -> dict[str, Any] | None: |
| 83 | + """The account as the statement defines it, after its events recorded by `as_of`, or None |
| 84 | + before its first event.""" |
| 85 | + events = [ |
| 86 | + event |
| 87 | + for event in stream(account) |
| 88 | + if as_of is None or moment(event["recorded_at"]) <= moment(as_of) |
| 89 | + ] |
| 90 | + if not events: |
| 91 | + return None |
| 92 | + balance = sum(signed_amount(event) for event in events) |
| 93 | + return {"account": account, "balance": balance, "version": len(events)} |
| 94 | + |
| 95 | + |
| 96 | +def stored_events(account: str) -> list[dict[str, Any]]: |
| 97 | + return [ |
| 98 | + {"version": event["version"], "type": event["type"], "data": event["data"]} |
| 99 | + for event in stream(account) |
| 100 | + ] |
| 101 | + |
| 102 | + |
| 103 | +def reads_only(case: Case) -> bool: |
| 104 | + return "request" in case and "before" not in case and case["request"]["method"] == "GET" |
| 105 | + |
| 106 | + |
| 107 | +def untouched_reads(path: re.Pattern[str], status: int) -> list[Any]: |
| 108 | + """Each case that only reads a path of this shape, with nothing sent before it, and expects |
| 109 | + `status`, as a `pytest.param` of its account, its query and its expected body.""" |
| 110 | + return [ |
| 111 | + pytest.param( |
| 112 | + found.group(1), |
| 113 | + case["request"].get("query", {}), |
| 114 | + case["expected"].get("body"), |
| 115 | + id=case["id"], |
| 116 | + ) |
| 117 | + for case in CASES |
| 118 | + if reads_only(case) |
| 119 | + and case["expected"]["status"] == status |
| 120 | + and (found := path.match(case["request"]["path"])) is not None |
| 121 | + ] |
| 122 | + |
| 123 | + |
| 124 | +def legs(kind: str) -> list[Event]: |
| 125 | + return [event for event in HISTORY if event["type"] == kind] |
| 126 | + |
| 127 | + |
| 128 | +def arrives_for(departure: Event, arrival: Event) -> bool: |
| 129 | + sent = {"amount": departure["data"]["amount"], "from": departure["stream_id"]} |
| 130 | + return ( |
| 131 | + arrival["event_id"] == departure["event_id"] |
| 132 | + and arrival["stream_id"] == departure["data"]["to"] |
| 133 | + and arrival["data"] == sent |
| 134 | + and arrival["recorded_at"] == departure["recorded_at"] |
| 135 | + ) |
| 136 | + |
| 137 | + |
| 138 | +def test_the_grading_baseline_is_the_starters(): |
| 139 | + assert GRADING_BASELINE.read_bytes() == STARTER_BASELINE.read_bytes() |
| 140 | + |
| 141 | + |
| 142 | +def test_every_seeded_row_is_read(): |
| 143 | + assert len(SEED) == len(seed_rows()) |
| 144 | + |
| 145 | + |
| 146 | +def test_hidden_events_hold_only_reserved_accounts(): |
| 147 | + assert all(event["stream_id"].startswith(HIDDEN_PREFIX) for event in HIDDEN) |
| 148 | + |
| 149 | + |
| 150 | +def test_seeded_events_hold_no_reserved_account(): |
| 151 | + assert not any(event["stream_id"].startswith(HIDDEN_PREFIX) for event in SEED) |
| 152 | + |
| 153 | + |
| 154 | +@pytest.mark.parametrize("account", STREAMS) |
| 155 | +def test_a_stream_is_numbered_from_1_with_no_gap(account: str): |
| 156 | + versions = [event["version"] for event in stream(account)] |
| 157 | + assert versions == list(range(1, len(versions) + 1)) |
| 158 | + |
| 159 | + |
| 160 | +@pytest.mark.parametrize("account", STREAMS) |
| 161 | +def test_a_stream_is_recorded_in_order(account: str): |
| 162 | + times = [moment(event["recorded_at"]) for event in stream(account)] |
| 163 | + assert times == sorted(times) |
| 164 | + |
| 165 | + |
| 166 | +@pytest.mark.parametrize("account", STREAMS) |
| 167 | +def test_a_stream_never_goes_below_zero(account: str): |
| 168 | + balances = accumulate(signed_amount(event) for event in stream(account)) |
| 169 | + assert min(balances) >= 0 |
| 170 | + |
| 171 | + |
| 172 | +@pytest.mark.parametrize("account", STREAMS) |
| 173 | +def test_an_event_id_is_used_once_in_a_stream(account: str): |
| 174 | + ids = [event["event_id"] for event in stream(account)] |
| 175 | + assert len(ids) == len(set(ids)) |
| 176 | + |
| 177 | + |
| 178 | +@pytest.mark.parametrize( |
| 179 | + "departure", |
| 180 | + [pytest.param(event, id=event["event_id"]) for event in legs("transferred_out")], |
| 181 | +) |
| 182 | +def test_a_transfer_arrives_where_it_was_sent(departure: Event): |
| 183 | + assert any(arrives_for(departure, arrival) for arrival in legs("transferred_in")) |
| 184 | + |
| 185 | + |
| 186 | +def test_every_arrival_has_a_departure(): |
| 187 | + assert len(legs("transferred_in")) == len(legs("transferred_out")) |
| 188 | + |
| 189 | + |
| 190 | +def test_some_cases_read_the_history_untouched(): |
| 191 | + assert untouched_reads(ACCOUNT_PATH, 200) |
| 192 | + |
| 193 | + |
| 194 | +@pytest.mark.parametrize(("account", "query", "body"), untouched_reads(ACCOUNT_PATH, 200)) |
| 195 | +def test_a_read_account_is_what_its_events_add_up_to( |
| 196 | + account: str, query: Mapping[str, str], body: Any |
| 197 | +): |
| 198 | + assert body == account_as_of(account, query.get("as_of")) |
| 199 | + |
| 200 | + |
| 201 | +@pytest.mark.parametrize(("account", "query", "body"), untouched_reads(ACCOUNT_PATH, 404)) |
| 202 | +def test_an_unknown_account_has_no_events_by_then( |
| 203 | + account: str, query: Mapping[str, str], body: Any |
| 204 | +): |
| 205 | + assert account_as_of(account, query.get("as_of")) is None |
| 206 | + |
| 207 | + |
| 208 | +@pytest.mark.parametrize(("account", "query", "body"), untouched_reads(EVENTS_PATH, 200)) |
| 209 | +def test_a_read_stream_is_the_stored_events(account: str, query: Mapping[str, str], body: Any): |
| 210 | + assert body == stored_events(account) |
0 commit comments