askrobots / dbbasic-object-server
Public
Runs live, versioned Python application objects on one VM, with a suite of apps: projects, notes, tasks, files and more.
danq9
signup: the person chooses the password and name on the confirm page
83c7aa6
2 weeks, 5 days ago
History
test_wallet.py · 15.9 KB · 351 lines
| 1 | """Wallets: the ledger IS the balance, and the cap is the safety. |
| 2 | |
| 3 | Two claims under test. First, that a wallet's balance cannot drift from |
| 4 | its entries -- the predecessor's mutable balance column beside a |
| 5 | transaction table is the failure this design exists to prevent, and when |
| 6 | those two disagree the customer is right and you cannot prove otherwise. |
| 7 | Second, that auto top-up is bounded: autopay plus one runaway metering |
| 8 | bug is a four-figure surprise, and a monthly cap turns that into |
| 9 | something a human notices instead. |
| 10 | """ |
| 11 | |
| 12 | import json |
| 13 | import pathlib |
| 14 | |
| 15 | from conftest import stage_collection |
| 16 | |
| 17 | import object_execution |
| 18 | import object_records |
| 19 | import python_object_runtime |
| 20 | |
| 21 | REPO_ROOT = pathlib.Path(__file__).resolve().parents[1] |
| 22 | PACKAGES = REPO_ROOT / "packages" |
| 23 | BILLING_OBJECTS = PACKAGES / "app-billing" / "objects" |
| 24 | RUNTIME = python_object_runtime.PythonObjectRuntime() |
| 25 | |
| 26 | |
| 27 | def setup_env(tmp_path, monkeypatch, *, settings=()): |
| 28 | data_dir = tmp_path / "data" |
| 29 | for pkg, name in (("app-billing", "wallets"), ("app-billing", "wallet_entries"), |
| 30 | ("app-finance", "denominations"), ("app-settings", "app_settings")): |
| 31 | stage_collection(data_dir, pkg, name, |
| 32 | seed=(name == "denominations")) |
| 33 | rows = "" |
| 34 | for i, (k, v) in enumerate(settings): |
| 35 | rows += f"s{i}\t{k}\t{v}\t\n" |
| 36 | if rows: |
| 37 | stage_collection(data_dir, "app-settings", "app_settings", rows=rows) |
| 38 | monkeypatch.setenv("DBBASIC_DATA_DIR", str(data_dir)) |
| 39 | monkeypatch.delenv("DBBASIC_STRIPE_SECRET_KEY", raising=False) |
| 40 | monkeypatch.delenv("DBBASIC_STRIPE_WEBHOOK_SECRET", raising=False) |
| 41 | return data_dir |
| 42 | |
| 43 | |
| 44 | def make_wallet(data_dir, wid="w1", **fields): |
| 45 | record = {"id": wid, "owner_id": "dan", "is_active": "true"} |
| 46 | record.update(fields) |
| 47 | return object_records.create_collection_record("wallets", record, base_dir=data_dir) |
| 48 | |
| 49 | |
| 50 | def entry(data_dir, wid, amount, *, kind="topup", eid=None, generated_from="", |
| 51 | created_at=None): |
| 52 | record = {"id": eid or f"e-{abs(amount)}-{kind}-{object_records.new_record_id()}" |
| 53 | if hasattr(object_records, "new_record_id") else (eid or f"e{amount}{kind}"), |
| 54 | "wallet_id": wid, "amount_minor": str(amount), "kind": kind, |
| 55 | "generated_from": generated_from, "owner_id": "dan"} |
| 56 | if created_at: |
| 57 | record["created_at"] = created_at |
| 58 | return object_records.create_collection_record( |
| 59 | "wallet_entries", record, base_dir=data_dir) |
| 60 | |
| 61 | |
| 62 | def wallet(data_dir, wid="w1"): |
| 63 | return object_records.get_collection_record("wallets", wid, base_dir=data_dir) |
| 64 | |
| 65 | |
| 66 | def hook(record, action="create"): |
| 67 | return object_execution.execute_object( |
| 68 | RUNTIME, |
| 69 | object_execution.ObjectExecutionRequest( |
| 70 | "hook_wallet_entries", method="BEFORE_WRITE", |
| 71 | payload={"action": action, "collection": "wallet_entries", "record": record}), |
| 72 | roots=[BILLING_OBJECTS]).result |
| 73 | |
| 74 | |
| 75 | def replenish(payload=None): |
| 76 | return object_execution.execute_object( |
| 77 | RUNTIME, |
| 78 | object_execution.ObjectExecutionRequest( |
| 79 | "system_wallet_replenish", method="POST", payload=payload or {}), |
| 80 | roots=[BILLING_OBJECTS]).result |
| 81 | |
| 82 | |
| 83 | # --- the ledger is the balance ------------------------------------------------ |
| 84 | |
| 85 | def test_balance_is_the_sum_of_entries_and_nothing_writes_it(tmp_path, monkeypatch): |
| 86 | data_dir = setup_env(tmp_path, monkeypatch) |
| 87 | make_wallet(data_dir) |
| 88 | entry(data_dir, "w1", 5000, kind="topup", eid="e1") |
| 89 | assert wallet(data_dir)["balance_minor"] == "5000" |
| 90 | entry(data_dir, "w1", -1250, kind="debit", eid="e2") |
| 91 | assert wallet(data_dir)["balance_minor"] == "3750" |
| 92 | entry(data_dir, "w1", 1250, kind="refund", eid="e3") |
| 93 | assert wallet(data_dir)["balance_minor"] == "5000" |
| 94 | |
| 95 | |
| 96 | def test_the_balance_field_cannot_be_written_by_anyone(tmp_path, monkeypatch): |
| 97 | """The predecessor's drift bug is impossible here by construction: the |
| 98 | field is computed, and the write path refuses it.""" |
| 99 | data_dir = setup_env(tmp_path, monkeypatch) |
| 100 | make_wallet(data_dir) |
| 101 | entry(data_dir, "w1", 1000, eid="e1") |
| 102 | try: |
| 103 | object_records.update_collection_record( |
| 104 | "wallets", "w1", {"balance_minor": "999999"}, base_dir=data_dir) |
| 105 | raise AssertionError("a computed balance must not be writable") |
| 106 | except object_records.InvalidRecordPayloadError as exc: |
| 107 | assert "computed" in str(exc) or "read-only" in str(exc) |
| 108 | assert wallet(data_dir)["balance_minor"] == "1000" |
| 109 | |
| 110 | |
| 111 | # --- the debit gate ------------------------------------------------------------- |
| 112 | |
| 113 | def test_a_debit_beyond_the_balance_is_refused_with_402(tmp_path, monkeypatch): |
| 114 | data_dir = setup_env(tmp_path, monkeypatch) |
| 115 | make_wallet(data_dir) |
| 116 | entry(data_dir, "w1", 1000, eid="e1") |
| 117 | ok = hook({"wallet_id": "w1", "amount_minor": "-1000", "kind": "debit"}) |
| 118 | assert ok is None # exactly to zero is allowed |
| 119 | over = hook({"wallet_id": "w1", "amount_minor": "-1001", "kind": "debit"}) |
| 120 | assert over["status"] == 402 # Payment Required, the honest code |
| 121 | assert "Insufficient wallet balance" in over["error"] |
| 122 | |
| 123 | |
| 124 | def test_credits_are_never_gated(tmp_path, monkeypatch): |
| 125 | data_dir = setup_env(tmp_path, monkeypatch) |
| 126 | make_wallet(data_dir) |
| 127 | assert hook({"wallet_id": "w1", "amount_minor": "5000", "kind": "topup"}) is None |
| 128 | |
| 129 | |
| 130 | def test_an_overdraft_floor_can_be_allowed_deliberately(tmp_path, monkeypatch): |
| 131 | """A high-frequency workload may prefer a few cents of race over |
| 132 | failing a customer's request mid-flight -- but it must be a decision.""" |
| 133 | data_dir = setup_env(tmp_path, monkeypatch, |
| 134 | settings=(("billing.wallet.overdraft_minor", "500"),)) |
| 135 | make_wallet(data_dir) |
| 136 | entry(data_dir, "w1", 100, eid="e1") |
| 137 | assert hook({"wallet_id": "w1", "amount_minor": "-600", "kind": "debit"}) is None |
| 138 | assert hook({"wallet_id": "w1", "amount_minor": "-601", |
| 139 | "kind": "debit"})["status"] == 402 |
| 140 | |
| 141 | |
| 142 | def test_a_zero_entry_is_refused(tmp_path, monkeypatch): |
| 143 | setup_env(tmp_path, monkeypatch) |
| 144 | assert hook({"wallet_id": "w1", "amount_minor": "0", "kind": "debit"})["status"] == 400 |
| 145 | |
| 146 | |
| 147 | # --- auto top-up, and the cap that bounds it ------------------------------------ |
| 148 | |
| 149 | def test_the_monthly_cap_stops_a_runaway(tmp_path, monkeypatch): |
| 150 | """The scenario: metering goes wrong and drains the wallet repeatedly. |
| 151 | Without a cap, autopay follows it down forever.""" |
| 152 | data_dir = setup_env(tmp_path, monkeypatch) |
| 153 | make_wallet(data_dir, auto_replenish_enabled="true", |
| 154 | auto_replenish_threshold_minor="1000", |
| 155 | auto_replenish_amount_minor="2000", |
| 156 | auto_replenish_monthly_cap_minor="3000", |
| 157 | stripe_customer_id="cus_1", payment_method_ref="pm_1") |
| 158 | # The real runaway shape: an auto top-up already happened this month, |
| 159 | # then metering drained the wallet back below the threshold. Without a |
| 160 | # cap the pass would top up again, and again, following the bug down. |
| 161 | # The test's calendar is DERIVED from the wall clock, because it has |
| 162 | # no choice: the cap fold counts seeded entries by their created_at |
| 163 | # month, and created_at is computed at write time -- deliberately |
| 164 | # unwritable by any caller, this test included. Hardcoding |
| 165 | # "2026-07-25" here held only during July 2026: at the first month |
| 166 | # rollover the seed landed in August, the July fold saw nothing, and |
| 167 | # the "cap reached" path silently became the "already attempted" |
| 168 | # skip. A test about a calendar window must run in the month its |
| 169 | # records actually carry. |
| 170 | from datetime import datetime, timezone |
| 171 | # UTC, not local: created_at is stamped in UTC, and for a few hours |
| 172 | # around every month boundary the two disagree about what month it |
| 173 | # is -- which is precisely when this test first failed. |
| 174 | period = datetime.now(timezone.utc).strftime("%Y-%m") |
| 175 | entry(data_dir, "w1", 2000, kind="auto_topup", eid="e1", |
| 176 | generated_from=f"auto_topup/w1/{period}/2000") |
| 177 | entry(data_dir, "w1", -1800, kind="debit", eid="e2") # balance now 200 |
| 178 | |
| 179 | result = replenish({"today": f"{period}-25"}) |
| 180 | capped = [r for r in result["results"] if r.get("skipped") == "monthly cap reached"] |
| 181 | assert capped, result |
| 182 | assert capped[0]["capped_at_minor"] == 3000 |
| 183 | assert capped[0]["already_this_month_minor"] == 2000 |
| 184 | assert result["charged"] == 0 |
| 185 | |
| 186 | |
| 187 | def test_a_zero_cap_means_auto_topup_is_off(tmp_path, monkeypatch): |
| 188 | """A blank number must never read as 'unlimited' -- the safe default.""" |
| 189 | data_dir = setup_env(tmp_path, monkeypatch) |
| 190 | make_wallet(data_dir, auto_replenish_enabled="true", |
| 191 | auto_replenish_threshold_minor="1000", |
| 192 | auto_replenish_amount_minor="2000", |
| 193 | stripe_customer_id="cus_1", payment_method_ref="pm_1") |
| 194 | entry(data_dir, "w1", 0 + 500, eid="e1") |
| 195 | result = replenish({"today": "2026-07-25"}) |
| 196 | assert result["charged"] == 0 |
| 197 | assert any("cap is zero" in str(r.get("skipped", "")) for r in result["results"]) |
| 198 | |
| 199 | |
| 200 | def test_a_healthy_balance_is_left_alone(tmp_path, monkeypatch): |
| 201 | data_dir = setup_env(tmp_path, monkeypatch) |
| 202 | make_wallet(data_dir, auto_replenish_enabled="true", |
| 203 | auto_replenish_threshold_minor="1000", |
| 204 | auto_replenish_amount_minor="2000", |
| 205 | auto_replenish_monthly_cap_minor="10000", |
| 206 | stripe_customer_id="cus_1", payment_method_ref="pm_1") |
| 207 | entry(data_dir, "w1", 5000, eid="e1") |
| 208 | result = replenish({"today": "2026-07-25"}) |
| 209 | assert result["charged"] == 0 and result["results"] == [] |
| 210 | |
| 211 | |
| 212 | def test_without_stripe_it_reports_what_it_would_charge(tmp_path, monkeypatch): |
| 213 | """The rule can be tuned before any money moves.""" |
| 214 | data_dir = setup_env(tmp_path, monkeypatch) |
| 215 | make_wallet(data_dir, auto_replenish_enabled="true", |
| 216 | auto_replenish_threshold_minor="1000", |
| 217 | auto_replenish_amount_minor="2000", |
| 218 | auto_replenish_monthly_cap_minor="10000") |
| 219 | entry(data_dir, "w1", 100, eid="e1") |
| 220 | result = replenish({"today": "2026-07-25"}) |
| 221 | assert result["charged"] == 0 |
| 222 | would = [r for r in result["results"] if r.get("would_charge_minor")] |
| 223 | assert would and would[0]["would_charge_minor"] == 2000 |
| 224 | assert "not configured" in would[0]["reason"] |
| 225 | |
| 226 | |
| 227 | def test_a_wallet_without_a_saved_card_is_skipped_not_failed(tmp_path, monkeypatch): |
| 228 | data_dir = setup_env(tmp_path, monkeypatch) |
| 229 | monkeypatch.setenv("DBBASIC_STRIPE_SECRET_KEY", "sk_test") |
| 230 | monkeypatch.setenv("DBBASIC_STRIPE_WEBHOOK_SECRET", "whsec_test") |
| 231 | make_wallet(data_dir, auto_replenish_enabled="true", |
| 232 | auto_replenish_threshold_minor="1000", |
| 233 | auto_replenish_amount_minor="2000", |
| 234 | auto_replenish_monthly_cap_minor="10000") |
| 235 | entry(data_dir, "w1", 100, eid="e1") |
| 236 | result = replenish({"today": "2026-07-25"}) |
| 237 | assert result["failed"] == 0 |
| 238 | assert any("no saved card" in str(r.get("skipped", "")) for r in result["results"]) |
| 239 | |
| 240 | |
| 241 | def test_billing_not_installed_is_a_graceful_skip(tmp_path, monkeypatch): |
| 242 | data_dir = tmp_path / "data" |
| 243 | data_dir.mkdir() |
| 244 | monkeypatch.setenv("DBBASIC_DATA_DIR", str(data_dir)) |
| 245 | assert replenish()["skipped"].startswith("billing not installed") |
| 246 | |
| 247 | |
| 248 | # --- rule 2: a provenance marker is used once --------------------------------- |
| 249 | # |
| 250 | # Doctrine #7 says a replayed event posts nothing twice, and every money |
| 251 | # writer here already honours it -- by READING the ledger, looking for its |
| 252 | # marker, then writing. That is check-then-write, and it is only as good |
| 253 | # as the absence of a second writer in between. system_wallet_replenish |
| 254 | # runs on a daily schedule AND by hand; the Stripe charge is safe because |
| 255 | # that pass sends its marker as Stripe's idempotency_key, but the wallet |
| 256 | # credit that follows had nothing protecting it, so the customer could be |
| 257 | # credited twice for one card charge and the shop ate the difference. |
| 258 | |
| 259 | def test_a_marker_cannot_be_posted_to_the_ledger_twice(tmp_path, monkeypatch): |
| 260 | data_dir = setup_env(tmp_path, monkeypatch) |
| 261 | make_wallet(data_dir) |
| 262 | entry(data_dir, "w1", 500, kind="auto_topup", |
| 263 | generated_from="auto_topup/w1/2026-07/500") |
| 264 | |
| 265 | refused = hook({"wallet_id": "w1", "amount_minor": "500", |
| 266 | "kind": "auto_topup", |
| 267 | "generated_from": "auto_topup/w1/2026-07/500"}) |
| 268 | assert refused["status"] == 409 |
| 269 | assert "already been posted" in refused["error"] |
| 270 | assert "auto_topup/w1/2026-07/500" in refused["error"] |
| 271 | |
| 272 | |
| 273 | def test_the_duplicate_check_covers_credits_which_is_the_case_it_exists_for(tmp_path, monkeypatch): |
| 274 | data_dir = setup_env(tmp_path, monkeypatch) |
| 275 | """A duplicated credit is money leaving the business exactly as a |
| 276 | duplicated debit is money leaving a customer, so the marker check runs |
| 277 | BEFORE the 'money arriving is never gated' shortcut.""" |
| 278 | make_wallet(data_dir) |
| 279 | entry(data_dir, "w1", 2000, kind="topup", generated_from="checkout/o-1") |
| 280 | |
| 281 | # A credit -- the path that used to return before reading anything. |
| 282 | refused = hook({"wallet_id": "w1", "amount_minor": "2000", |
| 283 | "kind": "topup", "generated_from": "checkout/o-1"}) |
| 284 | assert refused["status"] == 409 |
| 285 | |
| 286 | |
| 287 | def test_a_blank_marker_is_never_a_collision(tmp_path, monkeypatch): |
| 288 | data_dir = setup_env(tmp_path, monkeypatch) |
| 289 | """Most entries carry none: a manual top-up, an adjustment, an |
| 290 | ordinary debit. Uniqueness is a property of the markers that exist, |
| 291 | not a requirement that every entry have one -- the same view |
| 292 | hook_wallets takes of a blank gift-card code.""" |
| 293 | make_wallet(data_dir) |
| 294 | for n in range(3): |
| 295 | entry(data_dir, "w1", 100, kind="topup", generated_from="", |
| 296 | eid=f"blank-{n}") |
| 297 | assert hook({"wallet_id": "w1", "amount_minor": "100", |
| 298 | "kind": "topup", "generated_from": ""}) is None |
| 299 | assert hook({"wallet_id": "w1", "amount_minor": "100", |
| 300 | "kind": "topup"}) is None |
| 301 | |
| 302 | |
| 303 | def test_a_different_marker_from_the_same_source_still_posts(tmp_path, monkeypatch): |
| 304 | data_dir = setup_env(tmp_path, monkeypatch) |
| 305 | """The template runner writes release and charge as two legs of one |
| 306 | settlement, with distinct markers. Refusing the second because it |
| 307 | shares a prefix would break every multi-leg settlement on the box.""" |
| 308 | make_wallet(data_dir) |
| 309 | entry(data_dir, "w1", 5000, kind="topup") |
| 310 | entry(data_dir, "w1", 50, kind="release", |
| 311 | generated_from="template_run/r1/release") |
| 312 | assert hook({"wallet_id": "w1", "amount_minor": "-50", "kind": "debit", |
| 313 | "generated_from": "template_run/r1/charge"}) is None |
| 314 | |
| 315 | |
| 316 | def test_an_unreadable_ledger_now_refuses_credits_too(tmp_path, monkeypatch): |
| 317 | data_dir = setup_env(tmp_path, monkeypatch) |
| 318 | """It already failed closed for debits (unknown balance). It must fail |
| 319 | closed for credits as well now, because an unreadable ledger also |
| 320 | means unknown markers, and posting into that is how a duplicate |
| 321 | becomes permanent.""" |
| 322 | monkeypatch.setenv("DBBASIC_DATA_DIR", str(data_dir / "gone")) |
| 323 | refused = hook({"wallet_id": "w1", "amount_minor": "500", |
| 324 | "kind": "topup", "generated_from": "auto_topup/w1/x"}) |
| 325 | assert refused["status"] == 409 |
| 326 | assert "unreadable" in refused["error"] |
| 327 | |
| 328 | |
| 329 | def test_two_overlapping_topups_credit_the_wallet_once(tmp_path, monkeypatch): |
| 330 | data_dir = setup_env(tmp_path, monkeypatch) |
| 331 | """The reproduction. Both passes find no marker and both try to |
| 332 | credit; the ledger accepts one. Before this rule the wallet ended up |
| 333 | with 1000 against a single 500 charge at the card.""" |
| 334 | make_wallet(data_dir) |
| 335 | marker = "auto_topup/w1/2026-07/500" |
| 336 | credit = {"wallet_id": "w1", "amount_minor": "500", "kind": "auto_topup", |
| 337 | "generated_from": marker, "owner_id": "dan"} |
| 338 | |
| 339 | landed = 0 |
| 340 | for _ in range(2): |
| 341 | if hook(dict(credit)) is None: |
| 342 | object_records.create_collection_record( |
| 343 | "wallet_entries", dict(credit), base_dir=data_dir) |
| 344 | landed += 1 |
| 345 | |
| 346 | assert landed == 1 |
| 347 | total = sum(int(r["amount_minor"]) for r in |
| 348 | object_records.read_collection_records("wallet_entries", |
| 349 | base_dir=data_dir) |
| 350 | if r["wallet_id"] == "w1") |
| 351 | assert total == 500 |