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.
test_findings_handlers.py · 79.3 KB · 1703 lines
| 1 | """FINDINGS: system handlers and scheduled runners, reproduced. |
| 2 | |
| 3 | Every test here verifies one suspected bug from the read-only inventory in |
| 4 | config-inventory/handlers.md (section 3.5). Nothing is fixed by this file; |
| 5 | it only says, in a form that can be run, which of those suspicions are real. |
| 6 | |
| 7 | How to read it: |
| 8 | |
| 9 | * A test asserts the CORRECT behaviour -- the stamped total survives, the |
| 10 | status follows the money, the schedule advances by its own period. |
| 11 | * Where the bug is real the test is ``xfail(strict=True)``: the suite stays |
| 12 | green today and goes red the day somebody fixes it, which is the prompt to |
| 13 | delete the marker. |
| 14 | * Where the suspicion was wrong (or is a platform FACT rather than a bug) |
| 15 | the test is an ordinary passing one and its docstring says what was |
| 16 | refuted and what prevents it. |
| 17 | |
| 18 | Two rules keep a strict xfail from lying: |
| 19 | |
| 20 | 1. The assertion that states the finding raises ``FindingReproduced``, and |
| 21 | every xfail marker says ``raises=FindingReproduced``. Setup and |
| 22 | precondition checks are plain ``assert``. So a test that breaks for an |
| 23 | unrelated reason -- a package that did not install, a refused write, a |
| 24 | handler that returned early on a malformed payload -- FAILS instead of |
| 25 | hiding inside the xfail. |
| 26 | 2. Handlers are driven the way the server drives them. The dispatcher puts |
| 27 | the RAW verb in ``request["action"]`` ("create"/"update"/"delete") and |
| 28 | the participle only in ``request["event"]``, so nothing here hand-builds |
| 29 | a payload where the real dispatcher can build it: writes go through the |
| 30 | ASGI app with DBBASIC_ENABLE_EVENT_HANDLERS on, or -- for storage-level |
| 31 | writers such as action_checkout -- through the change-log replay pass |
| 32 | (DBBASIC_ENABLE_CHANGE_DISPATCH), which is the documented production |
| 33 | route for those writes. |
| 34 | |
| 35 | Nothing here opens a socket: Stripe events are signed locally and handed to |
| 36 | the webhook object, and "a collection could not be read" is a monkeypatched |
| 37 | OSError on object_records.read_collection_records. |
| 38 | """ |
| 39 | |
| 40 | import ast |
| 41 | import asyncio |
| 42 | import contextlib |
| 43 | import hashlib |
| 44 | import hmac |
| 45 | import json |
| 46 | import socket |
| 47 | import time |
| 48 | import urllib.request |
| 49 | from pathlib import Path |
| 50 | |
| 51 | import pytest |
| 52 | |
| 53 | import object_cart |
| 54 | import object_change_dispatch |
| 55 | import object_computed |
| 56 | import object_daemon |
| 57 | import object_daemon_status |
| 58 | import object_execution |
| 59 | import object_handlers |
| 60 | import object_lines |
| 61 | import object_packages |
| 62 | import object_records |
| 63 | import object_server |
| 64 | import object_stripe |
| 65 | import python_object_runtime |
| 66 | |
| 67 | REPO_ROOT = Path(__file__).resolve().parents[1] |
| 68 | PACKAGES_ROOT = REPO_ROOT / "packages" |
| 69 | ADMIN_TOKEN = "findings-handlers-admin-token" |
| 70 | |
| 71 | SHOP_PACKAGES = ("app-settings", "app-catalog", "app-orders", "app-invoices", |
| 72 | "app-payments", "app-shipping", "app-promotions", "app-shop") |
| 73 | BILLING_PACKAGES = ("app-settings", "app-finance", "app-invoices", |
| 74 | "app-payments", "app-billing") |
| 75 | |
| 76 | |
| 77 | class FindingReproduced(AssertionError): |
| 78 | """Raised ONLY by the assertion that states a finding (see module doc).""" |
| 79 | |
| 80 | |
| 81 | def expect(actual, expected, what): |
| 82 | """The finding's own assertion: exact values, named, both sides shown.""" |
| 83 | if actual != expected: |
| 84 | raise FindingReproduced(f"{what}: expected {expected!r}, got {actual!r}") |
| 85 | |
| 86 | |
| 87 | def reproduced(message): |
| 88 | raise FindingReproduced(message) |
| 89 | |
| 90 | |
| 91 | class Env: |
| 92 | """One isolated install: a data dir, an object root, and the real doors. |
| 93 | |
| 94 | Packages are installed with object_packages.install_package (so handler |
| 95 | objects land as kind="system", which is the only kind the handler index |
| 96 | reads), and every write helper names which door it uses. |
| 97 | """ |
| 98 | |
| 99 | def __init__(self, tmp_path, monkeypatch): |
| 100 | self.monkeypatch = monkeypatch |
| 101 | self.data_dir = tmp_path / "data" |
| 102 | self.object_root = tmp_path / "objects" |
| 103 | self.object_root.mkdir() |
| 104 | monkeypatch.setenv("DBBASIC_DATA_DIR", str(self.data_dir)) |
| 105 | monkeypatch.setenv("DBBASIC_OBJECTS_DIR", str(self.object_root)) |
| 106 | monkeypatch.setenv("DBBASIC_ADMIN_TOKEN", ADMIN_TOKEN) |
| 107 | # A stock install: no reaction flag, no override root, no enforcement. |
| 108 | for flag in (object_handlers.HANDLERS_ENABLED_ENV, |
| 109 | object_change_dispatch.ENABLE_ENV, |
| 110 | "DBBASIC_OVERRIDES_DIR", |
| 111 | "DBBASIC_ENABLE_PERMISSION_ENFORCEMENT"): |
| 112 | monkeypatch.delenv(flag, raising=False) |
| 113 | self.runtime = python_object_runtime.PythonObjectRuntime( |
| 114 | base_dir=self.data_dir) |
| 115 | |
| 116 | # --- setup ----------------------------------------------------------- |
| 117 | def install(self, *packages): |
| 118 | for package_id in packages: |
| 119 | object_packages.install_package( |
| 120 | package_id, root=PACKAGES_ROOT, base_dir=self.data_dir, |
| 121 | object_roots=[self.object_root]) |
| 122 | object_handlers.invalidate() |
| 123 | |
| 124 | def setting(self, key, value): |
| 125 | self.create("app_settings", {"key": key, "value": value}) |
| 126 | |
| 127 | # --- storage-level door (what actions and runners use) ----------------- |
| 128 | def create(self, collection, record, **kwargs): |
| 129 | return object_records.create_collection_record( |
| 130 | collection, record, base_dir=self.data_dir, **kwargs) |
| 131 | |
| 132 | def update(self, collection, record_id, changes, actor="test"): |
| 133 | return object_records.update_collection_record( |
| 134 | collection, record_id, changes, base_dir=self.data_dir, actor=actor) |
| 135 | |
| 136 | def get(self, collection, record_id): |
| 137 | return object_records.get_collection_record( |
| 138 | collection, record_id, base_dir=self.data_dir) |
| 139 | |
| 140 | def rows(self, collection): |
| 141 | return object_records.read_collection_records( |
| 142 | collection, base_dir=self.data_dir) |
| 143 | |
| 144 | # --- executing an object directly (runners, actions, webhooks) --------- |
| 145 | def execute(self, object_id, method="POST", **payload): |
| 146 | return object_execution.execute_object( |
| 147 | self.runtime, |
| 148 | object_execution.ObjectExecutionRequest( |
| 149 | object_id, method=method, payload=payload), |
| 150 | roots=[self.object_root]) |
| 151 | |
| 152 | def run(self, object_id, method="POST", **payload): |
| 153 | result = self.execute(object_id, method, **payload) |
| 154 | assert result.ok, (object_id, result.error) |
| 155 | return result.result |
| 156 | |
| 157 | # --- the HTTP door, with the synchronous dispatcher --------------------- |
| 158 | def enable_handlers(self): |
| 159 | self.monkeypatch.setenv(object_handlers.HANDLERS_ENABLED_ENV, "true") |
| 160 | object_handlers.invalidate() |
| 161 | |
| 162 | def http(self, method, path, body=None): |
| 163 | """One request through the real ASGI app as the admin token.""" |
| 164 | async def call(): |
| 165 | messages = [] |
| 166 | sent = [] |
| 167 | |
| 168 | async def receive(): |
| 169 | if not sent: |
| 170 | sent.append(True) |
| 171 | raw = json.dumps(body).encode() if body is not None else b"" |
| 172 | return {"type": "http.request", "body": raw, "more_body": False} |
| 173 | return {"type": "http.disconnect"} |
| 174 | |
| 175 | async def send(message): |
| 176 | messages.append(message) |
| 177 | |
| 178 | scope = { |
| 179 | "type": "http", "method": method, "path": path, |
| 180 | "query_string": b"", |
| 181 | "headers": [(b"accept", b"application/json"), |
| 182 | (b"content-type", b"application/json"), |
| 183 | (b"authorization", f"Token {ADMIN_TOKEN}".encode())], |
| 184 | "client": ("127.0.0.1", 12345), |
| 185 | } |
| 186 | await object_server.app(scope, receive, send) |
| 187 | start = next(m for m in messages if m["type"] == "http.response.start") |
| 188 | payload = b"".join(m.get("body", b"") for m in messages |
| 189 | if m["type"] == "http.response.body") |
| 190 | return start["status"], json.loads(payload.decode("utf-8")) |
| 191 | |
| 192 | return asyncio.run(call()) |
| 193 | |
| 194 | def dispatch(self, collection, record_id, action): |
| 195 | """The server's own synchronous dispatcher, for a write whose HTTP |
| 196 | form needs an owner session (guarded transitions). It builds the |
| 197 | payload and picks the handlers exactly as the HTTP path does.""" |
| 198 | object_server._dispatch_event_handlers(collection, record_id, action, None) |
| 199 | |
| 200 | # --- the change-log replay pass (storage-level writes) ------------------ |
| 201 | def start_change_dispatch(self): |
| 202 | """Turn DBBASIC_ENABLE_CHANGE_DISPATCH on. The first pass only stamps |
| 203 | the cursor (it never backfills), so call this BEFORE the writes.""" |
| 204 | self.monkeypatch.setenv(object_change_dispatch.ENABLE_ENV, "true") |
| 205 | first = object_change_dispatch.dispatch_pending( |
| 206 | base_dir=self.data_dir, roots=[self.object_root]) |
| 207 | assert first["processed"] == 0 |
| 208 | time.sleep(0.002) # the cursor is a microsecond timestamp |
| 209 | |
| 210 | def replay(self): |
| 211 | """Replay passes until the change log is quiet; returns every |
| 212 | dispatch that happened. A handler that failed to EXECUTE fails the |
| 213 | test outright -- that would be a different bug from the one asserted.""" |
| 214 | results = [] |
| 215 | for _ in range(8): |
| 216 | outcome = object_change_dispatch.dispatch_pending( |
| 217 | base_dir=self.data_dir, roots=[self.object_root]) |
| 218 | assert outcome["errors"] == 0, outcome["results"] |
| 219 | results.extend(outcome["results"]) |
| 220 | if not outcome["processed"]: |
| 221 | return results |
| 222 | raise AssertionError("change dispatch never went quiet") |
| 223 | |
| 224 | |
| 225 | @pytest.fixture |
| 226 | def env(tmp_path, monkeypatch): |
| 227 | object_handlers.invalidate() |
| 228 | yield Env(tmp_path, monkeypatch) |
| 229 | object_handlers.invalidate() |
| 230 | |
| 231 | |
| 232 | @contextlib.contextmanager |
| 233 | def _unreadable(monkeypatch, collection): |
| 234 | """Make ONE collection unreadable for the duration of a `with` block -- |
| 235 | a transient read failure (too many open files, a lock timeout). The |
| 236 | patch is undone on exit, so nothing leaks into the rest of the test.""" |
| 237 | original = object_records.read_collection_records |
| 238 | |
| 239 | def flaky(name, *args, **kwargs): |
| 240 | if name == collection: |
| 241 | raise OSError(f"transient: {collection} could not be read") |
| 242 | return original(name, *args, **kwargs) |
| 243 | |
| 244 | with monkeypatch.context() as patcher: |
| 245 | patcher.setattr(object_records, "read_collection_records", flaky) |
| 246 | yield |
| 247 | |
| 248 | |
| 249 | def _money(record): |
| 250 | return tuple(int(record.get(field) or 0) |
| 251 | for field in ("subtotal_cents", "tax_cents", "total_cents")) |
| 252 | |
| 253 | |
| 254 | # =========================================================================== |
| 255 | # The shop: checkout documents and the two totals folds (M1, M2, M18, D1) |
| 256 | # =========================================================================== |
| 257 | |
| 258 | def _shop(env, *settings): |
| 259 | env.install(*SHOP_PACKAGES) |
| 260 | for key, value in settings: |
| 261 | env.setting(key, value) |
| 262 | env.create("products", { |
| 263 | "id": "p1", "name": "Mug", "sku": "P1", "product_type": "service", |
| 264 | "price_cents": "1400", "currency": "USD", "is_active": "true", |
| 265 | "owner_id": "shop"}) |
| 266 | env.create("products", { |
| 267 | "id": "p2", "name": "Loose tea (kg)", "sku": "P2", |
| 268 | "product_type": "service", "price_cents": "333", "currency": "USD", |
| 269 | # Sold by the kilo: a basket takes a fractional quantity only of |
| 270 | # a product whose unit is a measure (object_cart.sold_by_measure). |
| 271 | "unit": "kg", "is_active": "true", "owner_id": "shop"}) |
| 272 | |
| 273 | |
| 274 | def _checkout(env, *, session="s1", product_id="p1", quantity="1", **payload): |
| 275 | added = env.run("action_cart", session_token=session, action="add", |
| 276 | product_id=product_id, quantity=quantity) |
| 277 | assert added.get("ok") is True, added |
| 278 | placed = env.run("action_checkout", session_token=session, |
| 279 | customer_email="grace@example.test", **payload) |
| 280 | assert placed.get("ok") is True and placed.get("invoice_id"), placed |
| 281 | return placed |
| 282 | |
| 283 | |
| 284 | def _invoice_lines(env, invoice_id): |
| 285 | return [line for line in env.rows("invoice_lines") |
| 286 | if line["invoice_id"] == invoice_id] |
| 287 | |
| 288 | |
| 289 | def _order_lines(env, order_id): |
| 290 | return [line for line in env.rows("order_lines") |
| 291 | if line["order_id"] == order_id] |
| 292 | |
| 293 | |
| 294 | def test_m1_checkout_invoice_keeps_its_tax_when_only_the_postage_line_states_a_rate(env): |
| 295 | """Goods 1400 + postage 600 at 15% with taxable postage: the customer |
| 296 | agreed to 2300 (tax 300 on the whole 2000). action_checkout stamps the |
| 297 | rate on the postage line only, so the fold's "does any line state a |
| 298 | rate?" guard is satisfied by that one line and the document's tax is |
| 299 | replaced by the postage line's 90. The customer is then billed 210 less |
| 300 | than they agreed to and the shop under-collects tax it still owes. |
| 301 | |
| 302 | Driven through the change-log replay, which is how invoice_lines written |
| 303 | by action_checkout (storage level) reach this handler in production.""" |
| 304 | _shop(env, ("shop.tax_rate_bps", "1500"), ("shop.shipping_flat_cents", "600"), |
| 305 | ("shop.tax_shipping", "true")) |
| 306 | env.start_change_dispatch() |
| 307 | placed = _checkout(env) |
| 308 | assert (placed["subtotal_cents"], placed["shipping_cents"], |
| 309 | placed["tax_cents"], placed["total_cents"]) == (1400, 600, 300, 2300) |
| 310 | assert _money(env.get("invoices", placed["invoice_id"])) == (2000, 300, 2300) |
| 311 | |
| 312 | fired = [r for r in env.replay() if r["handler_id"] == "system_invoice_totals"] |
| 313 | assert [(r["event"], r["action"], r["ok"]) for r in fired] == [ |
| 314 | ("invoice_lines.record.created", "create", True)] * 2 |
| 315 | |
| 316 | expect(_money(env.get("invoices", placed["invoice_id"])), (2000, 300, 2300), |
| 317 | "checkout invoice (subtotal, tax, total) after invoice_totals folded its lines") |
| 318 | |
| 319 | |
| 320 | def test_m1_editing_a_line_description_over_http_does_not_restate_the_invoice_tax(env): |
| 321 | """The same fold reached the other way: a real PUT through the ASGI app |
| 322 | with DBBASIC_ENABLE_EVENT_HANDLERS on. The edit changes a description |
| 323 | and no money at all, yet the invoice total drops by 210.""" |
| 324 | _shop(env, ("shop.tax_rate_bps", "1500"), ("shop.shipping_flat_cents", "600"), |
| 325 | ("shop.tax_shipping", "true")) |
| 326 | placed = _checkout(env) |
| 327 | assert _money(env.get("invoices", placed["invoice_id"])) == (2000, 300, 2300) |
| 328 | goods = next(line for line in _invoice_lines(env, placed["invoice_id"]) |
| 329 | if line["description"] == "Mug") |
| 330 | |
| 331 | env.enable_handlers() |
| 332 | status, body = env.http( |
| 333 | "PUT", f"/collections/invoice_lines/records/{goods['id']}", |
| 334 | {"description": "Mug (gift wrapped)"}) |
| 335 | assert status == 200, body |
| 336 | assert env.get("invoice_lines", goods["id"])["description"] == "Mug (gift wrapped)" |
| 337 | |
| 338 | expect(_money(env.get("invoices", placed["invoice_id"])), (2000, 300, 2300), |
| 339 | "checkout invoice (subtotal, tax, total) after a description-only line edit") |
| 340 | |
| 341 | |
| 342 | def test_m2_checkout_order_total_keeps_the_postage_the_buyer_owes(env): |
| 343 | """The documented live numbers: 1400 goods + 600 postage + 116 tax = |
| 344 | 2116. action_checkout stamps orders.total_cents as "what the buyer |
| 345 | owes"; order_totals defines it as "what its own lines come to" and |
| 346 | rewrites it to 1400 + 116. The order then disagrees with its own invoice |
| 347 | (2116) by exactly the postage, and the confirmation email -- which prints |
| 348 | orders.total_cents -- quotes the customer 6.00 less than they are billed. |
| 349 | |
| 350 | Driven through the change-log replay of the order line action_checkout |
| 351 | wrote.""" |
| 352 | _shop(env, ("shop.tax_rate_bps", "825"), ("shop.shipping_flat_cents", "600")) |
| 353 | env.start_change_dispatch() |
| 354 | placed = _checkout(env) |
| 355 | assert (placed["subtotal_cents"], placed["shipping_cents"], |
| 356 | placed["tax_cents"], placed["total_cents"]) == (1400, 600, 116, 2116) |
| 357 | assert _money(env.get("orders", placed["order_id"])) == (1400, 116, 2116) |
| 358 | |
| 359 | fired = [r for r in env.replay() if r["handler_id"] == "system_order_totals"] |
| 360 | assert [(r["event"], r["action"], r["ok"]) for r in fired] == [ |
| 361 | ("order_lines.record.created", "create", True)] |
| 362 | |
| 363 | order = env.get("orders", placed["order_id"]) |
| 364 | assert (int(order["subtotal_cents"]), int(order["tax_cents"])) == (1400, 116) |
| 365 | expect(int(order["total_cents"]), 2116, |
| 366 | "checkout order total_cents after order_totals folded its lines") |
| 367 | |
| 368 | |
| 369 | def test_m2_checkout_order_total_keeps_the_promotion_discount(env): |
| 370 | """The other half of the same restatement: 1400 goods, 20% off (280), |
| 371 | 8.25% tax on the discounted 1120 = 92, so the buyer owes 1212. The fold |
| 372 | knows nothing about the redemption and writes 1400 + 92 = 1492 -- an |
| 373 | order that says the customer owes 2.80 more than the invoice does. |
| 374 | |
| 375 | Driven by a real PUT (a packer's note on the line) with handlers on.""" |
| 376 | _shop(env, ("shop.tax_rate_bps", "825")) |
| 377 | env.create("promotions", { |
| 378 | "id": "pr1", "code": "SPRING20", "kind": "percent", "value": "2000", |
| 379 | "is_active": "true", "stacking": "never", "owner_id": "shop"}) |
| 380 | placed = _checkout(env, promo_code="SPRING20") |
| 381 | assert (placed["subtotal_cents"], placed["shipping_cents"], |
| 382 | placed["discount_cents"], placed["tax_cents"], |
| 383 | placed["total_cents"]) == (1400, 0, 280, 92, 1212) |
| 384 | assert _money(env.get("orders", placed["order_id"])) == (1400, 92, 1212) |
| 385 | line = _order_lines(env, placed["order_id"])[0] |
| 386 | |
| 387 | env.enable_handlers() |
| 388 | status, body = env.http( |
| 389 | "PUT", f"/collections/order_lines/records/{line['id']}", |
| 390 | {"description": "Mug (blue)"}) |
| 391 | assert status == 200, body |
| 392 | |
| 393 | order = env.get("orders", placed["order_id"]) |
| 394 | assert (int(order["subtotal_cents"]), int(order["tax_cents"])) == (1400, 92) |
| 395 | expect(int(order["total_cents"]), 1212, |
| 396 | "discounted checkout order total_cents after order_totals folded its lines") |
| 397 | |
| 398 | |
| 399 | def _draft_with_document_tax(env): |
| 400 | """The 21.16 sale written as a DRAFT invoice with its tax on the |
| 401 | document and no rate on any line -- a hand-written bill still being |
| 402 | put together. Since decision 2 (2026-11-30) checkout stamps a rate on |
| 403 | every taxable line and invoice_totals folds drafts only, so a draft is |
| 404 | where the "fold must not replace a value it cannot reproduce" guard |
| 405 | still has work to do.""" |
| 406 | env.install("app-settings", "app-invoices") |
| 407 | env.create("invoices", { |
| 408 | "id": "inv-d1", "number": "D1", "customer_name": "Ada", "status": "draft", |
| 409 | "subtotal_cents": "2000", "tax_cents": "116", "total_cents": "2116", |
| 410 | "owner_id": "shop"}) |
| 411 | for line_id, description, price in (("l-mug", "Mug", "1400"), |
| 412 | ("l-post", "Shipping", "600")): |
| 413 | env.create("invoice_lines", { |
| 414 | "id": line_id, "invoice_id": "inv-d1", "description": description, |
| 415 | "quantity": "1", "unit_price_cents": price, "line_total_cents": price, |
| 416 | "owner_id": "shop"}) |
| 417 | return "inv-d1" |
| 418 | |
| 419 | |
| 420 | def test_d1_the_shop_cart_regression_payload_returns_before_the_fold(env): |
| 421 | """D1 CONFIRMED by tracing, pinned here as a fact. |
| 422 | |
| 423 | tests/test_shop_cart.py::test_a_totals_recompute_never_zeroes_tax_it_cannot_see |
| 424 | fires system_invoice_totals with |
| 425 | {"collection": "invoice_lines", "action": "created", "record_id": ""}. |
| 426 | invoice_totals.EVENT returns at its first guard (`not record_id`), so |
| 427 | the fold never runs and that test passes whether or not the "fold must |
| 428 | not replace a value it cannot reproduce" guard exists. |
| 429 | |
| 430 | Proof that the payload is inert: add a line so that a fold WOULD move |
| 431 | the (draft) invoice, fire that exact payload, and nothing moves; fire |
| 432 | the real dispatcher's payload and the invoice follows the line.""" |
| 433 | invoice_id = _draft_with_document_tax(env) |
| 434 | env.create("invoice_lines", {"id": "l-wrap", "invoice_id": invoice_id, |
| 435 | "description": "Gift wrap", "quantity": "1", |
| 436 | "unit_price_cents": "100", "owner_id": "shop"}) |
| 437 | |
| 438 | as_test_shop_cart_sends_it = env.run( |
| 439 | "system_invoice_totals", "EVENT", |
| 440 | collection="invoice_lines", action="created", record_id="") |
| 441 | assert as_test_shop_cart_sends_it == { |
| 442 | "ok": True, "skipped": "not an invoice_lines event"} |
| 443 | assert _money(env.get("invoices", invoice_id)) == (2000, 116, 2116) |
| 444 | |
| 445 | as_the_dispatcher_sends_it = env.run( |
| 446 | "system_invoice_totals", "EVENT", |
| 447 | event="invoice_lines.record.created", collection="invoice_lines", |
| 448 | record_id="l-wrap", action="create") |
| 449 | assert as_the_dispatcher_sends_it == { |
| 450 | "ok": True, "invoice_id": invoice_id, "changed": True} |
| 451 | assert _money(env.get("invoices", invoice_id)) == (2100, 116, 2216) |
| 452 | |
| 453 | |
| 454 | def test_d1_the_fold_keeps_document_level_tax_when_no_line_states_a_rate(env): |
| 455 | """The regression test the 21.16 incident should have: the same sale |
| 456 | (1400 goods + 600 postage + 116 tax computed once on the document, no |
| 457 | rate on any line), with invoice_totals actually run for every line the |
| 458 | way the dispatcher runs it -- raw verb, real record ids. The guard holds: |
| 459 | the invoice stays 2000/116/2116 instead of being restated to 2000/0/2000.""" |
| 460 | invoice_id = _draft_with_document_tax(env) |
| 461 | for line_id in ("l-mug", "l-post"): |
| 462 | result = env.run( |
| 463 | "system_invoice_totals", "EVENT", |
| 464 | event="invoice_lines.record.created", collection="invoice_lines", |
| 465 | record_id=line_id, action="create") |
| 466 | assert result == {"ok": True, "invoice_id": invoice_id, "changed": False} |
| 467 | |
| 468 | assert _money(env.get("invoices", invoice_id)) == (2000, 116, 2116) |
| 469 | |
| 470 | |
| 471 | def test_d2_checkout_stamps_every_taxable_line_with_its_rate_and_share(env): |
| 472 | """Decision 2 (2026-11-30): the rate is stamped per line at issue and |
| 473 | the tax is computed once per rate group, half-up, the odd cent to the |
| 474 | line with the largest remainder. 1400 goods + 650 taxable postage at |
| 475 | 8.25%: 169.125 -> 169 for the sale; 115.5 + 53.625 floor to 168 and the |
| 476 | cent goes to the postage (.625 > .5). The lines add up to the invoice, |
| 477 | and a basket discount carries the rate of what it discounts.""" |
| 478 | _shop(env, ("shop.tax_rate_bps", "825"), ("shop.shipping_flat_cents", "650"), |
| 479 | ("shop.tax_shipping", "true")) |
| 480 | placed = _checkout(env) |
| 481 | lines = {line["description"]: (line["tax_rate_bps"], line["line_tax_cents"]) |
| 482 | for line in _invoice_lines(env, placed["invoice_id"])} |
| 483 | assert lines == {"Mug": ("825", "115"), "Shipping": ("825", "54")} |
| 484 | assert placed["tax_cents"] == 169 |
| 485 | |
| 486 | |
| 487 | def test_d2_a_discount_line_carries_the_rate_of_what_it_discounts(env): |
| 488 | _shop(env, ("shop.tax_rate_bps", "825")) |
| 489 | env.create("promotions", { |
| 490 | "id": "pr1", "code": "SPRING20", "kind": "percent", "value": "2000", |
| 491 | "is_active": "true", "stacking": "never", "owner_id": "shop"}) |
| 492 | placed = _checkout(env, promo_code="SPRING20") |
| 493 | lines = sorted((line["unit_price_cents"], line["tax_rate_bps"], line["line_tax_cents"]) |
| 494 | for line in _invoice_lines(env, placed["invoice_id"])) |
| 495 | # 1400 x 8.25% = 115.5, -280 x 8.25% = -23.1: floors 115 and -24, the |
| 496 | # sale's 92 leaves one cent, which goes to the larger remainder (.9). |
| 497 | assert lines == [("-280", "825", "-23"), ("1400", "825", "115")] |
| 498 | assert placed["tax_cents"] == 92 |
| 499 | order = env.get("orders", placed["order_id"]) |
| 500 | assert (order["discount_cents"], order["total_cents"]) == ("280", "1212") |
| 501 | |
| 502 | |
| 503 | def test_m18_the_cart_and_the_line_fold_agree_on_the_tax_of_one_line(): |
| 504 | """650 cents of postage at 825 bps is 53.625. action_checkout stamps the |
| 505 | postage line's line_tax_cents with object_cart.tax_cents; invoice_totals |
| 506 | recomputes the same field with object_lines.line_amounts.""" |
| 507 | cart_tax = object_cart.tax_cents(650, 825) |
| 508 | line_tax = object_lines.line_amounts( |
| 509 | {"quantity": "1", "unit_price_cents": "650", "tax_rate_bps": "825"} |
| 510 | )["line_tax_cents"] |
| 511 | assert {cart_tax, line_tax} <= {53, 54} |
| 512 | expect(line_tax, cart_tax, |
| 513 | "line_tax_cents for 650 cents at 825 bps: object_lines vs object_cart") |
| 514 | |
| 515 | |
| 516 | def test_m18_invoice_totals_leaves_the_stamped_postage_line_tax_alone(env): |
| 517 | """End to end: checkout stamps 54 on the postage line; the first event |
| 518 | for that line makes invoice_totals write 53 over it.""" |
| 519 | _shop(env, ("shop.tax_rate_bps", "825"), ("shop.shipping_flat_cents", "650"), |
| 520 | ("shop.tax_shipping", "true")) |
| 521 | placed = _checkout(env) |
| 522 | postage = next(line for line in _invoice_lines(env, placed["invoice_id"]) |
| 523 | if line["description"] == "Shipping") |
| 524 | assert (postage["line_total_cents"], postage["tax_rate_bps"], |
| 525 | postage["line_tax_cents"]) == ("650", "825", "54") |
| 526 | |
| 527 | env.enable_handlers() |
| 528 | status, body = env.http( |
| 529 | "PUT", f"/collections/invoice_lines/records/{postage['id']}", |
| 530 | {"description": "Shipping (tracked)"}) |
| 531 | assert status == 200, body |
| 532 | |
| 533 | expect(env.get("invoice_lines", postage["id"])["line_tax_cents"], "54", |
| 534 | "postage line_tax_cents after invoice_totals synced the line") |
| 535 | |
| 536 | |
| 537 | def test_m18_order_totals_leaves_a_fractional_quantity_line_total_alone(env): |
| 538 | """The same disagreement on line_total_cents: 1.5 x 333 = 499.5, which |
| 539 | object_cart.line_total_cents rounds to 500 (what the shopper was shown |
| 540 | and agreed to) and object_lines floors to 499.""" |
| 541 | assert object_cart.line_total_cents("1.5", 333) == 500 |
| 542 | _shop(env, ("shop.tax_rate_bps", "0")) |
| 543 | placed = _checkout(env, product_id="p2", quantity="1.5") |
| 544 | assert placed["subtotal_cents"] == 500 |
| 545 | line = _order_lines(env, placed["order_id"])[0] |
| 546 | assert (line["quantity"], line["unit_price_cents"], |
| 547 | line["line_total_cents"]) == ("1.5", "333", "500") |
| 548 | |
| 549 | env.enable_handlers() |
| 550 | status, body = env.http( |
| 551 | "PUT", f"/collections/order_lines/records/{line['id']}", |
| 552 | {"description": "Loose tea, 1.5 kg"}) |
| 553 | assert status == 200, body |
| 554 | |
| 555 | expect(env.get("order_lines", line["id"])["line_total_cents"], "500", |
| 556 | "order line_total_cents (1.5 x 333) after order_totals synced the line") |
| 557 | |
| 558 | |
| 559 | # =========================================================================== |
| 560 | # Invoice status follows the money (M3, M4) |
| 561 | # =========================================================================== |
| 562 | |
| 563 | def _invoice(env, invoice_id, total="2000", owner="u1"): |
| 564 | """An issued invoice, written the way checkout and the biller write it.""" |
| 565 | return env.create("invoices", { |
| 566 | "id": invoice_id, "number": invoice_id.upper(), "customer_name": "Ada", |
| 567 | "status": "sent", "issue_date": "2026-11-01", "due_date": "2026-12-31", |
| 568 | "subtotal_cents": total, "total_cents": total, "owner_id": owner}) |
| 569 | |
| 570 | |
| 571 | def _pay_over_http(env, payment_id, invoice_id, amount): |
| 572 | status, body = env.http("POST", "/collections/payments/records", { |
| 573 | "id": payment_id, "invoice_id": invoice_id, "amount_cents": str(amount), |
| 574 | "method": "card", "received_on": "2026-11-02", "owner_id": "u1"}) |
| 575 | assert status == 201, body |
| 576 | |
| 577 | |
| 578 | def _refund_over_http(env, refund_id, payment_id, invoice_id, amount): |
| 579 | status, body = env.http("POST", "/collections/refunds/records", { |
| 580 | "id": refund_id, "payment_id": payment_id, "invoice_id": invoice_id, |
| 581 | "amount_cents": str(amount), "refunded_on": "2026-11-03", |
| 582 | "owner_id": "u1"}) |
| 583 | assert status == 201, body |
| 584 | |
| 585 | |
| 586 | def _paid_state(env, invoice_id): |
| 587 | invoice = env.get("invoices", invoice_id) |
| 588 | return (invoice["status"], int(invoice["amount_paid_cents"] or 0), |
| 589 | int(invoice["balance_due_cents"] or 0)) |
| 590 | |
| 591 | |
| 592 | def test_m3_a_fully_refunded_invoice_does_not_stay_paid(env): |
| 593 | """Pay 2000, refund 2000, both over HTTP with handlers on. The derived |
| 594 | fields are right (paid 0, balance 2000) and the status is not: every |
| 595 | list, the aging pass and system_shop_fulfillment keep reading `paid`.""" |
| 596 | env.install("app-settings", "app-invoices", "app-payments") |
| 597 | env.enable_handlers() |
| 598 | _invoice(env, "inv1") |
| 599 | _pay_over_http(env, "pay1", "inv1", 2000) |
| 600 | assert _paid_state(env, "inv1") == ("paid", 2000, 0) |
| 601 | |
| 602 | _refund_over_http(env, "ref1", "pay1", "inv1", 2000) |
| 603 | status, paid, balance = _paid_state(env, "inv1") |
| 604 | assert (paid, balance) == (0, 2000) |
| 605 | if status == "paid": |
| 606 | reproduced("invoice with amount_paid_cents 0 and balance_due_cents 2000 " |
| 607 | "after a full refund still has status 'paid'") |
| 608 | |
| 609 | |
| 610 | def test_m3_a_bounced_payment_does_not_leave_the_invoice_paid(env): |
| 611 | """A cheque is recorded, the invoice flips to paid, the cheque bounces |
| 612 | (payments.status received -> bounced, written at storage level the way |
| 613 | action_resolve_bank_line does and replayed from the change log).""" |
| 614 | env.install("app-settings", "app-invoices", "app-payments") |
| 615 | env.start_change_dispatch() |
| 616 | _invoice(env, "inv1") |
| 617 | env.create("payments", { |
| 618 | "id": "pay1", "invoice_id": "inv1", "amount_cents": "2000", |
| 619 | "method": "check", "received_on": "2026-11-02", "status": "received", |
| 620 | "owner_id": "u1"}) |
| 621 | env.replay() |
| 622 | assert _paid_state(env, "inv1") == ("paid", 2000, 0) |
| 623 | |
| 624 | env.update("payments", "pay1", {"status": "bounced"}, |
| 625 | actor="action_resolve_bank_line") |
| 626 | fired = [r for r in env.replay() if r["handler_id"] == "system_invoice_status"] |
| 627 | assert [(r["event"], r["action"]) for r in fired] == [ |
| 628 | ("payments.record.updated", "update")] |
| 629 | |
| 630 | status, paid, balance = _paid_state(env, "inv1") |
| 631 | assert (paid, balance) == (0, 2000) |
| 632 | if status == "paid": |
| 633 | reproduced("invoice whose only payment bounced (amount_paid_cents 0, " |
| 634 | "balance_due_cents 2000) still has status 'paid'") |
| 635 | |
| 636 | |
| 637 | def test_m3_a_part_payment_refunded_in_full_does_not_leave_the_invoice_partial(env): |
| 638 | env.install("app-settings", "app-invoices", "app-payments") |
| 639 | env.enable_handlers() |
| 640 | _invoice(env, "inv1") |
| 641 | _pay_over_http(env, "pay1", "inv1", 500) |
| 642 | assert _paid_state(env, "inv1") == ("partial", 500, 1500) |
| 643 | |
| 644 | _refund_over_http(env, "ref1", "pay1", "inv1", 500) |
| 645 | status, paid, balance = _paid_state(env, "inv1") |
| 646 | assert (paid, balance) == (0, 2000) |
| 647 | if status == "partial": |
| 648 | reproduced("invoice with amount_paid_cents 0 after its only part " |
| 649 | "payment was refunded still has status 'partial'") |
| 650 | |
| 651 | |
| 652 | def test_m4_deleting_a_payment_un_pays_the_invoice_at_the_latest_by_the_aging_pass(env): |
| 653 | """Payments are owner-deletable (app-payments/permissions/rules.json). |
| 654 | The delete goes through the ASGI app with handlers on, and then the |
| 655 | aging pass the handler's own comment defers to is run as well.""" |
| 656 | env.install("app-settings", "app-invoices", "app-payments") |
| 657 | env.enable_handlers() |
| 658 | _invoice(env, "inv1") |
| 659 | _pay_over_http(env, "pay1", "inv1", 2000) |
| 660 | assert _paid_state(env, "inv1") == ("paid", 2000, 0) |
| 661 | |
| 662 | status, body = env.http("DELETE", "/collections/payments/records/pay1") |
| 663 | assert status == 200, body |
| 664 | assert env.rows("payments") == [] |
| 665 | aging = env.run("system_invoice_aging", today="2026-12-01") |
| 666 | assert aging["ok"] is True |
| 667 | |
| 668 | status, paid, balance = _paid_state(env, "inv1") |
| 669 | assert (paid, balance) == (0, 2000) |
| 670 | if status == "paid": |
| 671 | reproduced("invoice whose only payment was deleted (amount_paid_cents " |
| 672 | "0, balance_due_cents 2000) is still 'paid' after " |
| 673 | "invoice_status and invoice_aging both ran") |
| 674 | |
| 675 | |
| 676 | def test_m4_deleting_a_refund_restores_the_paid_status(env): |
| 677 | """Pay 2000, refund 800 (invoice correctly drops to partial), then the |
| 678 | refund is deleted as entered in error. Paid 2000 of 2000, balance 0 -- |
| 679 | and the invoice keeps saying partial, so it is dunned for money that is |
| 680 | not owed.""" |
| 681 | env.install("app-settings", "app-invoices", "app-payments") |
| 682 | env.enable_handlers() |
| 683 | assert object_handlers.get_handlers("payments.record.deleted") == [ |
| 684 | "system_invoice_status"] |
| 685 | _invoice(env, "inv1") |
| 686 | _pay_over_http(env, "pay1", "inv1", 2000) |
| 687 | _refund_over_http(env, "ref1", "pay1", "inv1", 800) |
| 688 | assert _paid_state(env, "inv1") == ("partial", 1200, 800) |
| 689 | |
| 690 | status, body = env.http("DELETE", "/collections/refunds/records/ref1") |
| 691 | assert status == 200, body |
| 692 | aging = env.run("system_invoice_aging", today="2026-12-01") |
| 693 | assert aging["ok"] is True |
| 694 | |
| 695 | status, paid, balance = _paid_state(env, "inv1") |
| 696 | assert (paid, balance) == (2000, 0) |
| 697 | expect(status, "paid", |
| 698 | "status of an invoice paid 2000 of 2000 after its refund was deleted") |
| 699 | |
| 700 | |
| 701 | # =========================================================================== |
| 702 | # Recurring journals (M8) |
| 703 | # =========================================================================== |
| 704 | |
| 705 | RECURRING_LINES = json.dumps([ |
| 706 | {"account_id": "acct-rent", "debit_cents": 1000, "credit_cents": 0}, |
| 707 | {"account_id": "acct-cash", "debit_cents": 0, "credit_cents": 1000}, |
| 708 | ]) |
| 709 | |
| 710 | |
| 711 | def _finance(env): |
| 712 | env.install("app-settings", "app-finance") |
| 713 | for account_id, kind in (("acct-rent", "expense"), ("acct-cash", "asset"), |
| 714 | ("acct-reimb", "liability")): |
| 715 | env.create("fin_accounts", { |
| 716 | "id": account_id, "name": account_id, "code": account_id, |
| 717 | "account_type": kind, "owner_id": "u1"}) |
| 718 | |
| 719 | |
| 720 | def _template(env, template_id, frequency, next_run): |
| 721 | env.create("fin_recurring", { |
| 722 | "id": template_id, "name": template_id, |
| 723 | "template_lines": RECURRING_LINES, "frequency": frequency, |
| 724 | "next_run": next_run, "auto_post": "true", "is_active": "true", |
| 725 | "owner_id": "u1"}) |
| 726 | |
| 727 | |
| 728 | def _recurring_journals(env): |
| 729 | return sorted(journal["generated_from"] for journal in env.rows("fin_journals") |
| 730 | if journal["generated_from"].startswith("fin_recurring/")) |
| 731 | |
| 732 | |
| 733 | def test_m8_weekly_monthly_and_yearly_schedules_advance_by_their_own_period(env): |
| 734 | """The control: the three frequencies _advance knows are right, so the |
| 735 | two xfails below fail for the frequency and nothing else.""" |
| 736 | _finance(env) |
| 737 | _template(env, "weekly", "weekly", "2026-03-10") |
| 738 | _template(env, "monthly", "monthly", "2026-03-10") |
| 739 | _template(env, "yearly", "yearly", "2026-03-10") |
| 740 | result = env.run("system_fin_recurring_runner", today="2026-03-10") |
| 741 | assert result["ran"] == 3 |
| 742 | assert {t["id"]: (t["last_run"], t["next_run"]) |
| 743 | for t in env.rows("fin_recurring")} == { |
| 744 | "weekly": ("2026-03-10", "2026-03-17"), |
| 745 | "monthly": ("2026-03-10", "2026-04-10"), |
| 746 | "yearly": ("2026-03-10", "2027-03-10")} |
| 747 | |
| 748 | |
| 749 | def test_m8_a_daily_schedule_advances_by_one_day(env): |
| 750 | """A daily accrual books once and then goes quiet for a month: 30 of |
| 751 | every 31 entries are never composed.""" |
| 752 | _finance(env) |
| 753 | _template(env, "daily", "daily", "2026-03-10") |
| 754 | result = env.run("system_fin_recurring_runner", today="2026-03-10") |
| 755 | assert result["ran"] == 1 |
| 756 | assert _recurring_journals(env) == ["fin_recurring/daily:2026-03-10"] |
| 757 | expect(env.get("fin_recurring", "daily")["next_run"], "2026-03-11", |
| 758 | "next_run of a daily template after its 2026-03-10 run") |
| 759 | |
| 760 | |
| 761 | def test_m8_a_quarterly_schedule_advances_by_three_months(env): |
| 762 | """A quarterly adjusting entry is composed every month instead: the |
| 763 | expense is booked three times over in each quarter.""" |
| 764 | _finance(env) |
| 765 | _template(env, "quarterly", "quarterly", "2026-03-10") |
| 766 | result = env.run("system_fin_recurring_runner", today="2026-03-10") |
| 767 | assert result["ran"] == 1 |
| 768 | expect(env.get("fin_recurring", "quarterly")["next_run"], "2026-06-10", |
| 769 | "next_run of a quarterly template after its 2026-03-10 run") |
| 770 | |
| 771 | |
| 772 | def test_m8_a_yearly_schedule_from_feb_29_does_not_block_the_templates_after_it(env): |
| 773 | """`date.replace(year=2029)` on 2028-02-29 raises. The leap template has |
| 774 | already composed its journal and never advances, so it raises again on |
| 775 | every pass and the rent template behind it never runs at all.""" |
| 776 | _finance(env) |
| 777 | _template(env, "a-leap", "yearly", "2028-02-29") |
| 778 | _template(env, "b-rent", "monthly", "2028-02-29") |
| 779 | |
| 780 | first = env.execute("system_fin_recurring_runner", today="2028-02-29") |
| 781 | second = env.execute("system_fin_recurring_runner", today="2028-03-01") |
| 782 | journals = _recurring_journals(env) |
| 783 | assert "fin_recurring/a-leap:2028-02-29" in journals |
| 784 | if not first.ok or not second.ok: |
| 785 | failed = first if not first.ok else second |
| 786 | assert "ValueError: day 29 must be in range" in failed.error.message, ( |
| 787 | failed.error.message) |
| 788 | reproduced("the pass raised on the Feb 29 yearly template; journals " |
| 789 | f"composed across two runs: {journals}; b-rent next_run " |
| 790 | f"still {env.get('fin_recurring', 'b-rent')['next_run']!r}") |
| 791 | expect("fin_recurring/b-rent:2028-02-29" in journals, True, |
| 792 | "the monthly template after the leap-day one was composed") |
| 793 | |
| 794 | |
| 795 | def test_m8_a_skipped_compose_does_not_consume_the_period(env): |
| 796 | """fin_journals cannot be read for one pass. The composer correctly |
| 797 | declines to risk a duplicate -- and the runner then advances the |
| 798 | template past the period anyway, so the healthy pass a minute later has |
| 799 | nothing due and March's entry is simply missing from the books.""" |
| 800 | _finance(env) |
| 801 | _template(env, "rent", "monthly", "2026-03-10") |
| 802 | |
| 803 | with _unreadable(env.monkeypatch, "fin_journals"): |
| 804 | during = env.run("system_fin_recurring_runner", today="2026-03-10") |
| 805 | assert during["results"] == [{"template": "rent", "journal": "", "posted": False}] |
| 806 | assert env.rows("fin_journals") == [] |
| 807 | |
| 808 | env.run("system_fin_recurring_runner", today="2026-03-10") |
| 809 | expect(_recurring_journals(env), ["fin_recurring/rent:2026-03-10"], |
| 810 | "journals for the 2026-03-10 period once the books were readable again " |
| 811 | f"(template next_run is {env.get('fin_recurring', 'rent')['next_run']!r})") |
| 812 | |
| 813 | |
| 814 | # =========================================================================== |
| 815 | # Shipping: cost of goods, the status ladder, the confirmation link (M5, S5, R7) |
| 816 | # =========================================================================== |
| 817 | |
| 818 | def _warehouse(env, *extra_packages): |
| 819 | env.install("app-settings", "app-catalog", "app-orders", "app-shipping", |
| 820 | "app-finance", *extra_packages) |
| 821 | for key, value in (("shop.stock_location", "loc-shelf"), |
| 822 | ("shop.customer_location", "loc-customer"), |
| 823 | ("inventory.journal.inventory_account", "acct-inventory"), |
| 824 | ("inventory.journal.sale_account", "acct-cogs"), |
| 825 | ("inventory.journal.cogs_account", "acct-cogs"), |
| 826 | ("inventory.journal.shrinkage_account", "acct-shrinkage")): |
| 827 | env.setting(key, value) |
| 828 | for account_id in ("acct-inventory", "acct-cogs", "acct-shrinkage"): |
| 829 | env.create("fin_accounts", { |
| 830 | "id": account_id, "name": account_id, "code": account_id, |
| 831 | "account_type": "asset", "owner_id": "shop"}) |
| 832 | for location_id in ("loc-shelf", "loc-customer"): |
| 833 | env.create("locations", {"id": location_id, "name": location_id, |
| 834 | "owner_id": "shop"}) |
| 835 | env.create("products", { |
| 836 | "id": "p1", "name": "Enamel Mug", "sku": "P1", "product_type": "physical", |
| 837 | "cost_cents": "250", "price_cents": "1200", "owner_id": "shop"}) |
| 838 | env.create("stock_moves", { |
| 839 | "id": "mv-purchase", "product_id": "p1", "to_location_id": "loc-shelf", |
| 840 | "quantity": "10", "unit_cost_cents": "250", "reason": "purchase", |
| 841 | "occurred_at": "2026-06-01", "owner_id": "shop"}) |
| 842 | env.create("orders", { |
| 843 | "id": "o1", "doc_type": "sale", "number": "SO-1", "customer_name": "Ada", |
| 844 | "customer_email": "ada@example.test", "status": "confirmed", |
| 845 | "order_date": "2026-07-01", "owner_id": "shop"}) |
| 846 | env.create("order_lines", { |
| 847 | "id": "ol1", "order_id": "o1", "product_id": "p1", "description": "Mug", |
| 848 | "quantity": "3", "unit_price_cents": "1200", "line_total_cents": "3600", |
| 849 | "owner_id": "shop"}) |
| 850 | env.create("order_lines", { |
| 851 | "id": "ol2", "order_id": "o1", "product_id": "p1", |
| 852 | "description": "Mug, second box", "quantity": "1", |
| 853 | "unit_price_cents": "1200", "line_total_cents": "1200", |
| 854 | "owner_id": "shop"}) |
| 855 | |
| 856 | |
| 857 | def _shipment(env, shipment_id, *lines): |
| 858 | env.create("shipments", {"id": shipment_id, "order_id": "o1", |
| 859 | "direction": "outbound", "status": "packed", |
| 860 | "owner_id": "shop"}) |
| 861 | for order_line_id, quantity in lines: |
| 862 | env.create("shipment_lines", { |
| 863 | "id": f"{shipment_id}-{order_line_id}", "shipment_id": shipment_id, |
| 864 | "order_line_id": order_line_id, "product_id": "p1", |
| 865 | "description": "Mug", "quantity": quantity, "owner_id": "shop"}) |
| 866 | |
| 867 | |
| 868 | def _move_shipment(env, shipment_id, status): |
| 869 | """The warehouse marks a parcel (a guarded transition, so written at |
| 870 | storage level by the owner) and the change log is replayed.""" |
| 871 | env.update("shipments", shipment_id, {"status": status}, actor="shop") |
| 872 | return env.replay() |
| 873 | |
| 874 | |
| 875 | def test_m5_shipping_a_sale_books_its_cost_of_goods(env): |
| 876 | """Three mugs bought at 250 leave the shelf: the books should show DR |
| 877 | cost of goods sold 750 / CR inventory 750. The real chain is shipment |
| 878 | -> order_fulfillment -> stock move -> system_stock_books, all replayed |
| 879 | from the change log here. tests/test_cogs_on_sale.py proves the last |
| 880 | link only, by staging the move with a hand-written cost.""" |
| 881 | _warehouse(env) |
| 882 | env.start_change_dispatch() |
| 883 | _shipment(env, "s1", ("ol1", "3")) |
| 884 | fired = _move_shipment(env, "s1", "shipped") |
| 885 | |
| 886 | sales = [move for move in env.rows("stock_moves") if move["reason"] == "sale"] |
| 887 | assert [(move["product_id"], move["quantity"], move["reference"]) |
| 888 | for move in sales] == [("p1", "3", "shipments/s1:line/s1-ol1 SO-1")] |
| 889 | assert ("stock_moves.record.created", "system_stock_books") in [ |
| 890 | (r["event"], r["handler_id"]) for r in fired if r["record_id"] == sales[0]["id"]] |
| 891 | |
| 892 | cogs_debits = [ |
| 893 | int(line["debit_cents"]) for line in env.rows("fin_journal_lines") |
| 894 | if line["account_id"] == "acct-cogs"] |
| 895 | if not cogs_debits: |
| 896 | reproduced("no cost-of-goods journal after a 3 x 250 sale shipped; the " |
| 897 | f"sale move's unit_cost_cents is {sales[0]['unit_cost_cents']!r} " |
| 898 | f"and fin_journals holds {len(env.rows('fin_journals'))} rows") |
| 899 | expect(cogs_debits, [750], "cost of goods sold debits for the shipped sale") |
| 900 | |
| 901 | |
| 902 | def test_s5_an_order_with_a_lost_parcel_drops_back_to_partial(env): |
| 903 | _warehouse(env) |
| 904 | env.start_change_dispatch() |
| 905 | _shipment(env, "s1", ("ol1", "3")) |
| 906 | _shipment(env, "s2", ("ol2", "1")) |
| 907 | _move_shipment(env, "s1", "shipped") |
| 908 | assert env.get("orders", "o1")["status"] == "partial" |
| 909 | _move_shipment(env, "s2", "shipped") |
| 910 | assert env.get("orders", "o1")["status"] == "shipped" |
| 911 | |
| 912 | _move_shipment(env, "s2", "lost") |
| 913 | assert env.get("shipments", "s2")["status"] == "lost" |
| 914 | expect(env.get("orders", "o1")["status"], "partial", |
| 915 | "order status after one of its two shipped parcels was lost") |
| 916 | |
| 917 | |
| 918 | def test_s5_an_order_whose_only_parcel_was_lost_is_back_in_the_pick_queue(env): |
| 919 | """With every counted shipment gone the derivation returns "" and the |
| 920 | order is left where it was. Nothing tells anybody the customer still |
| 921 | has not received anything.""" |
| 922 | _warehouse(env) |
| 923 | env.start_change_dispatch() |
| 924 | assert env.run("system_order_attention", "COUNT") == { |
| 925 | "count": 1, "detail": "4 units to pick"} |
| 926 | _shipment(env, "s1", ("ol1", "3"), ("ol2", "1")) |
| 927 | _move_shipment(env, "s1", "shipped") |
| 928 | assert env.get("orders", "o1")["status"] == "shipped" |
| 929 | assert env.run("system_order_attention", "COUNT")["count"] == 0 |
| 930 | |
| 931 | _move_shipment(env, "s1", "lost") |
| 932 | count = env.run("system_order_attention", "COUNT")["count"] |
| 933 | expect(count, 1, |
| 934 | "orders awaiting picking after the only parcel was lost (order " |
| 935 | f"status is {env.get('orders', 'o1')['status']!r})") |
| 936 | |
| 937 | |
| 938 | def test_r7_the_confirmation_email_of_a_hand_entered_order_carries_its_tracking_link(env): |
| 939 | """A confirmed order entered over the API (not a web checkout, which |
| 940 | mints its own token). Both handlers fire on the one write; the token |
| 941 | exists a moment after the email that needed it was queued. A later |
| 942 | event on the order does not help: the `confirmed` marker is already in |
| 943 | the outbox, so the customer is never sent the link.""" |
| 944 | env.install("app-settings", "app-orders", "app-email") |
| 945 | env.setting("portal.base_url", "https://shop.example.test") |
| 946 | env.enable_handlers() |
| 947 | assert object_handlers.get_handlers("orders.record.created") == [ |
| 948 | "system_order_email", "system_order_portal_link"] |
| 949 | |
| 950 | status, body = env.http("POST", "/collections/orders/records", { |
| 951 | "id": "o1", "doc_type": "sale", "number": "SO-1", "customer_name": "Ada", |
| 952 | "customer_email": "ada@example.test", "status": "confirmed", |
| 953 | "order_date": "2026-07-01", "owner_id": "shop"}) |
| 954 | assert status == 201, body |
| 955 | status, body = env.http("PUT", "/collections/orders/records/o1", |
| 956 | {"notes": "Customer rang to check the address."}) |
| 957 | assert status == 200, body |
| 958 | |
| 959 | token = env.get("orders", "o1")["portal_token"] |
| 960 | assert token, "system_order_portal_link did not mint a token" |
| 961 | mails = [mail for mail in env.rows("email_outbox") |
| 962 | if mail["to"] == "ada@example.test"] |
| 963 | assert [mail["subject"] for mail in mails] == ["Your order SO-1 is confirmed"] |
| 964 | link = f"https://shop.example.test/orders/track/{token}" |
| 965 | expect(link in mails[0]["text_body"], True, |
| 966 | f"the confirmation email contains the tracking link {link}") |
| 967 | |
| 968 | |
| 969 | # =========================================================================== |
| 970 | # Expenses reach the books, and leave them (M9) |
| 971 | # =========================================================================== |
| 972 | |
| 973 | def _expense_books(env): |
| 974 | _finance(env) |
| 975 | for key, value in (("expenses.journal.expense_account", "acct-rent"), |
| 976 | ("expenses.journal.paid_account", "acct-cash"), |
| 977 | ("expenses.journal.reimbursable_account", "acct-reimb")): |
| 978 | env.setting(key, value) |
| 979 | env.create("expenses", { |
| 980 | "id": "e1", "description": "Flight to Leeds", "incurred_on": "2026-05-01", |
| 981 | "amount_cents": "30000", "status": "submitted", "paid_by": "company", |
| 982 | "owner_id": "u1"}) |
| 983 | env.enable_handlers() |
| 984 | |
| 985 | |
| 986 | def _set_expense_status(env, status): |
| 987 | code, body = env.http("PUT", "/collections/expenses/records/e1", |
| 988 | {"status": status}) |
| 989 | assert code == 200, body |
| 990 | assert env.get("expenses", "e1")["status"] == status |
| 991 | |
| 992 | |
| 993 | def _net_expense_on_the_books(env): |
| 994 | posted = {journal["id"] for journal in env.rows("fin_journals") |
| 995 | if journal["status"] == "posted"} |
| 996 | return sum(int(line["debit_cents"] or 0) - int(line["credit_cents"] or 0) |
| 997 | for line in env.rows("fin_journal_lines") |
| 998 | if line["journal_id"] in posted and line["account_id"] == "acct-rent") |
| 999 | |
| 1000 | |
| 1001 | def test_m9_rejecting_an_approved_expense_takes_it_back_off_the_books(env): |
| 1002 | """approved -> rejected is a declared transition on expenses.status. |
| 1003 | Both moves are real PUTs with handlers on.""" |
| 1004 | _expense_books(env) |
| 1005 | _set_expense_status(env, "approved") |
| 1006 | assert _net_expense_on_the_books(env) == 30000 |
| 1007 | |
| 1008 | _set_expense_status(env, "rejected") |
| 1009 | expect(_net_expense_on_the_books(env), 0, |
| 1010 | "net posted expense for a rejected expense (cents)") |
| 1011 | |
| 1012 | |
| 1013 | def test_m9_reapproving_a_corrected_expense_books_the_corrected_amount(env): |
| 1014 | """rejected -> draft -> (amount corrected 30000 -> 12000) -> submitted |
| 1015 | -> approved. The owner's own moves are guarded transitions, written at |
| 1016 | storage level and dispatched by the server's dispatcher; both approvals |
| 1017 | and the rejection are real PUTs.""" |
| 1018 | _expense_books(env) |
| 1019 | _set_expense_status(env, "approved") |
| 1020 | _set_expense_status(env, "rejected") |
| 1021 | for changes in ({"status": "draft"}, {"amount_cents": "12000"}, |
| 1022 | {"status": "submitted"}): |
| 1023 | env.update("expenses", "e1", changes, actor="u1") |
| 1024 | env.dispatch("expenses", "e1", "update") |
| 1025 | _set_expense_status(env, "approved") |
| 1026 | assert env.get("expenses", "e1")["amount_cents"] == "12000" |
| 1027 | |
| 1028 | expect(_net_expense_on_the_books(env), 12000, |
| 1029 | "net posted expense for an expense approved at 12000 cents") |
| 1030 | |
| 1031 | |
| 1032 | # =========================================================================== |
| 1033 | # The period biller and the usage fold (M10, M11) |
| 1034 | # =========================================================================== |
| 1035 | |
| 1036 | def _billing(env): |
| 1037 | env.install(*BILLING_PACKAGES) |
| 1038 | _plan(env, "plan-pro") |
| 1039 | |
| 1040 | |
| 1041 | def _plan(env, plan_id): |
| 1042 | env.create("billing_plans", { |
| 1043 | "id": plan_id, "name": "Pro", "code": plan_id, "period": "month", |
| 1044 | "base_minor": "4900", "is_active": "true", "owner_id": "dan"}) |
| 1045 | |
| 1046 | |
| 1047 | def _subscribe(env, subscription_id, plan_id="plan-pro", |
| 1048 | start="2026-06-01", end="2026-06-30"): |
| 1049 | env.create("subscriptions", { |
| 1050 | "id": subscription_id, "customer_name": "Acme Ltd", |
| 1051 | "customer_email": "a@acme.test", "plan_id": plan_id, |
| 1052 | "billing_mode": "subscription", "status": "active", |
| 1053 | "current_period_start": start, "current_period_end": end, |
| 1054 | "owner_id": "dan"}) |
| 1055 | |
| 1056 | |
| 1057 | def _period(env, subscription_id): |
| 1058 | row = env.get("subscriptions", subscription_id) |
| 1059 | return row["current_period_start"], row["current_period_end"] |
| 1060 | |
| 1061 | |
| 1062 | def _subscription_invoices(env, subscription_id): |
| 1063 | """The invoices that CLOSE a period (what M10 is about). Since decision |
| 1064 | 4 (2026-11-30) the base fee is billed in advance, so a subscription |
| 1065 | whose current period began unbilled also gets an opening invoice for it |
| 1066 | (numbered ...-ADV); _advance_invoices lists those.""" |
| 1067 | return [(invoice["number"], int(invoice["total_cents"])) |
| 1068 | for invoice in env.rows("invoices") |
| 1069 | if invoice["number"].startswith(f"SUB-{subscription_id[:8]}-") |
| 1070 | and not invoice["number"].endswith("-ADV")] |
| 1071 | |
| 1072 | |
| 1073 | def _advance_invoices(env, subscription_id): |
| 1074 | return [(invoice["number"], int(invoice["total_cents"])) |
| 1075 | for invoice in env.rows("invoices") |
| 1076 | if invoice["number"].startswith(f"SUB-{subscription_id[:8]}-") |
| 1077 | and invoice["number"].endswith("-ADV")] |
| 1078 | |
| 1079 | |
| 1080 | def test_m10_the_biller_bills_a_closed_period_once_and_a_rerun_is_a_no_op(env): |
| 1081 | """The control for everything below: a healthy pass raises one 49.00 |
| 1082 | invoice for June and advances; running it again raises nothing.""" |
| 1083 | _billing(env) |
| 1084 | _subscribe(env, "sub-a") |
| 1085 | first = env.run("system_billing_runner", today="2026-07-01") |
| 1086 | # June's base fee, late but in advance, then the close (July's base). |
| 1087 | assert (first["invoiced"], first["advanced"]) == (2, 1) |
| 1088 | assert _period(env, "sub-a") == ("2026-06-30", "2026-07-30") |
| 1089 | again = env.run("system_billing_runner", today="2026-07-01") |
| 1090 | assert (again["invoiced"], again["advanced"]) == (0, 0) |
| 1091 | assert _subscription_invoices(env, "sub-a") == [("SUB-sub-a-2026-06", 4900)] |
| 1092 | assert _advance_invoices(env, "sub-a") == [("SUB-sub-a-2026-06-ADV", 4900)] |
| 1093 | |
| 1094 | |
| 1095 | def test_m10_an_unreadable_plan_does_not_consume_the_billing_period(env): |
| 1096 | _billing(env) |
| 1097 | _subscribe(env, "sub-a") |
| 1098 | with _unreadable(env.monkeypatch, "billing_plans"): |
| 1099 | during = env.run("system_billing_runner", today="2026-07-01") |
| 1100 | # The unreadable pass used to answer "nothing to bill for this period" |
| 1101 | # (and advance); now it says it could not look and leaves June open. |
| 1102 | assert during["results"] == [ |
| 1103 | {"subscription": "sub-a", |
| 1104 | "error": "billing_plans unreadable; period left open for the next pass", |
| 1105 | "retry": True}] |
| 1106 | assert _period(env, "sub-a") == ("2026-06-01", "2026-06-30") |
| 1107 | |
| 1108 | env.run("system_billing_runner", today="2026-07-01") |
| 1109 | expect(_subscription_invoices(env, "sub-a"), [("SUB-sub-a-2026-06", 4900)], |
| 1110 | "June invoices once the plan was readable again (subscription " |
| 1111 | f"period is now {_period(env, 'sub-a')})") |
| 1112 | |
| 1113 | |
| 1114 | def test_m10_a_deleted_plan_does_not_consume_the_billing_period(env): |
| 1115 | """REFUTED for the deleted-plan case when found: the period was NOT |
| 1116 | consumed, but only because the schema rejected the biller's own |
| 1117 | advancing update (subscriptions.plan_id is a relation), and that |
| 1118 | rejection aborted the whole pass. Since the M10 fix the biller itself |
| 1119 | refuses to advance a subscription whose plan is gone and reports it, |
| 1120 | so the pass completes and the subscription stays on June.""" |
| 1121 | _billing(env) |
| 1122 | _subscribe(env, "sub-a") |
| 1123 | status, body = env.http("DELETE", "/collections/billing_plans/records/plan-pro") |
| 1124 | assert status == 200, body |
| 1125 | |
| 1126 | result = env.execute("system_billing_runner", today="2026-07-01") |
| 1127 | assert result.ok, result.error |
| 1128 | assert result.result["results"] == [{ |
| 1129 | "subscription": "sub-a", |
| 1130 | "error": "plan 'plan-pro' not found; period left open until the " |
| 1131 | "subscription names a plan that exists"}] |
| 1132 | assert _period(env, "sub-a") == ("2026-06-01", "2026-06-30") |
| 1133 | assert env.rows("invoices") == [] |
| 1134 | |
| 1135 | |
| 1136 | def test_m10_one_subscription_with_a_deleted_plan_does_not_stop_the_others_being_billed(env): |
| 1137 | _billing(env) |
| 1138 | _plan(env, "plan-old") |
| 1139 | _subscribe(env, "sub-a", plan_id="plan-old") |
| 1140 | _subscribe(env, "sub-b") |
| 1141 | object_records.delete_collection_record( |
| 1142 | "billing_plans", "plan-old", base_dir=env.data_dir) |
| 1143 | |
| 1144 | result = env.execute("system_billing_runner", today="2026-07-01") |
| 1145 | if not result.ok: |
| 1146 | assert ("Record field 'plan_id' references a missing record: " |
| 1147 | "billing_plans/plan-old") in result.error.message |
| 1148 | expect(_subscription_invoices(env, "sub-b"), [("SUB-sub-b-2026-06", 4900)], |
| 1149 | "June invoices for the healthy subscription behind the broken one " |
| 1150 | f"(pass ok={result.ok})") |
| 1151 | |
| 1152 | |
| 1153 | def test_m10_unreadable_invoices_are_not_read_as_already_invoiced(env): |
| 1154 | """"Cannot tell -> do not risk a second invoice" is the right instinct |
| 1155 | for the invoice. It is the wrong one for the period: advancing past a |
| 1156 | month on the strength of "I could not look" loses that month's 49.00.""" |
| 1157 | _billing(env) |
| 1158 | _subscribe(env, "sub-a") |
| 1159 | with _unreadable(env.monkeypatch, "invoices"): |
| 1160 | during = env.run("system_billing_runner", today="2026-07-01") |
| 1161 | # The unreadable pass used to answer "already invoiced" (and advance); |
| 1162 | # now it says it could not look and leaves June open. |
| 1163 | assert during["results"] == [ |
| 1164 | {"subscription": "sub-a", |
| 1165 | "error": "invoices unreadable; the period's base fee was not billed in " |
| 1166 | "advance, left for the next pass", "retry": True}, |
| 1167 | {"subscription": "sub-a", |
| 1168 | "error": "invoices unreadable; not risking a second invoice, " |
| 1169 | "period left open for the next pass", |
| 1170 | "marker": "subscriptions/sub-a:2026-06-01", "retry": True}] |
| 1171 | assert _period(env, "sub-a") == ("2026-06-01", "2026-06-30") |
| 1172 | assert env.rows("invoices") == [] |
| 1173 | |
| 1174 | env.run("system_billing_runner", today="2026-07-01") |
| 1175 | expect(_subscription_invoices(env, "sub-a"), [("SUB-sub-a-2026-06", 4900)], |
| 1176 | "June invoices once the invoices collection was readable again " |
| 1177 | f"(subscription period is now {_period(env, 'sub-a')})") |
| 1178 | |
| 1179 | |
| 1180 | def test_m10_editing_an_invoice_note_does_not_allow_the_period_to_be_billed_twice(env): |
| 1181 | """The docstring's promise is "a biller that runs twice, or is re-run |
| 1182 | after a crash, cannot double-bill". The crash is staged by putting the |
| 1183 | subscription back on the period it had already invoiced (the invoice |
| 1184 | was written, the advance was not). With the note untouched the re-run |
| 1185 | is a no-op; after an ordinary PUT replaces the note it is a second bill.""" |
| 1186 | _billing(env) |
| 1187 | _subscribe(env, "sub-a") |
| 1188 | env.run("system_billing_runner", today="2026-07-01") |
| 1189 | assert _subscription_invoices(env, "sub-a") == [("SUB-sub-a-2026-06", 4900)] |
| 1190 | invoice = next(row for row in env.rows("invoices") if not row["number"].endswith("-ADV")) |
| 1191 | assert invoice["notes"] == ( |
| 1192 | "Generated by system_billing_runner [subscriptions/sub-a:2026-06-01]") |
| 1193 | |
| 1194 | def rerun_june(): |
| 1195 | env.update("subscriptions", "sub-a", { |
| 1196 | "current_period_start": "2026-06-01", |
| 1197 | "current_period_end": "2026-06-30"}) |
| 1198 | return env.run("system_billing_runner", today="2026-07-01") |
| 1199 | |
| 1200 | assert rerun_june()["invoiced"] == 0 |
| 1201 | assert _subscription_invoices(env, "sub-a") == [("SUB-sub-a-2026-06", 4900)] |
| 1202 | |
| 1203 | status, body = env.http("PUT", f"/collections/invoices/records/{invoice['id']}", |
| 1204 | {"notes": "Thanks for your business. Net 14."}) |
| 1205 | assert status == 200, body |
| 1206 | rerun_june() |
| 1207 | expect(_subscription_invoices(env, "sub-a"), [("SUB-sub-a-2026-06", 4900)], |
| 1208 | "invoices for June after the first one's note was edited and the " |
| 1209 | "period re-run") |
| 1210 | |
| 1211 | |
| 1212 | def _usage_event(env, event_id, quantity, occurred_at, subscription_id="sub-u"): |
| 1213 | env.create("usage_events", { |
| 1214 | "id": event_id, "event_id": event_id, "subscription_id": subscription_id, |
| 1215 | "metric": "api_calls", "quantity": str(quantity), |
| 1216 | "occurred_at": occurred_at, "owner_id": "dan"}) |
| 1217 | |
| 1218 | |
| 1219 | def _usage_summaries(env): |
| 1220 | return sorted((row["period_start"], row["period_end"], row["quantity"], |
| 1221 | row["event_count"]) for row in env.rows("usage_summaries")) |
| 1222 | |
| 1223 | |
| 1224 | def test_m11_a_crash_between_the_summary_write_and_the_rated_marks_does_not_double_count(env): |
| 1225 | """The docstring claims "a re-run after a crash adds nothing twice". |
| 1226 | The crash is one OSError on the first `rated=true` write, after the |
| 1227 | summary has already been written.""" |
| 1228 | _billing(env) |
| 1229 | _subscribe(env, "sub-u", start="2026-07-01", end="2026-07-31") |
| 1230 | _usage_event(env, "e1", 7, "2026-07-04T10:00:00Z") |
| 1231 | _usage_event(env, "e2", 9, "2026-07-04T11:00:00Z") |
| 1232 | |
| 1233 | original = object_records.update_collection_record |
| 1234 | state = {"crashed": False} |
| 1235 | |
| 1236 | def killed_once(collection, *args, **kwargs): |
| 1237 | if collection == "usage_events" and not state["crashed"]: |
| 1238 | state["crashed"] = True |
| 1239 | raise OSError("process killed") |
| 1240 | return original(collection, *args, **kwargs) |
| 1241 | |
| 1242 | with env.monkeypatch.context() as patcher: |
| 1243 | patcher.setattr(object_records, "update_collection_record", killed_once) |
| 1244 | crashed = env.execute("system_usage_rollup", today="2026-07-05") |
| 1245 | assert not crashed.ok and "OSError: process killed" in crashed.error.message |
| 1246 | assert _usage_summaries(env) == [("2026-07-01", "2026-07-31", "16", "2")] |
| 1247 | assert [event["rated"] for event in env.rows("usage_events")] == ["false", "false"] |
| 1248 | |
| 1249 | env.run("system_usage_rollup", today="2026-07-05") |
| 1250 | expect(_usage_summaries(env), [("2026-07-01", "2026-07-31", "16", "2")], |
| 1251 | "usage summaries for 7 + 9 calls after a crashed pass and a clean re-run") |
| 1252 | |
| 1253 | |
| 1254 | def test_m11_a_crash_then_the_period_closing_before_the_rerun_still_counts_once(env): |
| 1255 | """The same crash, but the biller runs before the next fold: it bills |
| 1256 | July from the summary that already counted the two unmarked events and |
| 1257 | advances to August. The re-run then finds the events still unrated in |
| 1258 | August's period -- and must not count them again there, because the |
| 1259 | July summary (now invoiced) already holds them.""" |
| 1260 | _billing(env) |
| 1261 | _subscribe(env, "sub-u", start="2026-07-01", end="2026-07-31") |
| 1262 | _usage_event(env, "e1", 7, "2026-07-04T10:00:00Z") |
| 1263 | _usage_event(env, "e2", 9, "2026-07-04T11:00:00Z") |
| 1264 | |
| 1265 | original = object_records.update_collection_record |
| 1266 | state = {"crashed": False} |
| 1267 | |
| 1268 | def killed_once(collection, *args, **kwargs): |
| 1269 | if collection == "usage_events" and not state["crashed"]: |
| 1270 | state["crashed"] = True |
| 1271 | raise OSError("process killed") |
| 1272 | return original(collection, *args, **kwargs) |
| 1273 | |
| 1274 | with env.monkeypatch.context() as patcher: |
| 1275 | patcher.setattr(object_records, "update_collection_record", killed_once) |
| 1276 | assert not env.execute("system_usage_rollup", today="2026-07-05").ok |
| 1277 | billed = env.run("system_billing_runner", today="2026-07-31") |
| 1278 | assert billed["advanced"] == 1 |
| 1279 | assert _period(env, "sub-u") == ("2026-07-31", "2026-08-31") |
| 1280 | |
| 1281 | env.run("system_usage_rollup", today="2026-08-01") |
| 1282 | assert [event["rated"] for event in env.rows("usage_events")] == ["true", "true"] |
| 1283 | expect(sorted((row[0], row[2], row[3]) for row in _usage_summaries(env) |
| 1284 | if row[2] != "0"), |
| 1285 | [("2026-07-01", "16", "2")], |
| 1286 | "non-empty usage summaries after a crash, a period close and a re-run") |
| 1287 | |
| 1288 | |
| 1289 | def test_m11_usage_is_bucketed_by_when_it_occurred_not_by_the_current_period(env): |
| 1290 | """100 calls happened on 29 June; the subscription's period then rolled |
| 1291 | to July before the fold ran. The module docstring describes exactly |
| 1292 | this behaviour, so whether to change it is an owner decision -- but the |
| 1293 | July bucket claiming June's usage moves overage between periods, which |
| 1294 | changes what a customer with an included allowance is charged.""" |
| 1295 | _billing(env) |
| 1296 | _subscribe(env, "sub-u", start="2026-07-01", end="2026-07-31") |
| 1297 | _usage_event(env, "june", 100, "2026-06-29T23:00:00Z") |
| 1298 | _usage_event(env, "july", 5, "2026-07-02T10:00:00Z") |
| 1299 | |
| 1300 | folded = env.run("system_usage_rollup", today="2026-07-03") |
| 1301 | assert folded["events_folded"] == 2 |
| 1302 | july = [row for row in _usage_summaries(env) if row[0] == "2026-07-01"] |
| 1303 | expect(july, [("2026-07-01", "2026-07-31", "5", "1")], |
| 1304 | "the July usage bucket after folding one June and one July event") |
| 1305 | |
| 1306 | |
| 1307 | # =========================================================================== |
| 1308 | # The Stripe webhook (M6) |
| 1309 | # =========================================================================== |
| 1310 | |
| 1311 | STRIPE_WEBHOOK_SECRET = "whsec_findings_test" |
| 1312 | |
| 1313 | |
| 1314 | def _no_network(*args, **kwargs): |
| 1315 | raise AssertionError("a test tried to open a network connection") |
| 1316 | |
| 1317 | |
| 1318 | def _stripe(env): |
| 1319 | # Nothing on the webhook path calls out, and it must stay that way in |
| 1320 | # a test: every route to a socket is stubbed BEFORE the object runs. |
| 1321 | env.monkeypatch.setattr(object_stripe, "_default_transport", _no_network) |
| 1322 | env.monkeypatch.setattr(urllib.request.OpenerDirector, "open", _no_network) |
| 1323 | env.monkeypatch.setattr(socket.socket, "connect", _no_network) |
| 1324 | env.install("app-settings", "app-invoices", "app-payments") |
| 1325 | env.monkeypatch.setenv("DBBASIC_STRIPE_SECRET_KEY", "sk_test_findings") |
| 1326 | env.monkeypatch.setenv("DBBASIC_STRIPE_WEBHOOK_SECRET", STRIPE_WEBHOOK_SECRET) |
| 1327 | env.create("invoices", { |
| 1328 | "id": "inv-1", "number": "INV-1", "customer_name": "Grace Ltd", |
| 1329 | "status": "sent", "currency": "USD", "issue_date": "2026-07-01", |
| 1330 | "due_date": "2026-07-31", "subtotal_cents": "250000", |
| 1331 | "total_cents": "250000", "owner_id": "dan"}) |
| 1332 | |
| 1333 | |
| 1334 | def _stripe_event(env, event_id, *, amount=250000, **session_fields): |
| 1335 | """Hand one locally signed checkout.session.completed to the webhook |
| 1336 | object, exactly as the raw-body endpoint would. No network anywhere.""" |
| 1337 | session = {"id": "cs_1", "amount_total": amount, |
| 1338 | "metadata": {"invoice_id": "inv-1"}} |
| 1339 | session.update(session_fields) |
| 1340 | raw = json.dumps({"id": event_id, "type": "checkout.session.completed", |
| 1341 | "created": 1785000000, |
| 1342 | "data": {"object": session}}).encode() |
| 1343 | stamp = int(time.time()) |
| 1344 | mac = hmac.new(STRIPE_WEBHOOK_SECRET.encode(), f"{stamp}.".encode() + raw, |
| 1345 | hashlib.sha256).hexdigest() |
| 1346 | return env.run("webhook_stripe", _raw_body=raw.decode(), |
| 1347 | _headers={"stripe-signature": f"t={stamp},v1={mac}"}) |
| 1348 | |
| 1349 | |
| 1350 | def _stripe_payments(env): |
| 1351 | return [(row["amount_cents"], row["status"], row["reference"]) |
| 1352 | for row in env.rows("payments")] |
| 1353 | |
| 1354 | |
| 1355 | def test_m6_a_paid_usd_session_records_one_payment(env): |
| 1356 | """The control: the staged event is a valid one, so the three xfails |
| 1357 | below fail for the field they vary and not for the signature.""" |
| 1358 | _stripe(env) |
| 1359 | result = _stripe_event(env, "evt_ok", payment_status="paid", currency="usd") |
| 1360 | assert result["status"] == 200 and result["amount_cents"] == 250000 |
| 1361 | assert _stripe_payments(env) == [("250000", "received", "evt_ok cs_1")] |
| 1362 | assert _stripe_event(env, "evt_ok", payment_status="paid")["duplicate"] == "evt_ok" |
| 1363 | assert len(env.rows("payments")) == 1 |
| 1364 | |
| 1365 | |
| 1366 | def test_m6_unreadable_payments_do_not_acknowledge_the_event_as_a_duplicate(env): |
| 1367 | """The webhook's own contract: 2xx for handled and deliberately ignored |
| 1368 | events, because anything else makes Stripe redeliver. An event it could |
| 1369 | not check is neither -- it needs the redelivery.""" |
| 1370 | _stripe(env) |
| 1371 | with _unreadable(env.monkeypatch, "payments"): |
| 1372 | result = _stripe_event(env, "evt_1", payment_status="paid", currency="usd") |
| 1373 | assert env.rows("payments") == [] |
| 1374 | if 200 <= result["status"] < 300: |
| 1375 | reproduced("the webhook acknowledged an event it recorded nothing for: " |
| 1376 | f"{result}") |
| 1377 | |
| 1378 | |
| 1379 | def test_m6_an_unpaid_checkout_session_records_no_received_payment(env): |
| 1380 | """Stripe sends checkout.session.completed with payment_status "unpaid" |
| 1381 | for delayed methods (bank debits, vouchers); the money, if it ever |
| 1382 | arrives, is announced by checkout.session.async_payment_succeeded. |
| 1383 | Reachable only if such a method is enabled on the Stripe account.""" |
| 1384 | _stripe(env) |
| 1385 | result = _stripe_event(env, "evt_2", payment_status="unpaid", currency="usd") |
| 1386 | assert result["status"] == 200 |
| 1387 | expect(_stripe_payments(env), [], |
| 1388 | "payments recorded for a session whose payment_status is 'unpaid'") |
| 1389 | |
| 1390 | |
| 1391 | def test_m6_a_session_in_another_currency_is_not_recorded_as_invoice_cents(env): |
| 1392 | _stripe(env) |
| 1393 | result = _stripe_event(env, "evt_3", amount=2500, payment_status="paid", |
| 1394 | currency="jpy") |
| 1395 | assert result["status"] == 200 |
| 1396 | assert env.get("invoices", "inv-1")["currency"] == "USD" |
| 1397 | expect(_stripe_payments(env), [], |
| 1398 | "payments recorded on a USD invoice for a JPY checkout session") |
| 1399 | |
| 1400 | |
| 1401 | # =========================================================================== |
| 1402 | # Formulas and rollups parse money as float (P1) |
| 1403 | # =========================================================================== |
| 1404 | |
| 1405 | def test_p1_an_integer_cents_formula_stores_a_whole_number_of_cents(): |
| 1406 | """No shipped schema divides today, which is the only reason this has |
| 1407 | not been seen: the formula language has no way to write the floor/round |
| 1408 | every totals fold needs (doctrine #10). Floor gives 101, half-up 102; |
| 1409 | either is a decision, '101.805' is neither.""" |
| 1410 | stored = object_computed.evaluate_formula( |
| 1411 | "amount_cents * rate_bps / 10000", |
| 1412 | {"amount_cents": "1234", "rate_bps": "825"}) |
| 1413 | expect(stored in ("101", "102"), True, |
| 1414 | f"1234 * 825 / 10000 stored as a whole number of cents (got {stored!r})") |
| 1415 | |
| 1416 | |
| 1417 | def test_p1_a_shipped_formula_keeps_every_digit_of_a_large_integer(env): |
| 1418 | """Out of reach for USD cents; in reach for any denomination with a |
| 1419 | large scale, and "Python ints are unbounded" is the stated reason for |
| 1420 | choosing integer minor units (logic-decisions #10).""" |
| 1421 | env.install("app-settings", "app-invoices", "app-payments") |
| 1422 | total = 2 ** 53 + 1 |
| 1423 | _invoice(env, "inv-big", total=str(total)) |
| 1424 | invoice = env.get("invoices", "inv-big") |
| 1425 | assert invoice["total_cents"] == "9007199254740993" |
| 1426 | expect(invoice["balance_due_cents"], "9007199254740993", |
| 1427 | "balance_due_cents of an unpaid invoice whose total is 2**53 + 1") |
| 1428 | |
| 1429 | |
| 1430 | def test_p1_a_wallet_balance_rollup_is_exact_above_two_to_the_53(env): |
| 1431 | """ETH is a seeded denomination with scale 18, so one whole unit |
| 1432 | (10**18) is already past 2**53. The balance is derived, never stored |
| 1433 | by hand -- and the derivation is wrong from the first deposit.""" |
| 1434 | env.install(*BILLING_PACKAGES) |
| 1435 | assert env.get("denominations", "den-eth")["scale"] == "18" |
| 1436 | env.create("wallets", {"id": "w1", "kind": "balance", |
| 1437 | "denomination_id": "den-eth", "owner_id": "dan"}) |
| 1438 | env.create("wallet_entries", { |
| 1439 | "id": "we1", "wallet_id": "w1", "amount_minor": str(10 ** 18 + 1), |
| 1440 | "kind": "topup", "reference": "deposit", "owner_id": "dan"}) |
| 1441 | assert env.get("wallet_entries", "we1")["amount_minor"] == "1000000000000000001" |
| 1442 | expect(env.get("wallets", "w1")["balance_minor"], "1000000000000000001", |
| 1443 | "wallets.balance_minor after one entry of 10**18 + 1") |
| 1444 | |
| 1445 | |
| 1446 | # =========================================================================== |
| 1447 | # Platform facts that decide how much of the above is live |
| 1448 | # =========================================================================== |
| 1449 | |
| 1450 | SHIPPED_DEPLOY_FILES = ( |
| 1451 | "scripts/install.sh", "scripts/one-click-install.sh", |
| 1452 | "scripts/docker-entrypoint.sh", "Dockerfile", "docker-compose.yml", |
| 1453 | "cloud-init.yaml", ".env.example", |
| 1454 | ) |
| 1455 | |
| 1456 | |
| 1457 | def test_platform_fact_no_shipped_deploy_file_enables_handlers_or_change_dispatch( |
| 1458 | monkeypatch): |
| 1459 | """FACT (a), checked: both reaction layers are env opt-ins that default |
| 1460 | off (object_handlers.py:34,54-61; object_change_dispatch.py:77,92-106) |
| 1461 | and no deploy file this repository ships sets either flag -- install.sh |
| 1462 | writes its env file at :104-146 without them, one-click-install.sh sets |
| 1463 | only login/enforcement at :100-101. So on a stock install every HANDLES |
| 1464 | object above is inert: M1/M2/M18 cannot fire, and equally no invoice |
| 1465 | flips to paid, no journal composes and no stock moves (see the next |
| 1466 | test). The findings become live on a box whose operator set the flags |
| 1467 | by hand, which the Stripe webhook's docstring tells them to do. |
| 1468 | |
| 1469 | If this test fails because a deploy file now enables a flag, M1 and M2 |
| 1470 | restate every web checkout on a default install: fix those first.""" |
| 1471 | monkeypatch.delenv(object_handlers.HANDLERS_ENABLED_ENV, raising=False) |
| 1472 | monkeypatch.delenv(object_change_dispatch.ENABLE_ENV, raising=False) |
| 1473 | assert object_handlers.HANDLERS_ENABLED_ENV == "DBBASIC_ENABLE_EVENT_HANDLERS" |
| 1474 | assert object_change_dispatch.ENABLE_ENV == "DBBASIC_ENABLE_CHANGE_DISPATCH" |
| 1475 | assert object_handlers.handlers_enabled() is False |
| 1476 | assert object_change_dispatch.change_dispatch_enabled(base_dir=".") is False |
| 1477 | |
| 1478 | mentions = [] |
| 1479 | for relative in SHIPPED_DEPLOY_FILES: |
| 1480 | text = (REPO_ROOT / relative).read_text() |
| 1481 | for flag in ("DBBASIC_ENABLE_EVENT_HANDLERS", "DBBASIC_ENABLE_CHANGE_DISPATCH"): |
| 1482 | if flag in text: |
| 1483 | mentions.append((relative, flag)) |
| 1484 | assert mentions == [] |
| 1485 | |
| 1486 | |
| 1487 | def test_platform_fact_with_stock_flags_a_payment_in_full_leaves_the_invoice_sent(env): |
| 1488 | """The consequence of fact (a), characterised rather than judged: on the |
| 1489 | default flags a payment recorded over the API updates the derived |
| 1490 | balance (rollups and formulas run in the storage layer, no flag) but no |
| 1491 | handler runs, so the status never moves and the replay pass does nothing.""" |
| 1492 | env.install("app-settings", "app-invoices", "app-payments") |
| 1493 | _invoice(env, "inv1") |
| 1494 | _pay_over_http(env, "pay1", "inv1", 2000) |
| 1495 | assert _paid_state(env, "inv1") == ("sent", 2000, 0) |
| 1496 | assert object_change_dispatch.dispatch_pending( |
| 1497 | base_dir=env.data_dir, roots=[env.object_root]) == { |
| 1498 | "processed": 0, "dispatched": 0, "skipped": 0, "errors": 0, "results": []} |
| 1499 | |
| 1500 | env.enable_handlers() |
| 1501 | _invoice(env, "inv2") |
| 1502 | _pay_over_http(env, "pay2", "inv2", 2000) |
| 1503 | assert _paid_state(env, "inv2") == ("paid", 2000, 0) |
| 1504 | |
| 1505 | |
| 1506 | def _lifespan_startup_stderr(capsys): |
| 1507 | """Boot the ASGI app's lifespan once and return what it said on stderr.""" |
| 1508 | async def boot(): |
| 1509 | messages = iter([{"type": "lifespan.startup"}, {"type": "lifespan.shutdown"}]) |
| 1510 | |
| 1511 | async def receive(): |
| 1512 | return next(messages) |
| 1513 | |
| 1514 | async def send(message): |
| 1515 | pass |
| 1516 | |
| 1517 | await object_server.app({"type": "lifespan"}, receive, send) |
| 1518 | |
| 1519 | capsys.readouterr() |
| 1520 | asyncio.run(boot()) |
| 1521 | return capsys.readouterr().err |
| 1522 | |
| 1523 | |
| 1524 | def test_platform_inert_handlers_are_named_at_boot_and_in_daemon_status(env, capsys): |
| 1525 | """event-handlers-off-on-a-stock-install, made visible. The flags keep |
| 1526 | their default (off) -- turning reactions on is the operator's call -- |
| 1527 | but a box whose installed packages declare handlers that cannot run now |
| 1528 | says so by name: in the server's startup log and in /daemon/status |
| 1529 | (daemon.reactions), instead of an invoice that silently never flips.""" |
| 1530 | env.install("app-settings", "app-invoices", "app-payments") |
| 1531 | assert object_handlers.handlers_enabled() is False |
| 1532 | assert object_change_dispatch.change_dispatch_enabled(base_dir=env.data_dir) is False |
| 1533 | |
| 1534 | reactions = object_daemon_status.reactions_status( |
| 1535 | base_dir=env.data_dir, object_roots=[env.object_root]) |
| 1536 | assert reactions["status"] == "degraded" |
| 1537 | inert = next(p for p in reactions["problems"] if p["id"] == "handlers_inert") |
| 1538 | assert "system_invoice_status" in inert["impact"] |
| 1539 | assert "DBBASIC_ENABLE_CHANGE_DISPATCH" in inert["fix"] |
| 1540 | |
| 1541 | err = _lifespan_startup_stderr(capsys) |
| 1542 | assert "Reactions NOT RUNNING (handlers_inert)" in err |
| 1543 | assert "system_invoice_status" in err |
| 1544 | |
| 1545 | status, payload = env.http("GET", "/daemon/status") |
| 1546 | assert status == 200 |
| 1547 | assert "handlers_inert" in [p["id"] for p in payload["daemon"]["reactions"]["problems"]] |
| 1548 | |
| 1549 | # app-invoices also installs cron schedules (invoice aging); whether |
| 1550 | # croniter is present is this machine's business, so it is set aside |
| 1551 | # here and pinned by the croniter tests below. |
| 1552 | def ids(**kwargs): |
| 1553 | return [p["id"] for p in object_daemon_status.reactions_status( |
| 1554 | base_dir=env.data_dir, object_roots=[env.object_root], **kwargs)["problems"] |
| 1555 | if p["id"] != "cron_needs_croniter"] |
| 1556 | |
| 1557 | # HTTP handlers on, replay off: storage-level writes still reach nothing. |
| 1558 | env.enable_handlers() |
| 1559 | assert ids() == ["storage_writes_unreacted", "daemon_not_running"] |
| 1560 | |
| 1561 | # Both on, but no daemon has run: the replay (and the schedules) never happen. |
| 1562 | env.monkeypatch.setenv(object_change_dispatch.ENABLE_ENV, "true") |
| 1563 | assert ids() == ["daemon_not_running"] |
| 1564 | |
| 1565 | # A live daemon heartbeat clears it; a stale one does not. |
| 1566 | object_daemon._last_beat = 0.0 |
| 1567 | object_daemon._beat(env.data_dir) |
| 1568 | assert ids() == [] |
| 1569 | later = int(time.time()) + object_daemon_status.DAEMON_STALE_AFTER_SECONDS + 5 |
| 1570 | assert ids(now=later) == ["daemon_not_running"] |
| 1571 | |
| 1572 | |
| 1573 | def test_platform_croniter_is_declared_where_a_stock_install_would_get_it(): |
| 1574 | """FACT (b), checked: `dependencies = []` and the dev/test/server extras |
| 1575 | (pyproject.toml:36-52) never name croniter; scripts/install.sh:91 runs |
| 1576 | `pip install -e .[server]`; the Dockerfile installs uvicorn and |
| 1577 | websockets (:26-32). The 15 schedules packages declare are all cron.""" |
| 1578 | text = (REPO_ROOT / "pyproject.toml").read_text() |
| 1579 | project = text.split("[project.urls]")[0] |
| 1580 | expect("croniter" in project, True, |
| 1581 | "pyproject.toml names croniter in dependencies or an extra") |
| 1582 | |
| 1583 | |
| 1584 | def _scheduler_objects(tmp_path, monkeypatch): |
| 1585 | objects_dir = tmp_path / "objects" |
| 1586 | (objects_dir / "triggers").mkdir(parents=True) |
| 1587 | (objects_dir / "triggers" / "scheduler.py").write_text( |
| 1588 | "def POST(request):\n return {'ok': True}\n") |
| 1589 | (objects_dir / "system").mkdir() |
| 1590 | marker = ("import os\n" |
| 1591 | "def _mark(name):\n" |
| 1592 | " path = os.environ['DBBASIC_DATA_DIR'] + '/ran.txt'\n" |
| 1593 | " with open(path, 'a') as handle:\n" |
| 1594 | " handle.write(name + '\\n')\n") |
| 1595 | (objects_dir / "system" / "post_only.py").write_text( |
| 1596 | marker + "def POST(request):\n _mark('post_only.POST')\n return {'ok': True}\n") |
| 1597 | (objects_dir / "system" / "event_only.py").write_text( |
| 1598 | marker + "def EVENT(request):\n _mark('event_only.EVENT')\n return {'ok': True}\n") |
| 1599 | data_dir = tmp_path / "data" |
| 1600 | data_dir.mkdir() |
| 1601 | monkeypatch.setenv("DBBASIC_OBJECTS_DIR", str(objects_dir)) |
| 1602 | monkeypatch.setenv("DBBASIC_DATA_DIR", str(data_dir)) |
| 1603 | monkeypatch.delenv("DBBASIC_OVERRIDES_DIR", raising=False) |
| 1604 | return objects_dir, data_dir |
| 1605 | |
| 1606 | |
| 1607 | def _scheduler_state(objects_dir): |
| 1608 | runtime = python_object_runtime.PythonObjectRuntime() |
| 1609 | scheduler = runtime.load_object(objects_dir / "triggers" / "scheduler.py") |
| 1610 | scheduler.state_manager.reload() |
| 1611 | return scheduler.state_manager |
| 1612 | |
| 1613 | |
| 1614 | def test_platform_fact_without_croniter_a_cron_task_is_never_scheduled_and_never_runs( |
| 1615 | tmp_path, monkeypatch): |
| 1616 | """FACT (b), behaviour: with croniter absent (which is what a stock |
| 1617 | install has; it is absent from this test environment too) |
| 1618 | _calculate_next_run returns None for a cron task (object_daemon.py: |
| 1619 | 246-251) and process_scheduler `continue`s past it. That part is |
| 1620 | still true -- the task cannot run without croniter. What changed is |
| 1621 | that it is no longer SILENT: the reason is recorded on the task, logged |
| 1622 | as an ERROR once per daemon process, and reported by /daemon/status |
| 1623 | (daemon.reactions, problem cron_needs_croniter). It used to leave no |
| 1624 | trace but one boot line.""" |
| 1625 | objects_dir, data_dir = _scheduler_objects(tmp_path, monkeypatch) |
| 1626 | monkeypatch.setattr(object_daemon, "croniter", None) |
| 1627 | monkeypatch.setattr(object_daemon, "_REPORTED_UNSCHEDULABLE", set()) |
| 1628 | import importlib.util |
| 1629 | real_find_spec = importlib.util.find_spec |
| 1630 | monkeypatch.setattr(importlib.util, "find_spec", |
| 1631 | lambda name, *a, **k: None if name == "croniter" |
| 1632 | else real_find_spec(name, *a, **k)) |
| 1633 | task = {"id": "aging", "object_id": "system_post_only", "method": "POST", |
| 1634 | "payload": {}, "schedule": "* * * * *", "type": "cron", |
| 1635 | "status": "active"} |
| 1636 | _scheduler_state(objects_dir).set("task_aging", json.dumps(task)) |
| 1637 | |
| 1638 | assert object_daemon._calculate_next_run(task) is None |
| 1639 | object_daemon.process_scheduler(python_object_runtime.PythonObjectRuntime()) |
| 1640 | |
| 1641 | after = json.loads(_scheduler_state(objects_dir).get("task_aging")) |
| 1642 | assert after.get("next_run") is None |
| 1643 | assert after.get("run_count", 0) == 0 |
| 1644 | assert not (data_dir / "ran.txt").exists() |
| 1645 | assert "croniter is not installed" in after["error"] |
| 1646 | |
| 1647 | reactions = object_daemon_status.reactions_status( |
| 1648 | base_dir=data_dir, object_roots=[objects_dir]) |
| 1649 | assert reactions["status"] == "degraded" |
| 1650 | problems = {problem["id"]: problem for problem in reactions["problems"]} |
| 1651 | assert "aging" in problems["cron_needs_croniter"]["impact"] |
| 1652 | assert "daemon_not_running" in problems |
| 1653 | |
| 1654 | |
| 1655 | def test_platform_fact_the_scheduler_calls_the_tasks_method_which_defaults_to_post( |
| 1656 | tmp_path, monkeypatch): |
| 1657 | """FACT (c), checked: AGENTS.md section 3 says "the change dispatcher |
| 1658 | and the scheduler call EVENT". The change dispatcher does |
| 1659 | (object_change_dispatch.py:246, object_server.py:13385). The scheduler |
| 1660 | does not: it calls task.get('method', 'POST') (object_daemon.py:169), |
| 1661 | and a manifest schedule's method defaults to POST |
| 1662 | (object_packages.py:994). An EVENT-only object on a schedule is the one |
| 1663 | that silently never runs; a POST-only one is fine.""" |
| 1664 | objects_dir, data_dir = _scheduler_objects(tmp_path, monkeypatch) |
| 1665 | state = _scheduler_state(objects_dir) |
| 1666 | for name in ("post_only", "event_only"): |
| 1667 | state.set(f"task_{name}", json.dumps({ |
| 1668 | "id": name, "object_id": f"system_{name}", "payload": {}, |
| 1669 | "schedule": "2020-01-01T00:00:00+00:00", "type": "onetime", |
| 1670 | "status": "active"})) # no "method": the default applies |
| 1671 | |
| 1672 | object_daemon.process_scheduler(python_object_runtime.PythonObjectRuntime()) |
| 1673 | |
| 1674 | assert (data_dir / "ran.txt").read_text() == "post_only.POST\n" |
| 1675 | for name in ("post_only", "event_only"): |
| 1676 | task = json.loads(_scheduler_state(objects_dir).get(f"task_{name}")) |
| 1677 | assert (task["status"], task["run_count"]) == ("completed", 1) |
| 1678 | |
| 1679 | |
| 1680 | def test_platform_fact_every_shipped_schedule_targets_an_object_that_defines_its_method(): |
| 1681 | """The reassuring half of fact (c): the doc is wrong but nothing is |
| 1682 | broken by it. Every schedule a package declares names an object in the |
| 1683 | same package that defines the method the scheduler will call (POST for |
| 1684 | every one; none declares another).""" |
| 1685 | checked = [] |
| 1686 | for manifest_path in sorted(PACKAGES_ROOT.glob("*/dbbasic-package.json")): |
| 1687 | manifest = json.loads(manifest_path.read_text()) |
| 1688 | for schedule in manifest.get("schedules", []): |
| 1689 | method = (schedule.get("method") or "POST").upper() |
| 1690 | category, name = schedule["object_id"].split("_", 1) |
| 1691 | source = manifest_path.parent / "objects" / category / f"{name}.py" |
| 1692 | assert source.is_file(), (schedule["id"], source) |
| 1693 | defined = set() |
| 1694 | for node in ast.parse(source.read_text()).body: |
| 1695 | if isinstance(node, ast.FunctionDef): |
| 1696 | defined.add(node.name) |
| 1697 | elif isinstance(node, ast.Assign): |
| 1698 | defined.update(target.id for target in node.targets |
| 1699 | if isinstance(target, ast.Name)) |
| 1700 | assert method in defined, (schedule["id"], schedule["object_id"], method) |
| 1701 | checked.append((schedule["id"], method)) |
| 1702 | assert len(checked) >= 15 # a pin on a pure addition is a test bug |
| 1703 | assert {method for _, method in checked} == {"POST"} |